0

I am having trouble understanding what the for loop is doing.

To me, I see it as:

int i = 0; //Declaring i to become 0. i is the value in myArray?

i < myArray.Length; //When i is less than any value in myArray keep looping?

i++; //Every time this loop goes through increase i by 1?

//Making an array called myArray that contains 20,5,7,2,55
int[] myArray = { 20, 5, 7, 2, 55 };

//Using the built in feature, Array.Sort(); to sort out myArray
Array.Sort(myArray);


for (int i = 0; i < myArray.Length; i++)
{
    Console.WriteLine(myArray[i]);
}
3
  • 5
    do a google search on C# for loop tutorial and start reading.. I would start there first.. it's very straight forward and easy reading Commented Dec 1, 2017 at 22:29
  • i < myArray.Length; is checking for i < number of items in array, not any value in array. In your example i < 5. Commented Dec 1, 2017 at 22:32
  • And now try this: for (int i = myArray.Length-1; i >= 0; i--) Console.WriteLine(myArray[i]); Commented Dec 1, 2017 at 22:34

4 Answers 4

3

I'm going to make some assumptions about your knowledge of programming, so forgive me if this explanation covers topics you're already familiar with, but they are all important for understanding what a for loop does, what it's use is and what the semantics are going to be when someone comes behind you and reads your code. Your question demonstrates that you're super close to understanding it, so hopefully it'll hit you like a ton of bricks once you have a good explanation.

Consider an array of strings of length 5. You would initialize it in C# like so:

string[] arr = new string[5];

What this means is that you have an array that has allocated 5 slots for strings. The names of these slots are the indexes of the array. Unfortunately for those who are new to programming, like yourself, indexes start at 0 (this is called zero-indexing) instead of 1. What that means is that the first slot in our new string[] has the name or index of 0, the second of 1, the third of 3 and so on. That means that they length of the array will always be a number equal to the index of the final slot plus one; to put it another way, because arrays are 0 indexed and the first (1st) slot's index is 0, we know what the index of any given slot is n - 1 where n is what folks who are not programmers (or budding programmers!) would typically consider to be the position of that slot in the array as a whole.

We can use the index to pick out the value from an array in the slot that corresponds to the index. Using your example:

int[] myArray = { 20, 5, 7, 2, 55 };

bool first = myArray[0] == 20: //=> true
bool second = myArray[1] == 5; //=> true
bool third = myArray[2] == 7; //=> true
// and so on...

So you see that the number we are passing into the indexer (MSDN) (the square brackets []) corresponds to the location in the array that we are trying to access.

