CSCI 1301

For Loop

1. Learning Objectives

  • What is a for loop?
  • What does continue do?
  • How do you loop over an array using a for loop?

2. What is for Loop?

Along with while loop, for loop is a second fundamental looping statement in programming. For loops are used to repeat a specific block of code a known number of times, that is, we know in advance how many times the loop will iterate.

When choosing which looping structure to use, determine if you know how many the program is expected to loop. If the answer is yes, for loop is a good statement to use.

3. Syntax

For loop declaration requires specifying looping variables and condition when to terminate as part of the loop declaration.

1// <initializations>; <condition>; <updates>
2for(int i = 0; i < 10; i++){
3 // this loop will iterate 10 times
4 // loop body statements here
5}

The variable initialization section is used to create and initialize an integer variable that indicates the current iteration; in the example above this variable is called i. Initialize this variable with a value where you want to start looping. Typically it will be 0, but the value can be any integer. Note: this variable can only be referred to inside the for loop the scope of the variable is the body of the for loop.

The second part of the for loop declaration is a Boolean expression that determines under which condition to continue looping. The loop will continue until this condition becomes false. Typical usage is to use the variable initialized previously and check that it is less or greater than the number of times to iterate.

  • When iterating over numbers in increasing order, start with smaller number, e.g. i = 0; i < 100;
  • When iterating over numbers in decreasing order, start with larger number, e.g. i = 100; i > 0;

The third part of for loop declaration contains variable updates. Perform either increment or decrement depending on the direction of the loop. When the update is +/- 1 on each iteration, use postfix or prefix operators. To perform an update greater than 1, you can use compound assignment operators, e.g. i += 3 would give an increment of 3 at each iteration.

Pay attention to all 3 parts when setting up a for loop. The declaration must guarantee the loop will eventually terminate. Otherwise you will end up with an infinite loop.

for Loop Examples

4. Keyword continue

Recall break is a keyword that will terminate a loop immediately. You can use it within any looping statement, including a for loop. The example below shows a for loop that should iterate 10 times, but will terminate when i==5 because of the break statement.

1// this loop outputs: 01234
2for(int i = 0; i < 10; i++){
3 if(i == 5){
4 break;
5 }
6 Console.Write(i);
7}

Keyword continue is another keyword we can use inside looping statements. continue keyword will skip the remainder of current iteration and then continue looping at the next iteration. You can observe the difference in the example below that uses continue instead of break.

1// this loop outputs: 012346789
2for(int i = 0; i < 10; i++){
3 if(i == 5){
4 continue;
5 }
6 Console.Write(i);
7}

Using continue in a for loop can be a useful option in situations where the loop should have a fairly constant behavior, but certain iterations should be handled differently.

Example with continue

Display all numbers 0 - 100 but skip iterations 12 and 56.

In this case for loop could be declared as for(int i = 0; i < 101; i++) and inside the loop body use an if statement: if(i == 12 || i == 56) { continue; } to skip the specified iterations. You can see a complete executable program below.

5. Combining Arrays and for Loops

Because arrays are fixed-size data structures, for loops are especially well-suited for working with arrays. Some common operations that can be performed include:

  • initializing array with values
  • traversing an array iterating over each array element
  • searching for occurrence(s) of specific value(s) in an array
  • making copies of arrays

To perform these operations initialize the variable by referring to the array index as the looping condition. In this next example the loop starts from 0 (first index) and ends at the last index of the array.

1char[] letters = {'a', 'b', 'c'};
2
3// display each value in letters array
4for(int i = 0; i < letters.Length; i++){
5 Console.Write(letters[i]);
6}
7
8// outputs: abc

It would have been possible to use condition i < 3 as the looping condition. However, this strategy will cause bugs if the array contents changes. It is better to refer to the array Length property. In the example below, observe how the array length has changed but the for loop declaration is the same:

1char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
2
3for(int i = 0; i < letters.Length; i++){
4 Console.Write(letters[i]);
5}
6
7// outputs: abcdefg

You can then perform other operations with arrays and for loops. This example shows traversing an array backwards and displaying each value stored in the array:


6. Summary

What is a for loop?

for loop is a repetition statement where the iteration start and end conditions are specified in the array declaration.

What does continue do?

continue is a keyword that can be used to skip the remainder of current iteration. Upon encountering this keyword, the code will continue execution of the loop at the next iteration.

How do you loop over an array using a for loop?

Use array index as a loop variable, then perform different operations with the array elements sequentially.