CMIS 102 Looping, or iteration, or repetition as it is also known. It's the most important of the control constructs to control the flow of execution. A while loop executes a body of statements any number of times. The body is executed repeatedly, as long as the condition is True. In other words, "while" the condition is True, execute the statements of the body. An execution of a body is called an iteration. To iterate means to repeat. The while statement can be contrasted with the if statement that executes a body zero or once. Like ifs, the while statement has a condition that controls it. The condition is exactly the same as the conditions used in if statements, even including the surrounding parentheses. So everything you learned about conditions, relational operators, logical operators, boolean values etc applies to the while statement. The syntax of a while statement is similar to that of an if statement. The only difference is the use of 'while' instead of 'if': while (condition) statement If the body has more than one statement, enclosing {} are needed, just like the if. No ; is after the condition, just like the if. The condition is a boolean/logical expression, i.e. something that is True or False, just like the if. The semantics of the while is different from that of the if. When executed, the condition is evaluated, if it's True, the statements of the body are executed and then control automatically loops back up to the condition again and reevaluates it and if it's true the statements of the body are executed and then control automatically loops back up to the condition again and reevaluates it and if it's true the statements of the body are executed and then ... (I can cut and paste some more times if you'd like but I think you get the point). So what stops it? When the condition is False, the body is not executed (it's skipped), the while is finished and the program goes on to whatever is after the while (and its body). It's called a "while" statement because that's how it works. "While" the condition is true, do another iteration. Or, in other words, "as long as" the condition is true, repeat. Or, in reverse logic, "until" the condition is False, iterate. Loop back or cyclic nature of the while loop. This happens automatically, it's how the while statement functions. What happens if the condition is always True? That's called an infinite loop, because it will loop forever (or until the program is terminated somehow by the user or operating system, or, if you run it long enough, the electronics malfunctions). Infinite loops are usually a bug to be avoided. Something that eventually happens in the body will make the condition false. Maybe the condition depends on some user input value (e.g. loop inputting numbers from user until user enters a zero), or it could a loop until all data has been input from a file, or until some combination of events have occurred. All the statements of the body are executed during an iteration (or pass through it). So don't think that as soon as a statement that makes the condition false is executed that the loop terminates. It's only when the condition is evaluated at the top of the loop, after all the statements of the body have executed, that the loop will exit. Here are some examples: //read numbers from user, output the square root. 0 to quit int num; cout << "Enter nos. for sqr. rooting. 0 to quit: "; cin >> num; //first number user enters. "primes" the while condition while (num != 0) { //until number entered is a 0 cout << "SQRT is: " << sqrt(num) << endl; cin >> num; //next number user enters } ------------------------------------------------------- //same, but check for negative numbers to avoid error of trying to do sqrt of //negative number cout << "Enter nos. for sqr. rooting. 0 to quit: "; cin >> num; while (num != 0) { if (num > 0) //body of any statement can contain any statements cout << "SQRT is: " << sqrt(num) << endl; else cout << "No square root of negative number!"; cin >> num; } ---------------------------------- //input 5 numbers from user and sum them int sum, count, num; sum = 0; //initialize the sum to 0 count = 0; //count of number of numbers read while (count < 5) { //loop five times cin >> num; sum += num; //add num to sum; short for sum = sum + num count++; //increment counter of numbers } cout << "Sum is " << sum; If the condition were: (count <= 5) it would be an error, six numbers would be input and summed. But it would not be an error if additonally count was initialized to 1. But if count was initialized to 1 instead of 0, and the condition stays as count<5, it would be an error, only four numbers would be input. These are known as "off by one" errors. You have to make sure that the code all works together correctly. ---------------------------------- It's rare that a program processes a constant number of values, like 5. Usually, the amount of data is variable. //user tells how many numbers to input and sum int num_nums; cout << "Enter number of numbers: "; cin >> num_nums; sum = 0; count = 0; while (count < num_nums) { //loop num_nums times cin >> num; sum += num; count++; } cout << "Sum is " << sum; ------------------------------------ //input numbers from user. Negative number indicates end. sum = 0; //no need for count variable cin >> num; //first number from user while (num >= 0) { //until a negative number is entered sum += num; cin >> num; } cout << "Sum is " << sum; //if the first number entered is negative, the condition is false the //first time in the while statement, thus the body wouldn't be //executed even once A while loop will execute 0 or more times. ---------------------------------------- //determine the number of digits in an integer //Ex. 548 has 3 digits, 2974 has 4 digits int num; cout << "Enter an integer: "; cin >> num; digits = 0; while (num > 0) { num = num / 10; //integer divide by 10 digits++; } cout << "Number of digits is " << digits; Trace this code with some examples. Show the values of the variables that result from the execution of each statement. Does it work with a negative number? How to correct it? ---------------------------------------- //read chars until #, count numbers of lowercase letters and of //uppercase letters and of all other chars int lowers=0, uppers=0, others=0; char c; cin >> c; while (c != '#') { //until # is entered if (islower(c)) //c is one of 3 categories lowers++; else if (isupper(c)) uppers++; else others++; cin >> c; } cout << "Number of lower letters: " << lowers << endl; cout << "Number of upper letters: " << uppers << endl; cout << "Number of all other chars: " << others << endl; -------------------------------------------------------------- You can categorize loops into count-controlled loops and event-controlled loops. Most loops fall into one of these categories. Notions of a sentinel, a priming read, EOF, and flag Some typical uses of loops: counting, summing, and keeping track of a previous value. Whatever the category of loop, it's what the loop does that is the important thing. Note that all this categorization is for pedagogical purposes. The thing is not to learn how to distinguish between a sentinel-controlled summing loop from an EOF-controlled summing loop, but to write a loop that accomplishes what's needed. There won't be any exam questions that require you to know any of this terminology. You only need to be able to read and write loops. By read, I mean trace (e.g. show the output). I'm not sure if all the terminology and categorization helps or hinders learning. Don't get bogged down in it. Study the examples and do the exercises and programs. Nested Logic section is very important. It's the natural extension of the earlier material. A loop can have a loop inside it. An example is code to count the number of commas on each line of input. The outer loop is looping over the lines, the inner loop is looping over the characters of a line. Display user-specified numbers of asterisks on multiple lines of output. The outer loop is looping over the user's input (numbers), the inner loops is looping the current user-number of times outputting an asterisk each iteration. It's getting hard to say in one sentence what these code fragments do. The trace shows the order of execution for a given set of input and what happens upon each statement's execution, in excrutiating detail. You will see more of efficiency analysis in future CMIS courses. Code must be above all else correct; then you can worry about how efficient it is. In particular, you must be careful that a loop iterates the exact number of times needed, not one less or one more ("off by 1" errors. You can put couts in the loop to show the value of certain variables at certain points to help you see what's going on when things are not working right.