CP Lab08
CP Lab08
CP Lab08
Objectives
• Understanding and getting familiar with conditional logic.
• Understanding and implementing conditional control structure (While & Do-While loop) of C++.
Tools
• Code::Blocks (Version: 13.12) or Bloodshed Dev C++ (Version: 4, 5 or higher)
8.1 Introduction
In C++, the three commonly used loop structures are for, while, and do-while. They all serve the purpose
of repeating a block of code until a certain condition is met, but they differ in their syntax and the way
they handle the condition evaluation. Let's take a look at each loop structure and their differences.
Syntax
Here's an example that prints numbers from 1 to 5:
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
// Output: 1 2 3 4 5
In each iteration, the for loop executes the code inside the curly braces, updates the loop control variable
(i in this case), and checks the condition. If the condition is true, the loop continues; otherwise, it
terminates.
The while loop C++ is a type of loop that will first evaluate a condition. If the condition is true, the
program will run the code inside of the while loop. It will then go back and re-evaluate the
condition. Every time the condition is true, the program will perform the code inside the loop.
The while loop is used when the number of iterations is not known in advance, and it repeats until
the given condition becomes false.
Syntax
while (condition) {
Here,
If the condition evaluates to true, the code inside the while loop is executed.
int i = 1;
while (i <= 5) {
i++;
// Output: 1 2 3 4 5
The loop continues as long as the condition remains true. If the condition is initially false, the loop
will never be executed.
The do...while loop is a variant of the while loop with one important difference: the body of
do...while loop is executed once before the condition is checked.
The do-while loop is similar to the while loop, but the condition is checked at the end of each
iteration. This guarantees that the loop body is executed at least once.
Syntax
do {
} while (condition);
int i = 1;
do {
i++;
// Output: 1 2 3 4 5
The loop body is executed first, and then the condition is evaluated. If the condition is true, the loop
continues; otherwise, it terminates.
In summary, the for loop is commonly used when the number of iterations is known, the while loop is
used when the condition needs to be checked before the loop starts, and the do-while loop is useful
when you want the loop body to execute at least once before the condition is checked.
EXERCISE
Problem Statement 01
Problem Statement 02
C++ program to print the first n even numbers using for, while and do-while loop.
All three solutions will produce the same output, which is the first n even numbers. For example, if n
is 5, the output will be: 2 4 6 8 10.