Presentation is loading. Please wait.

Presentation is loading. Please wait.

Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)

Similar presentations


Presentation on theme: "Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)"— Presentation transcript:

1 Looping I (while statement)

2 CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)

3 CSCE 1063 Repetition  Repetition or looping provides for the repeated execution of part of the algorithm.

4 CSCE 1064 Exercise 1  Problem Analyse, and design, using a flowchart, an algorithm that outputs the word “Hello” 10 times each on a separate line.  Analysis  Input None  Output “Hello” 10 times  Intermediate variables i: counter used to indicate the current iteration number.

5 CSCE 1065 Exercise (cont’d) OUTPUT “Hello”, ‘\n’ START STOP  Design i <= 10 ? True False i = 1 i = i + 1 #include using namespace std; void main () { int i; i = 1; while (i <= 10) { cout << “Hello”<<endl; i = i +1; } }

6 CSCE 1066 while Statement  Syntax: while (loop repetition condition) statement;  E.g. i = 1; while (i <= 10) { cout << “*”; i = i + 1; } Intialising loop control variable Testing loop control variable Updating loop control variable

7 CSCE 1067 Listing 5.1 while loop segment example

8 CSCE 1068 Exercise 2  Problem Analyse, design, and implement an algorithm that calculates and outputs the following sum: sum = 1 + 2 + 3 + ……. + n up to any number (n) input by the user.  Analysis  Input n: upper limit  Output sum: sum of series  Intermediate variables i: the current iteration number

9 CSCE 1069 INPUT n OUTPUT sum START STOP  Design i <= n ? True False i = 1 sum = 0 sum = sum + i i = i + 1 #include using namespace std; void main () { int n, i, sum; cin >> n; i = 1; sum = 0; while (i <= n) { sum = sum + i; i = i +1; } cout << “The sum is “<<sum; }

10 CSCE 10610 Exercise 3 Analyse, design, and implement an algorithm that calculates the factorial of a given number (n), input by the user. Factorial is calculated using the following equation: factorial = 1 * 2 * 3 * … * n

11 CSCE 10611 #include using namespace std; void main() { int i, n, factorial = 1; cout << “Please enter a whole number:“; cin >> n; i = 2; while (i <= n) { factorial = factorial * i; i = i + 1; } cout << “The factorial is:“ << factorial << endl; }

12 CSCE 10612 Next lecture we will continue Looping control construct in C++


Download ppt "Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)"

Similar presentations


Ads by Google