COMPUTER PROGRAMMING
TOPIC: LOOPS IN C++
, In C++, loops are control structures that allow you to execute a block of code repeatedly. They are
essential for automating repetitive tasks and iterating over data structures. C++ provides three main
types of loops: for, while, and do-while.
1. for loop:
The for loop is typically used when you know the number of iterations in advance.
It consists of three parts:
o Initialization: Executed only once before the loop starts. Used to initialize a loop counter
variable.
o Condition: Evaluated before each iteration. If the condition is true, the loop body is
executed. If it's false, the loop terminates.
o Increment/Decrement: Executed after each iteration. Used to update the loop counter
variable.
C++
for (int i = 0; i < 10; i++) {
// Code to be executed in each iteration
std::cout << i << " ";
}
// Output: 0 1 2 3 4 5 6 7 8 9
2. while loop:
The while loop is used when you want to repeat a block of code as long as a condition is true.
The condition is evaluated before each iteration. If the condition is initially false, the loop body is
never executed.
C++
int i = 0;
while (i < 10) {
// Code to be executed in each iteration
std::cout << i << " ";
i++;
}
// Output: 0 1 2 3 4 5 6 7 8 9
TOPIC: LOOPS IN C++
, In C++, loops are control structures that allow you to execute a block of code repeatedly. They are
essential for automating repetitive tasks and iterating over data structures. C++ provides three main
types of loops: for, while, and do-while.
1. for loop:
The for loop is typically used when you know the number of iterations in advance.
It consists of three parts:
o Initialization: Executed only once before the loop starts. Used to initialize a loop counter
variable.
o Condition: Evaluated before each iteration. If the condition is true, the loop body is
executed. If it's false, the loop terminates.
o Increment/Decrement: Executed after each iteration. Used to update the loop counter
variable.
C++
for (int i = 0; i < 10; i++) {
// Code to be executed in each iteration
std::cout << i << " ";
}
// Output: 0 1 2 3 4 5 6 7 8 9
2. while loop:
The while loop is used when you want to repeat a block of code as long as a condition is true.
The condition is evaluated before each iteration. If the condition is initially false, the loop body is
never executed.
C++
int i = 0;
while (i < 10) {
// Code to be executed in each iteration
std::cout << i << " ";
i++;
}
// Output: 0 1 2 3 4 5 6 7 8 9