120 likes | 138 Views
Looping I ( while statement). Outline. Looping/repetition construct while statement (section 5.1). Repetition. Repetition or looping provides for the repeated execution of part of the algorithm. Exercise 1. Problem
E N D
Outline • Looping/repetition construct • while statement (section 5.1) CSCE 106
Repetition • Repetition or looping provides for the repeated execution of part of the algorithm. CSCE 106
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. CSCE 106
#include <iostream> using namespace std; void main () { int i; i = 1; while (i <= 10) { cout << “Hello”<<endl; i = i +1; } } Exercise (cont’d) START • Design i = 1 False STOP i <= 10 ? True OUTPUT “Hello”, ‘\n’ i = i + 1 CSCE 106
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 CSCE 106
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 CSCE 106
#include <iostream> 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; } START • Design INPUT n i = 1 sum = 0 OUTPUT sum False i <= n ? True STOP sum = sum + i i = i + 1 CSCE 106
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 CSCE 106
#include <iostream> • 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; • } CSCE 106
Next lecture we will continue Looping control construct in C++ CSCE 106