Module 6-1 PDF
Module 6-1 PDF
DIFINITIONS
For Example, let’s say we want to show a message 100 times. Then instead of writing the
That was just a simple example; we can achieve much more efficiency and
for loop
while loop
do…while loop
OBJECTIVES
2. Able to use for loop, while loop, do while loop in C++ programming.
8
MODULE 6.1
Here,
If the condition evaluates the true, the code inside the while loop is executed.
Figure 2.
9
MODULE 6.1
Output
10
MODULE 6.1
Output
In this program, the user is prompted to enter a number, which is stored in the variable number.
In order to store the sum of the numbers, we declare a variable sum and initialize it to the value
of 0.
11
MODULE 6.1
The while loop continues until the user enters a negative number. During each iteration, the
When the user enters a negative number, the loop terminates. Finally, the total sum is displayed.
The do…while loop is a variant of the while loop with one important difference: the body of
Here,
The body of the loop is executed at first, then the condition is evaluated.
If the condition evaluates to true, the body of the loop inside the do statement is executed
again.
If the condition evaluates to true, the body of the loop inside the do statement is executed
again.
This process continues until the condition evaluates to false. Then the loop stops.
12
MODULE 6.1
13
MODULE 6.1
Output
14
MODULE 6.1
Output
Here, the do…while loop continues until the user enters a negative number.
When the number is negative, the loop terminates; the negative number is not added to the sum
variables.
The body of the do…while loops runs only once if the user enters a negative number.
15
MODULE 6.1
If the condition of a loop is always true, the loop runs for infinite times (until the memory is full).
For example,
In the above programs, the condition is always true. Hence, the loop body will run for infinite
times.
A for loop is usually used when the number of iterations is known. For example,
However, while and do…while loops are usually used when the number of iterations is unknown.
For example,
16
MODULE 6.1
Problem
17