Programs often need to repeat a set of instructions. Manually coding instructions that repeat hundreds or even millions of times would be at best time-consuming and error-prone, or at worst impossible. Programmers may not even know how many times a set of instructions must be repeated!
To handle these situations, we use a ubiquitous programming language mechanism called loops. Here we’ll see two different types of loops: for loops, and while loops.
Loops, Setup
(for running code many times, in succession)
//while loopwhile(/*condition*/){ //your code here! //this runs while the condition is true}//for loopfor(/*initialize*/; /*condition*/; /*increment*/){ //your code here! //this runs while the condition is true}
While Loops
While loops are in some ways, the simpler of the two. Notice that the structure of a while loop resembles another programming structure we’re already familiar with:
//IF STATEMENTif(/*condition*/){ //your code here! //this runs ONCE, if the condition is true}//WHILE LOOPwhile(/*condition*/){ //your code here! //this runs REPEATEDLY, only while the condition is true}
When a while loop is encountered, the condition is checked. If it is true, the code inside the curly braces is executed. This is exactly how an if statement works! However, with a loop the program will jump back to the condition, checking it again, and executing the code in the curly braces if the condition is still true. This process repeats until the condition finally evaluates to false.
This means we’ll almost always need to perform some action in the loop body that affects the loop’s condition, like so:
int i = 10;while(i > 0){ i = i-1; Console.WriteLine("Counter i is now at: " + i);}
Result
The while loop above will run 10 times, printing out the value of the counter from 9 to 0, then ending
For Loops
For loops are slightly more difficult to set up, but offer some great benefits. A for loop has 3 distinct sections: initialization, condition, and modification.
//for loop, this loop runs 10 timesfor(int i = 0; i < 10; ++i){ //your code here!}
The loop above is similar to the last while loop we looked at. In the initialization section we’re creating a new integer variable i, which we’re using to track how many times we’ve looped. The condition section states that the loop will continue to run while i is still less than 10. Finally, we increment the value of i. Our counter is only created when we first encounter the loop; the condition is checked at the beginning of the loop, and the variable modification (incrementing i) happens once the loop body is done.
We could also make our loop condition dependent on a variable, like so:
//Get user input as an integerint x = int.Parse(Console.ReadLine());for(int i = 0; i < x; ++i){ //this loop will run x times!}
Result
The while loop above will run x times, if x is greater than 0.
This is because the condition i < x will be true until i is equal to x.
i starts at 0, goes up by 1 after each loop. and finally becomes x.
When i is equal to x, the loop is finished.
A loop for every season
While loops and for loops are two different flavors of loop, but functionally they can do all of the same things. Which one you use for a particular problem depends on circumstance and preference. But there are some good rules of thumb to follow.
In general, a while loop is used when we’re not certain how many times the loop will run. For instance, many video games will run inside a while loop, and only exit the loop once the player has chosen to quit the game to return to the main menu. There is no way to know beforehand how long the player will be playing the game!
On the other hand, a for loop is more often used when you know how many times the loop will run (even if that number of iterations is stored in a variable). For example, the previous for loop is useful because we can immediately see that it will run x times, just by looking at the loop setup! If we had used a while loop, we would need to track down where i was being manipulated in the loop body, which could be after hundreds of lines of code! And the i counter variable must be created before the loop body, which means additional mental load for us as programmers.
So the rule of thumb would be: use while loops when you do NOT know how many times your loop will run, and use for loops when you DO know how many times your loop will run.
Loops, Examples
//while loop, this loop runs 10 timesint i = 0;while(i < 10){ //your code here! ++i;}//for loop, this loop runs 10 timesfor(int i = 0; i < 10; ++i){ //your code here!}
Result
The while loop above will run 10 times.
This is because the condition i < 10 will be true until i is equal to 10.
i starts at 0, goes up by 1 after each loop. and finally becomes 10.
When i is equal to 10, the loop is finished.
The exact same logic applies to the for loop.
Infinite Loops, Examples
//Loop 1while(true){ Console.WriteLine("This loop will run forever!");}//Loop 2int x = 10;while(x < 20){ Console.WriteLine("This loop will run forever");}//Loop 3for(int i = 100; i > 50; ++i){ Console.WriteLine("This loop will run forever");}
Result
Loop 1: the condition is always true (because it is literally just the value true).
Loop 2: the condition is always true because x is assigned the value 10, and the value of x never changes, so it will always be less than 20.
Loop 3: the condition is always true because i is assigned the value of 100, and is increased by 1 each loop. i will always be greater than 50.
Nested Loops
We can nest loops inside of each other, just like we can with if statements!
for(int j = 0; j < 3; ++j){ for(int k = 0; k < 4; ++k) { Console.WriteLine("j is " + j + ", k is " + k); } Console.WriteLine("Inner loop finished, j is still " + j);}
Output/Result
j is 0, k is 0
j is 0, k is 1
j is 0, k is 2
j is 0, k is 3
Inner loop finished, j is still 0
j is 1, k is 0
j is 1, k is 1
j is 1, k is 2
j is 1, k is 3
Inner loop finished, j is still 1
j is 2, k is 0
j is 2, k is 1
j is 2, k is 2
j is 2, k is 3
Inner loop finished, j is still 2
The outter loop (which increments j) will run 3 times.
The inner loop (which increments k) will run 4 times, on its own.
Since the inner loop is inside of the outter loop, the inner loop will run 12 times (3 times 4).
WARNING
Copying/pasting loop initialization code carelessly can cause HUGE headaches. For example, can you spot the mistake below?
for(int i = 0; i < 3; ++i){ for(int j = 0; j < 4; ++i) { Console.WriteLine("Ooops, big mistake!); }}
In the innermost loop, we’re incrementing i instead of j! This will mess up our loop structure, and our code will behave in strange ways. Ensure that you’re setting up your nested loops correctly!