Chapter 4 Loops Case Studies Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Using break and continue Two keywords, break and continue, can be used in loop statements to provide the loop with additional control. Break: immediately ends the innermost loop that contains it. In other words, break breaks out of a loop. continue: only ends the current iteration. Program control goes to the end of the loop body. In other words, continue breaks out of an iteration.
Example: TestBreak TestBreak.cpp Write a program that adds the integers from 1 to 20 in this order to sum until sum is greater than or equal to 100. #include <iostream> using namespace std; int main() { int sum = 0; int number = 0; while (number < 20) { number++; sum += number; if (sum >= 100) break; } cout << "The number is " << number << endl; cout << "The sum is " << sum << endl; return 0; }
Example: TestContinue TestContinue.cpp Write a program that adds all the integers from 1 to 20 except 10 and 11 to sum. #include <iostream> 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<<endl; return 0; } number is not added to sum when it is 10 or 11
Exercise 4.25 : Computing π You can approximate π by using the following series: Write a program that displays the π value for i=100000.
Exercise 4.18 : Print a Pyramid pattern Use nested loops that print the following pattern:
Homework Use nested loops that print the following pattern: (2) Write a program that displays the e value for i=100000.