Presentation is loading. Please wait.

Presentation is loading. Please wait.

While Loops 10/14/13. Repetition Allows a program to do tasks over and over. Very powerful because the computer is fast and accurate.

Similar presentations


Presentation on theme: "While Loops 10/14/13. Repetition Allows a program to do tasks over and over. Very powerful because the computer is fast and accurate."— Presentation transcript:

1 While Loops 10/14/13

2 Repetition Allows a program to do tasks over and over. Very powerful because the computer is fast and accurate.

3 Control Variable Loop – repeated portion of a program Control Variable – Variable whose value determines if body of loop is executed Example: ch4/manyHellos.cpp

4 Loop Components Needed Initialization of loop control variable –cin >> count_down Evaluation of loop control variable – while (count_down > 0) Update loop control variable –count_down--;

5 Other Definitions Loop Body – statements repeated Iteration – repetition of a loop body Example – ch4/odds.cpp

6 Other Definitions Infinite Loop – loop that repeats indefinitely – stop with cntl-C

7 Fix odds.cpp

8 Syntax of while-loop while (bool expression)‏ stmt;

9 Syntax of while-loop while (bool expression)‏ { stmt1; stmt2;. stmtn; }

10 01/27/1210 Increment and Decrement Operators  Increment Operator ++ post incrementx++; pre increment++x;  Decrement Operator - - post decrementx- -; pre decrement- -x;  For examples assume k=5 prior to executing the statement. m= ++k;both m and k become 6 n = k- -; n becomes 5 and k becomes 4

11 01/27/12Engineering Problem Solving with C++, Etter,Ingber Second Edition 11 Abbreviated Assignment Operators operatorexampleequivalent statement +=x+=2; x=x+2; -=x-=2;x=x-2; *=x*=y;x=x*y; /=x/=y;x=x/y; %=x%=y;x=x%y;

12 Find the Sum of Ten Numbers. Write a program that uses a while loop to input 10 numbers then output their sum. First, let's write an algorithm.

13 Hand Tracing It can be useful to step through loops, keeping track of the variables as you do. int i = 2; int n = 4; while(i <= n){ cout << i; i++; }

14 Hand Tracing It can be useful to step through loops, keeping track of the variables as you do. Example: trace.cpp What does the loop do for arbitrary values of a and r?


Download ppt "While Loops 10/14/13. Repetition Allows a program to do tasks over and over. Very powerful because the computer is fast and accurate."

Similar presentations


Ads by Google