CSCI 201 Study Aid: Loops

Common uses of loops

The for loop

Version 1 (when the body of the loop is one statement)

for (initialization ; logical expression; update expression) statement1;

Version 2 (when the body of the loop is a block of statements)

for (initialization ; logical expression; update expression) { statement a; // Two or more statements between { }'s statement b; // comprise a block of statements statement c; }

Operators for Performing Shortcuts

Examples

Here are some examples of simple for loops with different loop parameters. In each case notice that the counter variable of the loop is declared in the for statement. In C++ common practice is to declare variables close to their first use, though technically the loop variables could be declared anywhere before the entry into the loop.

 
// Program fragment Output // Loop #1 for(int k = 5; k < 7; ++k) 5 6 cout << k << " "; cout << endl; // Loop #2 for(int k = 50; k <= 56; k = k + 2) 50 52 54 56 cout << k << " "; cout << endl; // Loop #3 for(int k = -5; k < 0; ++k) 5 -4 -3 -2 -1 cout << k << " "; cout << endl;

The while loop

For some problems the number of times the body of a loop would be executed is not known in advance, or depends only on the truth value of a logical expression. In such cases the C++ programmer can use a while loop.

Version 1 (one statement in loop body)

while (logical expression) statement;

Version 2 (more than one statement in loop body)

while (logical expression) { statement a; // Two or more statements between {}'s statement b; // comprise a block of statements statement c; }

A while loop will begin by checking to see if the logical expression is true. It the logical expression is true the body of the loop will be executed, and then the logical expression will be checked again and if the logical expression is true the body of the loop will be executed again. This will continue until the value of the logical expression turns up false, at which time the loop body will not be executed - control will pass to the statement following the while loop.

Example:

   x = 1;
   while (x != 0) {
       cout << "enter an integer, (0 to quit)\n";
       cin >> x;
       if (x > 0) cout "x squared is " << x*x << "\n";
   }

The do while loop

The do while loop is different from the for loop and the while loop, in that the logical expression is evaluated at the end of the loop rather than when the loop is entered. For practical purposes, this means that the do while loop is guaranteed to execute at least once. The do while loop has the following form:

do statement; while (logical expression);

The statement is executed and the, if the logical expression is false, control passes to the next statement after the while statement. If the logical expression is true, control passes back to the do statement again.

The do while loop is rare compared to the for and the while loop, but one place such a loop makes sense is one which solicits user input. For instance, suppose I am writing a very primitive word processor that detects periods and automatically prints three spaces before the next sentence. A loop to do that might look like the following fragment:

// Fragment of code to detect a period char aCharacter; do { // Start loop, execute body as long as... cin >> aCharacter; cout << endl << aCharacter; } while (aCharacter != '.'); // the expression in the while statement // is true for (j = 1; j <= 3; j = j + 1) cout << " " << endl; // Print three spaces

This loop continually asks for a character from the standard input device and prints it to the standard output device, as long as the character is not a period. In the event a period is extracted from the input stream, the period and three spaces are printed.

Exercises

In each of the following exercises you should assume all variables have been correctly declared previous to the fragment you are analyzing, and that the proper header files have been included.

  1. What would be printed by the following two loops?
    a)	for (int j; j<5; ++j)
    	   cout << "j= " << j << endl;
    
    b)	int j=5;
    	do {
    	   cout << "j= " << j << endl;
    	   ++j;
    	} while (j<5);
    

  2. Give the output in each of the following loops.
    a)	for (int k=0; k<5; ++k) {
    	   int j = k%2;	// % is the modulus operator, the remainder of
    			// k divided by 2 in this case
    	   if (j==0)
    	      cout << "k modulus 2 = 0, " << "j= " << j << endl;
               if (j==1)
                  cout << "k modulus 2 = 1, " << "j= " << j << endl;
    	   if (j==2)
                  cout << "k modulus 2 = 2, " << "j= " << j << endl;
    	}
    
    b)	int m=1;
    	int k=5;
    	while (k>1) {
    	   k = 10 % m;	// k equals the remainder of 10 divided by m
    	   switch (k)
    	   {
    		case 0:
    		   cout << "Physics is fun" << endl;
    		   break;
    		case 1:
    		   cout << "Chemistry is fun" << endl;
    		   break;
    		case 2:
    		   cout << "Math is fun" << endl;   //Notice, no break.
    		default:
    		   cout << "in fact, ALL science is fun, fun, fun!" << endl;
    		   break;
    	   }
    	   m = m + 1;			// ++m; could have been used
    	}
    
    c)	int n=9;
    	float k;
    	do {
    	   k = pow(n, 2.0);	// k equal n raised to the second power
    	   n = n-1;		// --n could have been used
    	   cout << "k= " << k << "; n = " << n << endl;
    	} while (k>30);
    

    solution

  3. Write simple loops (you do not need to write the whole program) to print each of the following sequences of numbers.
    1. 1, 3, 5, 7, 9
    2. 100, 90, 80, 70, 60, 50
    3. 1, 4, 9, 16, 25

    solution

  4. Write a program using a simple do-while loop to print the numbers 1 through 10.

    solution