Solved

C# Array Help/Instruction

Posted on 2014-11-05
4
220 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 33

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

920 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

16 Experts available now in Live!

Get 1:1 Help Now