Solved

C# Array Help/Instruction

Posted on 2014-11-05
4
215 Views
Last Modified: 2014-11-06
I'm just asking for some basic C# help. I've just started working with arrays and I'm have trouble wrapping my brain around the logic. For a simple example, this console application takes 10 numbers from the user, stores them in an array with a score of 10, and then prints the sum of those numbers. I'll comment on what I do get (please correct me if I'm wrong), and where I get stopped up.

int[] arr = new int[10];
 // initialize new array and assign it a score of 10
             int sum = 0;
 //declare sum and make it 0
             for (int i = 0; i < 10; i++) 
// creates a for loop, declares i and makes it 0, continues the loop until i is greater than 10, increments i after body
             {
                 Console.WriteLine("Enter Number");
 // asks the user for numbers
                 arr[i] = Convert.ToInt32(Console.ReadLine());
 //takes the numbers, converts them to int, assigns them to arr[i]
                 sum = sum + arr[i];
 // adds the value of sum(0 to start) to the value entered from the user, assigns that to sum
             }

Open in new window


So basically, if "i" is declared in the for loop, and then used as a value for the array, how does "i" stay under 10 to continue the loop? If the user enters 30, that is assigned to the "i" value of arr. As each value is assigned to the "i" value of arr, does it then assign them in sequence to the index scores? 0,1,2,etc automatically?

I hope I'm not talking nonsense here, it always seems way overcomplicated. Basically I'm having trouble understanding how the values are assigned to the array, how the program knows to assign them without index scores given, and how it stays on track with adding the "i" value of arr to the sum, when the "i" value of arr should contain the full set of array numbers right? How is the value "i" in the for loop statements separated from the value of "i" used to assign numbers to the array? Phew.
0
Comment
Question by:DrGangles
4 Comments
 
LVL 14

Accepted Solution

by:
Tchuki earned 375 total points
ID: 40425251
You create an array of type int and declare it to be of size (not score) 10.  This means that the array has 10 indicies which you can think of as holders for ints if it makes things easier.

Each index within the array can be referenced using its index number, remembering that arrays are 0 indexed, not 1 indexed.  So we can access the first index in the array using arr[0], or the fifth index using arr[4].

Your for loop is an iteration statement, it allows code within its body to be executed repeatedly based on the criteria you provide in its definition:
for (initialisation; condition; increment/decrement)

Open in new window


So using your example as a reference
for (int i = 0; i < 10 i++)

Open in new window


Is saying that:
Declare and initialise a variable of type int called i with the value of 0
Whilst the value of i is less than 10 keep looping
On each loop increment the value of i by 1

So basically, if "i" is declared in the for loop, and then used as a value for the array, how does "i" stay under 10 to continue the loop?

After each loop, the value of i is altered in accordance with the increment/decrement part of the for loops definition.  Once that operation has been performed the condition is checked and if it is met, the loop breaks.

If the user enters 30, that is assigned to the "i" value of arr. As each value is assigned to the "i" value of arr, does it then assign them in sequence to the index scores? 0,1,2,etc automatically?

The value of i is used to access that index in the arr array and as the for loop is incrementing the value of i by 1 each time around you have sequential index values and therefore sequential array index accessing.

OK so to clarify further (hopefully):

// create a for loop, start with a value of 0, loop whilst the value is less than 10 and add 1 to the value each iteration
for (int i = 0; i < 10; i++)
{
  //  use the value of i for the current iteration as the value for accessing that array index
  //  so if i equals 0, we will be accessing the first index of the array
  //  if i equals 8 we will be accessing the seventh index of the array etc.
  // save the value input via the console as the value stored in the array at index i
  arr[i] = Convert.ToIn32(Console.ReadLine()); // Note this is bad as will throw an exception if a non number is entered, use Int.TryParse instead

  // add the value saved to the array at index i to the sum variable
  sum = sum + arr[i];
}

Open in new window



Note - Be mindful of your terminology.  Using the correct terms will cause you and others less confusion, especially when attempting to describe non-trivial scenarios.
0
 
LVL 29

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 100 total points
ID: 40425273
First note, not related to the question. Usually comments are written ABOVE the related code. This is just a convention.

The rest is much simpler than you think. Imagine the array as a set of boxes.
You have a set of ten boxes (some space in a memory), on each box you have a number printed (from 0 to 9 in .Net).
You have a friend, aka user. You run your program manually and count from 0 to 9. You friend/user writes
a number on a piece of paper, say, 9. You do the following:
- put this piece of paper (number 9) to the first box
- read this number from a box and add this number to the SUM (which is zero so far)

Then you ask your friend to give the second number/piece of paper. It is, say, 17.
You do the following:
- put this piece of paper (number) to the second box
- read this number from a box and add this number to the SUM (which is 9 so far)

You repeat this sequence 10 times.
What is important:
- really, you do not need the array to count the SUM. Because you just add each new number to the SUM as you go through the loop (same as we count money, for example).
Alternatively, you might have just one variable, say, 'int X', each number from console is assigned to this variable and this variable then added to SUM.

But we may change the scenario. When your friend gives you a number you just put it to a box - that's it!
And you do this 10 times, without adding to the SUM.

Then you go through the boxes (it is another FOR loop), and add all numbers. In this case you have more power because you may tell what number was given at which step. Also, you may get a sum of first five numbers, e.g. Or you may even alter numbers in some boxes. And so on. The drawback - two loops take more time than one :).
0
 
LVL 32

Assisted Solution

by:it_saige
it_saige earned 25 total points
ID: 40425367
I don't know what version of Visual Studio (if you are even using Visual Studio) but here is a great extension to help visualize arrays in VS2010 and above:

https://arrayvisualizer.codeplex.com/

-saige-
0
 

Author Comment

by:DrGangles
ID: 40426166
Whoops, sorry. "Score" was the name of another array i was working on in an example. Also, I definitely understand the value of Int.TryParse. I'm taking a class right now, and that is the example she has been using thus far. Probably just to ram home that the input must be converted to an Int. "save the value input via the console as the value stored in the array at index i" was exactly what I needed to hear Tchuki.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now