Loops
Loops
Output: Explanation:
Iteration: 1 The loop starts with i = 1.
Iteration: 2 The condition i <= 5 is checked before each
Iteration: 3 iteration.
Iteration: 4 After each iteration, i is incremented by 1
Iteration: 5 (i++).
The loop stops when i becomes 6.
The while Loop
The while loop is used when you want to repeat a block of
code as long as
a condition is true. Unlike the for loop, the number of
iterations may not
be known in advance.
Output: Explanation:
Iteration: 1 The loop starts with i = 1.
Iteration: 2 The condition i <= 5 is checked before each
Iteration: 3 iteration.
Iteration: 4 The loop stops when i becomes 6.
Iteration: 5
The do-while Loop
The do-while loop is similar to the while loop, but it
guarantees that the loop body is executed at least once,
even if the condition is false.
Output: Explanation:
Iteration: 1 The loop body is executed first, and then the
Iteration: 2 condition i <= 5 is checked.
Iteration: 3 The loop stops when i becomes 6.
Iteration: 4
Iteration: 5
Comparison of Loops
Feature for Loop while Loop do-while Loop
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
The Nested Loops
You can place one loop inside another loop to create nested loops.
This is useful for working with multi-dimensional data structures
like matrices.
Output: Explanation:
The outer loop runs 3 times.
i = 1, j =i = 2, j i = 3, j
For each iteration of the outer
1 =1 =1 loop, the inner loop runs 3
i = 1, j =i = 2, j i = 3, j times.
2 =2 =2
i = 1, j =i = 2, j i = 3, j
Loop Control Statements
C++ provides two important keywords to control the flow of
loops:
1. break: Exits the loop immediately.
2. continue: Skips the rest of the current iteration and
proceeds to the next iteration.
Example 5: Using break and
continue
Infinite Loops
An infinite loop occurs when the loop condition
never becomes false. This can happen accidentally
or intentionally.
Example 6: Infinite Loop
Explanation:
The condition true is always true, so the loop never ends.
Use Ctrl+C to terminate the program manually.