Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 4 Loops
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X2 Objectives F F To use while, do-while, and for loops to execute statements repeatedly (§§ ). F F To understand the flow of control in loops (§§ ). F F To use Boolean expressions to control loops (§§ ). F F To write nested loops (§4.5). F F To know the similarities and differences of three types of loops (§4.6). F F (Optional) To implement program control with break and continue (§4.7). F F (Optional) To read and write data from/to a file (§4.11).
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 3 while Loop Flow Chart while (loop-continuation-condition) { // loop-body; Statement(s); } int count = 0; while (count < 100) { cout << "Welcome to C++!\n"; count++; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 4 Trace while Loop int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Initialize count animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 5 Trace while Loop, cont. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } (count < 2) is true animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 6 Trace while Loop, cont. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Print Welcome to C++ animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 7 Trace while Loop, cont. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Increase count by 1 count is 1 now animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 8 Trace while Loop, cont. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } (count < 2) is still true since count is 1 animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 9 Trace while Loop, cont. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Print Welcome to C++ animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 10 Trace while Loop, cont. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Increase count by 1 count is 2 now animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 11 Trace while Loop, cont. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } (count < 2) is false since count is 2 now animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 12 Trace while Loop int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } The loop exits. Execute the next statement after the loop. animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 13 Example: An Advanced Math Learning Tool The Math subtraction tutor program in Listing 3.6, SubtractionTutor.cpp, generates just one question for each run. You can use a loop to generate questions repeatedly. Listing 4.1 gives a program that generates ten questions and reports the number of the correct answers after a student answers all ten questions. The program also displays the time spent on the test and lists all the questions, as shown in sample output. SubtractionTutorLoop
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X #include #include // for time function #include // for the srand and rand functions using namespace std; int main() { int correctCount = 0; /*Count the number of correct answers*/ int count = 0; long startTime = time(0); while (count < 10) { // 1. Generate two random integers srand(time(0)); int number1 = rand( ) % 10; int number2 = rand( ) % 10; /*2. If number1 < number2, swap number1 with number2*/ if (number1 < number2) { int temp = number1; number1 = number2; number2 = temp; } /*3. Prompt the student to answer “what is number1 – number2?*/ cout << "What is " << number1 << " - " << number2 << "? "; int answer; cin >> answer;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X /* 4. Grade the answer and display the result*/ if (number1 - number2 == answer) { cout << "You are correct!\n"; correctCount++; } else cout << "Your answer is wrong.\n" << number1 << " - " << number2 << " should be " << (number1 - number2) << endl; // Increase the count count++; } long endTime = time(0); long testTime = endTime - startTime; cout << "Correct count is " << correctCount << "\nTest time is " << testTime << " seconds\n"; return 0; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 16 Controlling a Loop with User Confirmation char continueLoop = 'Y'; while (continueLoop == 'Y') { // Execute body once // Prompt the user for confirmation cout << “do you want to continue?\n Enter Y to continue and N to quit: "; cin >> continueLoop; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 17 Ending a Loop with a Sentinel Value Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value. Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. SentinelValue
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X #include #include using namespace std; int main() { cout << "Enter an int value (the program exits " << cout << "Enter an int value (the program exits " << "if the input is 0): "; "if the input is 0): "; int data; int data; cin >> data; cin >> data; // Keep reading data until the input is 0 // Keep reading data until the input is 0 int sum = 0; int sum = 0; while (data != 0) while (data != 0) { sum += data; sum += data; // Read the next data cout << "Enter an int value (the program exits " << cout << "Enter an int value (the program exits " << "if the input is 0): "; "if the input is 0): "; cin >> data; cin >> data; } cout << "The sum is " << sum << endl; cout << "The sum is " << sum << endl; return 0; return 0;}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 19 Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is 0. double data = pow(sqrt(2.0), 2) - 2; if (data != 0) cout << "data is zero"; else cout << "data is not zero";
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 20 do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition);
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 21 int sum = 0; int data = 0; do { sum += data; // Read the next data cout << "Enter an int value (the program exits " << " if the input is 0): "; cin >> data; } while (data != 0); cout << "The sum is " << sum << endl; int sum = 0; int data = 0; do { sum += data; // Read the next data cout << "Enter an int value (the program exits " << " if the input is 0): "; cin >> data; } while (data != 0); cout << "The sum is " << sum << endl;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 22 for Loops for (initial-action; loop-continuation- condition; action-after-each- iteration) { // loop body; Statement(s); } int i; for (i = 0; i < 100; i++) { cout << "Welcome to C++!\n"; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 23 Trace for Loop int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } Declare i animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 24 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } Execute initializer i is now 0 animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 25 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } (i < 2) is true since i is 0 animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 26 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } Print Welcome to C++! animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 27 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } Execute adjustment statement i now is 1 animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 28 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } (i < 2) is still true since i is 1 animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 29 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } Print Welcome to C++ animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 30 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } Execute adjustment statement i now is 2 animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 31 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } (i < 2) is false since i is 2 animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 32 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; } Exit the loop. Execute the next statement after the loop animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 33 Note The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each- iteration in a for loop can be a list of zero or more comma- separated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however. for (int i = 1; i < 100; cout << (i++)); for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 34 Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion:
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 35 Example: Using for Loops Problem: Write a program that sums a series that starts with 1 and ends with 100. The numbers in the series will increment by 1, as follows: and so on.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 36 #include using namespace std; int main() { // Initialize sum double sum = 0; // Add 1, 2,..., 99, 100 to sum for (int i = 1 ; i <= 100 ; i = i ++) sum += i; // Display result cout << "The sum is " << sum; return 0; } #include using namespace std; int main() { // Initialize sum double sum = 0; // Add 1, 2,..., 99, 100 to sum for (int i = 1 ; i <= 100 ; i = i ++) sum += i; // Display result cout << "The sum is " << sum; return 0; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 37 Which Loop to Use? The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b): A for loop in (a) in the following figure can generally be converted into the following while loop in (b) except in certain special cases (see Review Question 3.19 for one of them):
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 38 Recommendations Use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X Examples F Write a program to calculate factorial of an integer. 39
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 40 #include using namespace std; int main() { // Prompt the user to enter an integer cout << "Enter an integer: "; int n; cin >> n; double fact=1; for (int i=1; i<=n;i++) fact=fact*i; cout<< "\n"<<n <<"! = "<<fact<<endl; system("pause"); return 0; } #include using namespace std; int main() { // Prompt the user to enter an integer cout << "Enter an integer: "; int n; cin >> n; double fact=1; for (int i=1; i<=n;i++) fact=fact*i; cout<< "\n"<<n <<"! = "<<fact<<endl; system("pause"); return 0; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 41 Example: Finding the Greatest Common Divisor Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. GreatestCommonDivisorRun
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X #include using namespace std; int main() { cout << "Enter first integer: "; int n1; cin >> n1; cout << "Enter second integer: "; int n2; cin >> n2; int gcd; int k = 1; while (k <= n1 && k <= n2) { if (n1 % k == 0 && n2 % k == 0) gcd = k; k++; } cout << "The greatest common divisor for " << n1 << " and " << n2 << " is " << gcd; return 0; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X Nested Loops F Write a program to compute and print the factorial of all numbers between 1 and 10 43
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X #include using namespace std; int main() { cout << "factorial of integers from 1 to 10:\n "; double fact=1; for (int k=1; k<=10; k++) { fact=1; for (int i=1; i<=k ; i++) fact= fact * i ; cout<< "\n"<<k <<"! = "<<fact<<endl; } system("pause"); return 0; } 44
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 45 Nested Loops Problem: Write a program that uses nested for loops to print a multiplication table.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 46 #include using namespace std; int main() { cout << " Multiplication Table\n"; cout << " \n"; cout << " | "; for (int j = 1; j <= 9; j++) cout << setw(3) << j; cout << "\n"; for (int i = 1; i <= 9; i++) { cout << i << " | "; for (int j = 1; j <= 9; j++) { // Display the product and align properly cout << setw(3) << i * j; } cout << "\n"; } return 0; } #include using namespace std; int main() { cout << " Multiplication Table\n"; cout << " \n"; cout << " | "; for (int j = 1; j <= 9; j++) cout << setw(3) << j; cout << "\n"; for (int i = 1; i <= 9; i++) { cout << i << " | "; for (int j = 1; j <= 9; j++) { // Display the product and align properly cout << setw(3) << i * j; } cout << "\n"; } return 0; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 47 Using break and continue Examples for using the break and continue keywords: F F Break: immediately ends the innermost loop that contains it F F TestBreak.cpp F F Continue only ends the current iteration F F TestContinue.cpp TestBreak TestContinue
#include using namespace std; int main() { int sum = 0; int number = 0; while (number < 20) { number++; sum += number; if (sum >= 100) break; } 48 cout << "The number is " << number << endl; cout << "The sum is " << sum << endl; cout << "The sum is " << sum << endl;system("pause"); return 0; return 0;}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X #include using namespace std; int main() { int sum = 0; int number = 0; while (number < 20) { number++; if (number == 10 || number == 11) continue; sum += number; } cout << "The sum is " << sum; system("pause"); return 0; } 49
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X Prime number F Write a program that takes an integer as input and determine wether the number is prime or not 50
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X int main() { cout<<"enter a number\n"; int number; // A number to be tested for primeness cin>>number; bool isPrime=true; for (int divisor = 2; divisor <= number / 2; divisor++) if (number % divisor == 0) { // If true, the number is not prime isPrime = false; // Set isPrime to false break; // Exit the for loop } if (isPrime) cout << number <<" is prime number" << endl; else cout << number << " is not prime"; return 0;} ` 51
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 52 Example: Displaying Prime Numbers Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. PrimeNumberRun
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X Solution F The problem can be broken into the following tasks: For number = 2, 3, 4, 5, 6,..., test whether the number is prime. Determine whether a given number is prime. Count the prime numbers. Print each prime number, and print 10 numbers per line. 53
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X int main() { int count = 0; // Count the number of prime numbers int number = 2; // A number to be tested for primeness cout << "The first 50 prime numbers are \n"; while (count < 50) { bool isPrime = true; // Assume the number is prime // Test if number is prime for (int divisor = 2; divisor <= number / 2; divisor++) if (number % divisor == 0) // If true, the number is not prime { isPrime = false; break; // Exit the for loop } // Print the prime number and increase the count if (isPrime) {count++; // Increase the count cout << number << endl; } number++; } system("pause"); return 0; } 54
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 55 File Input and Output You used the cin to read input from the keyboard and the cout to write output to the console. You can also read and write data from/to a file. This section introduces simple file input and output. Detailed coverage of file input and output will be presented in Chapter 12. SimpleFileOutputRun SimpleFileInputRun
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X #include using namespace std; int main() { ifstream input; // Open a file input.open("numbers.txt"); // Read data int score1, score2, score3; input >> score1; input >> score2; input >> score3; cout << "Total score is " << score1 + score2 + score3 << endl; // Close file input.close(); cout << "Done" << endl; return 0; } Simple File Iutput
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X #include using namespace std; int main() { ofstream output; // Create a file output.open("numbers.txt"); // Write numbers output << "this is a test"<<95 << " " << 56 << " " << 34; // close file // output.close(); cout << "Done" << endl; return 0; } Simple File Output
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 58 Testing End of a File Listing 4.13 reads three numbers from the data file. If you don’t know how many numbers are in the file and want to read them all, how do you know the end of file? You can invoke the eof() function on the input object to detect it. Listing 4.14 revises Listing 4.13 to read all lines from the file numbers.txt. TestEndOfFileRun
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X #include using namespace std; int main() { ifstream input; // Open a file input.open("num.txt"); int score; int total=0; while (!input.eof()) // Continue if not end of file { input >> score; total+=score; } cout<<"total scoreis "<<total<<endl; input.close(); cout << "Done" << endl; return 0; }
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X Assignment # 4 F Read chapter 4 F Solve review question : 1, 8, 10, 11, 15, 17. F Solve the following programming exercises 2, 9, 12, 18(1, 2), 26 60