Iterative Structure
While Loop:
While Loops are used when we don’t know how many times certain instructions will be executed.
While loop terminates as soon as the condition gets false.
Syntax:
while (condition) {
// body of while loop
}
Flowchart:
Note: A while loop might not execute at all. When the condition is tested and the result is false,
the loop body will be skipped and the first statement after the while loop will be executed.
TASKS:
1. Practice the examples, discuss in theory lecture of counter-controlled while loop and Sentinel
controlled while loop and from the Chapter # 5 of text book.
2. Write a program that reads 10 positive numbers from the keyboard and determines and displays
the sum and average of the numbers.
3. The factorial is calculated by multiplying the original number by all the positive integers
smaller than itself. Thus, the factorial of 5 is 5*4*3*2*1 = 120. Write a C++ program to
calculate factorial, of any number given by user. Using while loop.
4. Write a C++ program that print the first 20 even and odd numbers using while loop.
5. Read a positive integer value, and compute the following sequence: If the number is even,
halve it; if it's odd, multiply by 3 and add 1. Repeat this process until the value is 1, printing
out each value. Finally, print out how many of these operations you performed.
The typical output might be:
Initial value is 9
Next value is 28
Next value is 14
Next value is 7
Next value is 22
Next value is 11
Next value is 34
Next value is 17
Next value is 52
Next value is 26
Next value is 13
Next value is 40
Next value is 20
Next value is 10
Next value is 5
Next value is 16
Next value is 8
Next value is 4
Next value is 2
Final value 1, number of steps 19
If the input value is less than 1, print a message containing the word Error and exit from
the program.
Note: Submit the Lab 7 on google classroom.