320 likes | 457 Vues
This chapter focuses on mastering the usage of loop constructs in C++, including while, do-while, and for loops. Readers will learn about control flow within loops, how Boolean expressions govern iterations, and the similarities and differences between loop types. The chapter also covers the break and continue statements, as well as simple file input and output. Real-world examples, such as generating questions and handling user inputs with sentinel values, provide practical insights into effective loop usage.
E N D
Chapter 4 Loops §4.1 The “while” Loop §4.2 The “do-while” Loop §4.3 The “for” Loop §4.4 Nested loop §4.5 “break” and “continue” §4.6 Simple File Input and Output
Objectives • To master the usage of while, do-while, and for loops statements • To understand the flow of control in loops • To use Boolean expressions to control loops • To know the similarities and differences of three types of loops • To know the use functionality of break and continue • To know how to read and write data from/to a file
§4.1 The “while” Loop while (loop-continuation-condition) { // loop-body; Statement(s); } int count = 0; while (count < 100) { cout << "Welcome to C++!\n"; count++; }
(count < 2) is false since count is 2 now Print Welcome to C++ The loop exits. Execute the next statement after the loop. (count < 2) is still true since count is 1 Increase count by 1 count is 2 now Initialize count (count < 2) is true Print Welcome to C++ Increase count by 1 count is 1 now Trace while Loop int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; }
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
Controlling a Loop with User Confirmation char continueLoop = 'Y'; while (continueLoop == 'Y') { // Execute body once // Prompt the user for confirmation cout << "Enter Y to continue and N to quit: "; cin >> continueLoop; }
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
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. • double data = pow(sqrt(2.0), 2) - 2; • if (data == 0) • cout << "data is zero"; • else • cout << "data is not zero";
§4.2 The “do-while” Loop “while” do { // Loop body; Statement(s); } while (loop-continuation-condition); “do-while”
Example • Listing 4.3: a program that reads and calculates the sum of an unspecified number of integers. • The input 0 signifies the end of the input. TestDoWhile
§4.3 The “for” Loop 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"; }
Execute adjustment statement i now is 2 (i < 2) is true since i is 0 Print Welcome to C++! Execute adjustment statement i now is 1 (i < 2) is still true since i is 1 Print Welcome to C++ (i < 2) is false since i is 2 Exit the loop. Execute the next statement after the loop Declare i Execute initializer i is now 0 Trace for Loop int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; }
Note • All the three control expressions in “for” loop can be omitted • But the semicolons can not be omitted sum=0; i=1; for (; i<=100;){ sum += i; i++;} sum=0; i=1; for ( ; ; ){ if (i<=100) break; sum += i; i++;} • sum=0; i=1; for (; i<=100; i++) sum += i; • sum=0;for (i=1; ; i++){ if (i<=100) break; sum += i;} • sum=0;for (i=1; i<=100; ){ sum += i; i++;} -- If the loop-continuation-condition in a for loop is omitted, it is implicitly true. -- It may result in infinite loop.
Note • The initial-action and action-after-each-iteration can be a list of comma-separated expressions • rarely used in practice “,” operator • for (int i = 0, j = 0; (i + j < 10); i++, j++) { • // Do something • }
“,” Operator • “,”: concatenate expressions and the value of the rightmost expression is the value of the whole comma expression • Example: int main(){ int x,y; x=50; for (int i = 0,j = 0;i + j < 10;i++,j++) { y=(x=x-5,x/5); cout<<x<<" "<<y<<endl; } }
Example: Using for Loops Problem: Write a program that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on. TestSum
Floating-point Numbers in Relational Expressions int main() { // Initialize sum double sum = 0; double prei=0; double i; // Add 0.01, 0.02, ..., 0.99, 1 to sum for (i = 0.01f; i <= 1.0f; i = i + 0.01f){ sum += i; prei=i; } // Display result cout << "The sum is " << sum<<endl; cout<<setprecision(10)<<"i is increaded by "<<i-prei<<endl; cout<<"The final i is "<<i<<", and i-1.0 is " <<(i-1.0)<<endl; return 0; } int main() { // Initialize sum double sum = 0; double i=0; // Add 0.01, 0.02, ..., 0.99, 1 to sum for (i = 0.01; i <= 1.0; i = i + 0.01) sum += i; // Display result cout << "The sum is " << sum; return 0; }
Which Loop to Use? • while, do-while, and for, are expressively equivalent and mutually conversable.
Which Loop to Use? • “for”: • if the number of repetitions is known. • “while”: • if the number of repetitions is unknown • “do-while”: • to replace a while loop if the loop body has to be executed before testing the continuation condition.
§4.4 Nested loop • Loop with one outer loop and one or more inner loops
Nested Loops Listing 4.5: a program that uses nested for loops to print a multiplication table. TestMultiplicationTable
Loop 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: Let the two input integers be n1 and n2. 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. GreatestCommonDivisor Run
Loop Example: Finding the Sales Amount • Problem: You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate. • Sales Amount Commission Rate • $0.01–$5,000 8 percent • $5,000.01–$10,000 10 percent • $10,000.01 and above 12 percent • Your goal is to earn $30,000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $30,000. FindSalesAmount Run
Loop Example: Displaying a Pyramid of Numbers Problem: Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid. For example, if the input integer is 12, the output is shown below. Run PrintPyramid
§4.5 “break” and “continue” • break: • May only be used inside a loop or a switch statement. • To terminate the current loop/switch immediately and transfer control to the statement immediately following that loop/switch. sum=0; mark=1; for ( i=0; ; ){ if (i>100) break; sum += i; i++;} if(i>0) avgnum = sum/I; …
“continue” • “continue”: • May only be used inside a loop. • To terminate the current iteration of the loop and proceeds directly to the next. • In the case of a for loop it jumps to its action-after-each-iteration. sum=0; mark=1; for ( i=0; ; ){ if (i>100) continue; sum += i; i++;} if(i>0) avgnum = sum/I; …
Examples • Use of “break” TestBreak • Use of “continue” TestContinue
Loop 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. • Solution: 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. PrimeNumber Run
§4.6 Simple File Input and Output • To read input from the keyboard and write output to the screen/console? • “cin” and “cout” • To read and write data from/to a file? • ifstream and ofstream
Simple File Input and Output • To write to a file SimpleFileOutput Run • To read from a file SimpleFileInput Run
Testing End of a File • Listing 4.3 read only three lines • How to determine when to stop reading if you don’t know how many numbers are in a file? • Use the eof() function to detect it. Listing 4.14 revises Listing 4.13 to read all lines from the file numbers.txt. TestEndOfFile Run
Summary • “while” and “do-while” loops • “for” loops • Difference between loop stements • Use of “break” and “continue” • Simple file I/O • Testing of end-of-file