for loops in C syntax languages (C# being one of them along with C, C++, Java, JavaScript, and several others) generally follow the same convention for the "parameters":

for (index_initializer; condition; index_incrementer)

To understand the intended use of these fields it's important to understand what indexes are. Indexes can be thought of as the names or locations for each of the slots in the array (or list or anything that is list-like).

So, to explain each of the parts of the for loop, lets go through them one by one:

Index Initializer

Because we're going to use the index to access the slots in the array, we need to initialize it to a starting value for our for loop. Everything before the first semicolon in the for loop statement is going to run exactly once before anything else in the for loop is run. We call the variable initialized here the index as it keeps track of the current index we're on in the scope of the for loop's life. It is typical (and therefore good practice) to name this variable i for index with nested loops using the subsequent letters of the Latin alphabet. Like I said, this initializing statement happens exactly once so we assign 0 to i to represent that we want to start looping on the first element of the array.

Condition

The next thing that happens when you declare a for loop is that the condition is checked. This check will be the first thing that is run each time the loop runs and the loop will immediately stop if the check returns false. This condition can be anything as long as it results in a bool. If you have a particularly complicated for loop, you might delegate the condition to a method call:

for (int i = 0; ShouldContinueLooping(i); i++)

In the case of your example, we're checking against the length of the array. What we are saying here from an idiomatic standpoint (and what most folks will expect when they see that as the condition) is that you're going to do something with each of the elements of the array. We only want to continue the loop so long as our i is within the "bounds" of the array, which is always defined as 0 through length - 1. Remember how the last index of an array is equal to its length minus 1? That's important here because the first time this condition is going to be false (that is, i will not be less than the length) is when it is equal to the length of the array and therefore 1 greater than the final slot's index. We need to stop looping because the next part of the for statement increases i by one and would cause us to try to access an index outside the bounds of our array.

Index incrementer

The final part of the for loop is executed once as the last thing that happens each time the loop runs. Your comment for this part is spot on.

To recap the order in which things happen:

  1. Index initializer
  2. Conditional check ("break out" or stop lopping if the check returns false)
  3. Body of loop
  4. Index incrementer
  5. Repeat from step 2

To make this clearer, here's your example with a small addition to make things a little more explicit:

// Making an array called myArray that contains 20,5,7,2,55
int[] myArray = { 20, 5, 7, 2, 55 };

// Using the built in feature, Array.Sort(); to sort out myArray
Array.Sort(myArray);
// Array is now [2, 5, 7, 20, 55]

for (int i = 0; i < myArray.Length; i++)
{
    int currentNumber = myArray[i];
    Console.WriteLine($"Index {i}; Current number {currentNumber}");
}

The output of running this will be:

Index 0; Current number 2
Index 1; Current number 5
Index 2; Current number 7
Index 3; Current number 20
Index 4; Current number 55
Sign up to request clarification or add additional context in comments.

Comments

3

I am having trouble understanding what the for loop is doing.

Then let's take a big step back.

When you see

for (int i = 0; i < myArray.Length; i++)
{
    Console.WriteLine(myArray[i]);
}

what you should mentally think is:

int i = 0;
while (i < myArray.Length)
{
    Console.WriteLine(myArray[i]);
    i++;
}

Now we have rewritten the for in terms of while, which is simpler.

Of course, this requires that you understand "while". We can understand while by again, breaking it down into something simpler. When you see while, think:

int i = 0;
START:
if (i < myArray.Length)
  goto BODY;
else
  goto END;
BODY:
Console.WriteLine(myArray[i]);
i++;
goto START;
END:
// the rest of your program here.

Now we have broken down your loop into its fundamental parts and the control flow is laid bare to your understanding. Walk through it.

We start with i equal to 0. Suppose the length of the array is 3.

Is 0 less than 3? Yes. So we go to BODY next. We write the 0th element of the array and increment i to 1. Now we go back to START.

Is 1 less than 3? Yes. So we go to BODY next. We write the 1th element of the array and increment i to 2. Now we go back to START.

Is 2 less than 3? Yes. So we go to BODY next. We write the 2th element of the array and increment i to 3. Now we go back to START.

Is 3 less than 3? No. So we go to END, and the rest of your program executes.

Now, you probably have noticed that the "goto" form is incredibly ugly and hard to read and reason about. That's why we invented while and for loops, so that you don't have to write awful code that uses gotos. But you can always reason about simple control flow by going back to the goto form mentally.

Comments

2
i < myArray.Length; 

This is not testing against the values inside myArray but against the length (how many items the array contains). Therefore it means: When i is less than the length of the array.

So the loop will keep going, adding 1 to i (as you correctly said) each time it loops, when i is equal to the length of the array, meaning it has gone through all the values, it will exit the loop.

As Nicolás Straub pointed out, i is the index of the array, meaning the location of an item in an array, you have initialised it with the value of 0, this is correct because the first value in an array would have an index of 0.

To directly answer your question about for loops:

A for loop is executing lines of code iteratively (multiple times), the amount depends on its control statement:

for (int i = 0; i < myArray.Length; i++)

For loops are generally pre-condition (the condition to loop is before the code) and have loop counters, being i (i is actually a counter but can be seen as the index because you are going through every element, if you wanted to skip some then i would only be a counter). For is great for when you know how many times you want to loop before you start looping.

1 Comment

also i is the index of the array
0

You are correct in your thinking except as what the others have stated. Think of an array as a sequence of data. You can even use the Reverse() method to apply that to your array. I would research more about arrays so you will understand different things you can do with an array and most importantly if you need to read or write them on the console, in a listbox, or a gridview from the text or csv file.

I suggest you add:

Console.ReadLine();

When you do this the application then will read like this: 2 5 7 20 55

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.