Looping I (while statement)
CSCE 1062 Outline Looping/repetition construct while statement (section 5.1)
CSCE 1063 Repetition Repetition or looping provides for the repeated execution of part of the algorithm.
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.
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; } }
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
CSCE 1067 Listing 5.1 while loop segment example
CSCE 1068 Exercise 2 Problem Analyse, design, and implement an algorithm that calculates and outputs the following sum: sum = ……. + 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 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; }
CSCE 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 #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; }
CSCE Next lecture we will continue Looping control construct in C++