Iteration, repetition, or looping, they all mean the same thing. When you want to repeat some portion of the program, you will use some form of iteration. Looping is a very common term to describe this. If programs didn't do some kind of iteration, they would all complete in a few seconds.
The while Statement
Whereas the if statement caused statement to be executed exactly once if expression
was true, the while statement causes statement to be executed repeatedly as long as
(a.k.a. while) expression remains true. If expression becomes false, then the repetition stops.
Another way to look at it is:
Simple example:
Tip: If you are running your program from the command prompt and it is stuck
in an infinite loop, pressing Ctrl-C will terminate the program.
The do Statement
Single statement Multiple statements
(braces required)if statement
while ( expression )
statement
while ( expression )
{
statements
}
if ( expression )
{
statements
}
if while do
if ( expression )
statement; // execute 0 or 1 time
while ( expression )
statement; // execute 0 or more times
do
statement; // execute 1 or more times
while ( expression );
Example with output (and a review of expressions). Note that, like the if statement, the braces are only
required with multiple (compound) statements:
int count = 5;
int i = 0;
while (i < count) /* controlling expression */
i++; /* body of the loop */
The output from all 3 examples: (Convince yourself that all 3 loops print the same thing.)
Version #1 (braces required) Version #2 (braces optional) Version #3 (braces optional)
int count = 5;
int i = 0;
while (i < count)
{
i++;
printf("i is %i\n", i);
}
int count = 5;
int i = 0;
while (i < count)
{
printf("i is %i\n", ++i);
}
int count = 5;
int i = 0;
while (i++ < count)
printf("i is %i\n", i);
Bart Simpson could have used C to make his punishment less painful:
i is 1
i is 2
i is 3
i is 4
i is 5
(Partial) output:
int i = 1;
while (i <= 100)
{
printf("I will check the CS 120 Style Guide before submitting code.\n");
i++;
}
Notes:
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
I will check the CS 120 Style Guide before submitting code.
Infinite loop #1 Infinite loop #2 Infinite loop #3
int i = 1;
while (i != 10)
i += 2;
int i = 0;
while (i < 10)
printf("i is %i\n", i);
while (1)
printf("This loop never ends...\n");
Single statement Multiple statements do statement while ( expression ); do { statements } while ( expression );
The primary difference between the while statement and the do statement is that the body of the do statement is guaranteed to execute at least once. This is simply because the controlling expression is executed after the first iteration of the loop body:
Body executes 0 or more times Body executes 1 or more times while ( expression ) statement do statement while ( expression );
Example:
Sample run:int number; int choice; do { printf("Enter a number: "); scanf("%d", &number); printf("You entered %i\n", number); printf("Enter another number? (1=yes,0=no) "); scanf("%d", &choice); } while (choice);
There really isn't much difference between while statement and the do statement. If you need the loop to execute at least once, then the do statement is the one to use.Enter a number: 23 You entered 23 Enter another number? (1=yes,0=no) 1 Enter a number: 10 You entered 10 Enter another number? (1=yes,0=no) 1 Enter a number: 5 You entered 5 Enter another number? (1=yes,0=no) 3 Enter a number: 12 You entered 12 Enter another number? (1=yes,0=no) 0
In computer science, there are 3 general kinds of repetitions regarding the number of repetitions and the technique used:
Technically, the if isn't repeating anything. However, keep these keywords in mind when you have to do something in one of those three ways.
Repetitions Keyword 0 or 1 time if 0 or more times while 1 or more times do...while
The for Statement
Now we get to the most complex of the looping mechanisms: the for statement. The general form is:and the compound version:for ( expression1 ; expression2 ; expression3 ) statement
The meaning of this is a little involved:for ( expression1 ; expression2 ; expression3 ) { statements }
In fact, we can re-write the while pseudocode for it:expression1; while ( expression2 ) { statements expression3; }
Simple examples to print the numbers 1 through 10:
for loop #1 | for loop #2 | while loop |
---|---|---|
int i; for (i = 1; i <= 10; i++) printf("%i\n", i); |
int i; for (i = 0; i < 10; i++) printf("%i\n", i + 1); |
int i = 1; while (i <= 10) printf("%i\n", i++); |
The for loops above show the typical ways in which they are used. The variable i is sometimes called the loop control variable (or simply the counter) because it controls when the loop continues or stops. The three expressions generally do these things:
These are just typical uses of the expressions. You can do practically anything with those expressions.
[1]expression2
[2]statement
[3]expression3
[1]expression2
[2]statement
[3]expression3
[1]expression2
[2]statement
[3]expression3
. . .
[until expression2 is false]
for ( expression1 ; [1]expression2 ; [3]expression3 ) [2]statement
Count to 20 by 2 | Count down from 30 by 3 | Squares of 1 to 10 |
---|---|---|
int i; for (i = 2; i <= 20; i += 2) printf("%i\n", i); 2 4 6 8 10 12 14 16 18 20 |
int i; for (i = 30; i >= 3; i -= 3) printf("%i\n", i); 30 27 24 21 18 15 12 9 6 3 |
int i; for (i = 1; i <= 10; i++) printf("%i\n", i * i); 1 4 9 16 25 36 49 64 81 100 |
Of course, all of these could be written as while loops as well.
Count to 20 by 2 | Count down from 30 by 3 | Squares of 1 to 10 |
---|---|---|
int i = 2; while (i <= 20) { printf("%i\n", i); i += 2; } |
int i = 30; while (i >= 3) { printf("%i\n", i); i -= 3; } |
int i = 1; while (i <= 10) { printf("%i\n", i * i); i++; } |
More on Looping
int i; for (i = 1; i <= 10; i++) printf("%i\n", i); |
→ |
int i = 1; for (; i <= 10;) printf("%i\n", i++); |
Of course, this is nothing but a strange-looking while loop now.
You can even omit the second expression, but this would lead to an infinite loop, since the default empty expression is true!int i = 1; while (i <= 10) printf("%i\n", i++);
If you want to exit from the loop prematurely, you can use the break statement:int i = 1; for (;;) printf("%i\n", i++);
breaking out of infinite for | breaking out of infinite while |
---|---|
int i = 1; for (;;) { printf("%i\n", i++); if (i > 10) break; } |
int i = 1; while (1) { printf("%i\n", i++); if (i > 10) break; } |
The break statement can be used in any of the looping mechanisms as well as the switch statement.
You can also have multiple expressions in between the semicolons separated by commas:
Using a for loop | Using a while loop |
---|---|
int i; int j; for (i = 0, j = 0; i < 16 || j < 3; i +=2, j++) printf("%i * %i = %i\n", i, j, i * j); 0 * 0 = 0 2 * 1 = 2 4 * 2 = 8 6 * 3 = 18 8 * 4 = 32 10 * 5 = 50 12 * 6 = 72 14 * 7 = 98 |
int i = 0; int j = 0; while (i < 16 || j < 3) { printf("%i * %i = %i\n", i, j, i * j); i += 2; j++; } |
Note the use of the comma operator used in the expressions. This operator has the form:
expression1 , expression2 , expression3 , etc...
i = 5; j = 3; c = ++i, ++j, j + i; printf("%i, %i, %i\n", i, j, c); |
i = 5; j = 3; c = (++i), (++j), (j + i); printf("%i, %i, %i\n", i, j, c); |
i = 5; j = 3; c = (++i, ++j, j + i); printf("%i, %i, %i\n",i , j, c); |
The continue statement is similar to the break statement in that it causes the loop to deviate from its prescribed course. The difference is subtle, but very important.
break statement | continue statement |
---|---|
for (/* expressions */) { /* first statement in loop */ /* second statement in loop */ /* etc... */ break; /* last statement in loop */ } [break jumps to here] /* first statement after loop */ |
for (/* expressions */) { /* first statement in loop */ /* second statement in loop */ /* etc... */ continue; /* last statement in loop */ [continue jumps to here] } /* first statement after loop */ |
This prints the even numbers from 2 to 20:
using for | using while | using while |
---|---|---|
for (i = 2; i <= 20; i++) { if ( (i % 2) == 1 ) continue; printf("%i\n", i); } 2 4 6 8 10 12 14 16 18 20 |
i = 2; while (i <= 20) { if ( (i % 2) == 1 ) { i++; continue; } printf("%i\n", i++); } |
i = 2; while (i <= 20) { if ( (i++ % 2) == 1 ) continue; printf("%i\n", i - 1); } |
The break and continue statements are not used all that often inside of a loop, but when you need this behavior, they come in handy.
Nested Loops
Sometimes we need to have one loop inside another. This is very popular when printing a table of some sort. Just as loops are designed to be used with arrays, nested loops are desired for 2-dimensional arrays (e.g. matrices, x-y grid) or any type of data that is represented with rows and columns.For example, printing your multiplication table for the values from 1 to 10 would look something like this:
And the code would look something like this:1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
You will see this a lot if you work with matrices (2-dimensional arrays) where one variable will be traversing the rows of the matrix and the other variable will be traversing the columns of the matrix. Essentially, most of the time that you are dealing with data that has rows and columns, you will be using nested loops.int i, j; for (i = 1; i <= 10; i++) { for (j = 1; j <= 10; j++) printf("%5i", i * j); printf("\n"); }
Sometimes you may even need to have 3 loops nested. Suppose you want to produce a table that shows all combinations of the integers, 1, 2, and 3 as well as the sum of the integers. This would yield 27 (3 * 3 * 3) rows of 3 columns:
This is how you might code it:1,1,1, sum is 3 1,1,2, sum is 4 1,1,3, sum is 5 1,2,1, sum is 4 1,2,2, sum is 5 1,2,3, sum is 6 1,3,1, sum is 5 1,3,2, sum is 6 1,3,3, sum is 7 2,1,1, sum is 4 2,1,2, sum is 5 2,1,3, sum is 6 2,2,1, sum is 5 2,2,2, sum is 6 2,2,3, sum is 7 2,3,1, sum is 6 2,3,2, sum is 7 2,3,3, sum is 8 3,1,1, sum is 5 3,1,2, sum is 6 3,1,3, sum is 7 3,2,1, sum is 6 3,2,2, sum is 7 3,2,3, sum is 8 3,3,1, sum is 7 3,3,2, sum is 8 3,3,3, sum is 9
The break statement is often used in nested loops, when you find that, in an inner loop, you no longer need to keep looping. However, remember that the break statement only breaks out of the current (inner) loop, not all of them. If you want to break all the way out, you need to have some kind of variable (called a flag) that indicates this.int i, j, k; int size = 3; for (i = 1; i <= size; i++) for (j = 1; j <= size; j++) for (k = 1; k <= size; k++) printf("%i,%i,%i\n", i, j, k);
For example, given the code above, supposed we wanted to stop printing results when the sum of the three numbers (i, j, k) is 8. This is an example of how we might do that:
This is the output:void break3a(void) { int i, j, k; /* Loop counters */ int size = 3; /* The max value for each loop */ int target = 8; /* Stop when the sum reaches this number */ int done = 0; /* Flag that indicates to stop looping */ /* Print all combinations until they add up to target */ /* The braces are required for multiple statements */ for (i = 1; i <= size; i++) { for (j = 1; j <= size; j++) { for (k = 1; k <= size; k++) { int sum = i + j + k; /* We want to stop when they add up to target */ printf("%i,%i,%i, sum is %i\n", i, j, k, sum); if (sum == target) { done = 1; /* Need to communicate with the outer loops */ break; } } /* If the numbers add up to target, we're done, otherwise, keep going */ if (done) break; } /* If the numbers add up to target, we're done, otherwise, keep going */ if (done) break; } }
This is another way to achieve the same results:1,1,1, sum is 3 1,1,2, sum is 4 1,1,3, sum is 5 1,2,1, sum is 4 1,2,2, sum is 5 1,2,3, sum is 6 1,3,1, sum is 5 1,3,2, sum is 6 1,3,3, sum is 7 2,1,1, sum is 4 2,1,2, sum is 5 2,1,3, sum is 6 2,2,1, sum is 5 2,2,2, sum is 6 2,2,3, sum is 7 2,3,1, sum is 6 2,3,2, sum is 7 2,3,3, sum is 8
There is a limit to how deeply you can nest the loops, but it's pretty big. It's bigger than what any human could comprehend. Of course, having 100 levels would be impossible for a human (programmer) to understand.void break3b(void) { int i, j, k; /* Loop counters */ int size = 3; /* The max value for each loop */ int target = 8; /* Stop when the sum reaches this number */ int done = 0; /* Flag that indicates to stop looping */ /* Print all combinations until they add up to target */ for (i = 1; i <= size && !done; i++) { for (j = 1; j <= size && !done; j++) { for (k = 1; k <= size && !done; k++) { int sum = i + j + k; /* We want to stop when they add up to target */ printf("%i,%i,%i, sum is %i\n", i, j, k, sum); if (sum == target) done = 1; /* Need to communicate with all of the loops */ } } } }