Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Loops Case Studies

Similar presentations


Presentation on theme: "Chapter 4 Loops Case Studies"— Presentation transcript:

1 Chapter 4 Loops Case Studies
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved

2 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.

3 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; }

4 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

5 Exercise 4.25 : Computing π You can approximate π by using the following series: Write a program that displays the π value for i=

6 Exercise 4.18 : Print a Pyramid pattern
Use nested loops that print the following pattern:

7 Homework Use nested loops that print the following pattern:
(2) Write a program that displays the e value for i=


Download ppt "Chapter 4 Loops Case Studies"

Similar presentations


Ads by Google