Presentation is loading. Please wait.

Presentation is loading. Please wait.

General Condition Loop

Similar presentations


Presentation on theme: "General Condition Loop"— Presentation transcript:

1 General Condition Loop
A general condition loop is a catch-all category for loops that are not count-controlled nor sentinel-controlled The program loops until some general condition becomes false Usually it is implemented with the while statement

2 Nim's Game Consider Nim's game. This is a two player game. We begin with a pile of 21 stones, and the players takes turns, each player taking 1, 2, or 3 stones from the pile. The player who takes the last stone from the pile loses.

3 Nim's Game (Code) int num = 21, winner = 1, n; while (num > 0) {
cout << num << " stones. Plr 1: How many?"; cin >> n; num -= n; if(num <= 0) winner = 2; else { cout << num << " stones. “ << “Plr 2: Take how many?"; } cout << "Winner is " << winner << endl;

4 Nim's Game (Output) 21 stones. Plr 1: Take how many?2
Winner is 1

5 Break, continue, and return
Three different C++ statements can be used to change how the loop code is done: The break statement ends the loop immediately. Control pass to the first statement after the loop. The continue statement jumps to the end of the loop, but the loop continues. The return statement returns from the function (main).

6 Nim's Game (Code 2) int num = 21, p = 1, n; while (true) {
cout << num << " stones. Plr " << p << ": Take how many?"; cin >> n; num -= n; p = 3 - p; // Change player, 1->2, 2-> 1 if(num <= 0) { cout << "Winner is " << p << endl; break; }

7 Do-While statement The do-while statement is similar to the while statement, but the test comes after the loop body: do { <statement> while (<Boolean expression>); So, the loop body is always done first, then the expression is evaluated and if true, the loop is repeated.

8 Sentinel-controlled Loop
The do-while statement could be used to implement a sentinel controlled loop, but at the cost of writing the test twice. do { cin >> temp; if(temp >= 0) <process temp>; while(temp>=0);

9 The Comma Operator The comma operator is used to sequentially evaluate expressions. For example, a+b, c-d, i++, will first evaluate a+b, then evaluate c-d, and then evaluate i++. The value of whole expression is the value of the last term. It is most commonly used in the iteration step of a for-loop. for(i=0, j=0; i < 10; i++, j+=2){}

10 Exercise Consider how to print out one page of a monthly calendar:
Su Mo Tu We Th Fr Sa

11 Exercise (Cont'd) The program should read in the number of days in the month, and the first day of the month (0=Sun, 1=Mon, 2=Tue,...) and then print out the month properly formatted.


Download ppt "General Condition Loop"

Similar presentations


Ads by Google