Lab 5
Lab 5
Lab 5
Engineering Faculty
Fall 2021
ECOM 2003
Contents
❖ Introduction
❖ While loop
❖ Do-While loop
❖ for loop
Introduction
Loops are used in programming to repeat a specific block until some end condition
is met.
Suppose that you need to display a string (e.g., "Welcome to C++!") 100 times. It
would be tedious to write the following statements 100 times:
So, how do you solve this problem?
C++ provides a powerful construct called a loop that controls how many times an
operation or a sequence of operations is performed in succession. Using a loop
statement, you simply tell the computer to display a string 100 times without
having to code the print statement 100 times.
2
Lab#5: Loops Part I
You can write a sentence "Welcome to C++!" 100 times using the while loop as
follows:
int count = 0;
while (count < 100)
{
cout << "Welcome to C++!\n";
count++;
}
3
Lab#5: Loops Part I
In this program, user is asked to enter a positive integer which is stored in variable
number. Let's suppose, user entered 4.
Then, the while loop starts executing the code. Here's how while loop works:
1. Initially, i = 1, test expression i <= number is true and factorial becomes 1.
4
Lab#5: Loops Part I
❖ Ex2: Write C++ Program to add all numbers entered by user until he enters 0
5
Lab#5: Loops Part I
6
Lab#5: Loops Part I
7
Lab#5: Loops Part I
Note:
❖ The initial-action in a for loop can be a list of zero or more comma-separated
expressions.
❖ The action-after-each-iteration in a for loop can be a list of zero or more comma-
separated statements.
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
❖ If the loop-continuation-condition in a for loop is omitted, it is implicitly true.
8
Lab#5: Loops Part I
❖ Lab work:
1. Convert the following for loop statement to a while loop and to a do-while
loop:
int sum = 0;
for (int i = 0; i <= 1000; i++)
sum = sum + i;
2. Write a program to calculate the sum of Natural Numbers "user
entered number ".
❖ Home work: