Loops In C++
Topic asked in February 2022 (CBCS) , July 2022 (CBCS) , September 2021 (CBCS) and March 2021 (CBCS) question paper.
In C++, loops are control statements and are used to execute a block of code repeatedly as long as a specified condition is true.
There are several types of loops available in C++, including the for
loop, the while
loop, and the do-while
loop.
Each type of loop has its own syntax and use cases.
There are 3 types of loops in C++:-
- for loop
- while loop
- do-while loop
for loop
The for
loop is commonly used when you know the exact number of iterations you want to perform.
It consists of three parts: initialization, condition, and increment/decrement.
Here's the syntax:
Here,
-
Initialization: Typically used to initialize a loop control variable. It's executed only once, at the beginning of the loop.
-
Condition: An expression evaluated before each iteration. If the condition is true, the loop continues; otherwise, the loop terminates.
-
Increment/Decrement: Usually used to modify the loop control variable. It's executed after each iteration.
Example:-
Output:-
Explanation:-
Iteration | Variable | i | Action |
---|---|---|---|
1st | i = 1 | true | 1 is printed. i is increased to 2 |
2nd | i = 2 | true | 2 is printed. i is increased to 3 |
3rd | i = 3 | true | 3 is printed. i is increased to 4 |
4th | i = 4 | true | 4 is printed. i is increased to 5 |
5th | i = 5 | true | 5 is printed. i is increased to 6 |
6th | i = 6 | true | 6 is printed. i is increased to 7 |
7th | i = 7 | true | 7 is printed. i is increased to 8 |
8th | i = 8 | false | The loop is terminated |
Ranged Based for Loop
The range-based for loop is a convenient feature introduced in C++11, which simplifies iteration over elements in a container, such as arrays, vectors, and other sequence-like data structures.
Here's the syntax of the range-based for loop:-
- declaration: A variable that will be declared for each iteration, representing the current element in the range.
- range: The range over which to iterate. It can be an array, a container (such as vector, list, etc.), or any sequence-like data structure that provides a begin and end iterator.
Here's an example to illustrate the usage of the range-based for loop:-
Output:-
while loop
A while
loop is a control flow statement in C++ that allows you to execute a block of code repeatedly as
long as a specified condition is true.
It's useful when you don't know the exact number of iterations beforehand and want to continue looping until a certain condition is met.
Here's the basic structure of a while
loop:-
Explanation:-
-
Condition: The loop continues to execute as long as the specified condition evaluates to true. If the condition evaluates to false, the loop terminates, and program control moves to the next statement after the loop.
-
Code Block: The code block inside the loop is executed repeatedly as long as the condition remains true. It contains the statements that you want to repeat.
Example Code:
Here's a simple example of a while loop in C++ that prints numbers from 1 to 5:-
Output:
Explanation of the Code:-
Iteration | Variable | i | Action |
---|---|---|---|
1st | i = 1 | true | 1 is printed. i is increased to 2 |
2nd | i = 2 | true | 2 is printed. i is increased to 3 |
3rd | i = 3 | true | 3 is printed. i is increased to 4 |
4th | i = 4 | true | 4 is printed. i is increased to 5 |
5th | i = 5 | true | 5 is printed. i is increased to 6 |
6th | i = 6 | false | The loop is terminated |
do-while loop
The do-while loop is another type of loop in C++ that is similar to the while loop. However, the difference lies in when the loop condition is evaluated. In a do-while loop, the condition is evaluated after the loop body is executed, meaning that the loop body will always execute at least once, even if the condition is initially false.
Here's the basic syntax of a do-while loop:-
Explanation:
-
Code Block: The block of code inside the do-while loop is executed first.
-
Condition: After executing the loop body, the condition is evaluated. If the condition is true, the loop continues, and the code block is executed again. If the condition is false, the loop terminates.
Example Code:
Let's see an example of a do-while loop in C++ that prints numbers from 1 to 5:-
Output:
When you run the above code, it will print:
Explanation of the Code:-
Iteration | Variable | i <= 5 | Action |
---|---|---|---|
1st | i = 1 | not checked | 1 is printed. i is increased to 2 |
2nd | i = 2 | true | 2 is printed. i is increased to 3 |
3rd | i = 3 | true | 3 is printed. i is increased to 4 |
4th | i = 4 | true | 4 is printed. i is increased to 5 |
5th | i = 5 | true | 5 is printed. i is increased to 6 |
6th | i = 6 | false | The loop is terminated |
Infinite loop
An infinite loop is a loop that continues indefinitely, executing its block of code repeatedly without stopping.
Here's an example of an infinite for
loop in C++:
- The
for
loop has no initialization, condition, or increment/decrement expressions specified inside the parentheses. - Therefore, the loop will continue indefinitely, repeatedly printing "This is an infinite loop." to the console.
An infinite while loop
can be created by specifying a condition that always evaluates to true. Here's an example:
An infinite do-while
loop can be created similarly by specifying a condition that always evaluates to true. Here's an example:
- Since the condition is always true, the while and do-while loop continues to execute indefinitely, repeatedly printing "This is an infinite loop." to the console.
It's essential to exercise caution when using infinite loops because they can lead to programs becoming unresponsive or consuming excessive resources. In practice, infinite loops are often used in conjunction with some kind of termination condition, such as a break statement or an external event that causes the loop to exit. Without a termination condition, the loop will continue indefinitely, which may not be desirable in most situations.
Nested Loops
Topic asked in December 2022 (CBCS) question paper.
Nested loops in C++ refer to the situation where one loop is nested inside another loop. This allows you to iterate over a two-dimensional structure, such as a matrix or a grid, by using an outer loop to iterate over the rows and an inner loop to iterate over the columns (or vice versa).
Here's the general syntax of nested loops:-
for
loop:-
Or with while
loop:-
Or with do-while
loops:-
Example:
Output:-
In this example:-
- The outer loop for (int i = 0; i < 5; ++i) iterates over the rows (i represents the row index).
- The inner loop for (int j = 0; j < 5; ++j) iterates over the columns within each row (j represents the column index).
- Inside the inner loop, we print an asterisk followed by a space.
- After printing all columns in a row, we move to the next line
cout << endl;
, effectively printing each row on a new line.
Checkout another example program of nesting of loops.
Difference between for, while and do-while loop
Feature | for Loop | while Loop | do-while Loop |
---|---|---|---|
Initialization | Initialization statement is included within the loop syntax | Initialization statement is done before the loop starts | Initialization statement is done before the loop starts |
Condition Checking | Condition is checked before each iteration | Condition is checked before each iteration | Condition is checked after each iteration |
Iteration | Increment/decrement operation is often included within the loop syntax | Increment/decrement operation must be done explicitly within the loop body | Increment/decrement operation must be done explicitly within the loop body |
Usage | Preferred when the number of iterations is known beforehand or when iterating over a range | Preferred when the loop may not be executed at all or when the number of iterations is unknown | Preferred when the loop must execute at least once before condition checking |
Break And Continue Statements
Break Statements
Topic asked in July 2022 (CBCS) question paper.
The break
statement is a control flow statement used in loops (such as for
, while
, or do-while
loops) to prematurely exit the loop's execution when a certain condition is met.
When encountered, the break
statement causes immediate termination of the loop containing it, and program execution continues with the statement following the loop.
Example:-
Output:-
Explanation:-
- The for loop iterates from 1 to 5.
- Inside the loop, each value of i is printed followed by a space.
- When i equals 3, the condition if (i == 3) is true, and the break statement is executed, causing immediate termination of the loop.
- As a result, only the numbers 1, 2, and 3 are printed, and the message "Loop terminated." is displayed.
We can also use break
statement with nested loop:-
Output:-
Explanation:-
- The outer loop iterates from 1 to 3.
- The inner loop iterates from 1 to 3.
- When the condition j == 3 is met in the inner loop, the break statement is executed, causing immediate termination of the inner loop.
We can also use break
statement in while
and do-while
loop:-
Example with break
in a while
Loop:
Output:-
Example with break
in a do-while
Loop:
Output:-
In both examples:
- The loop runs endlessly until the break condition is satisfied.
- The break statement is used to exit the loop when i equals 5.
- Once the
break
statement is encountered, the loop immediately terminates, and program execution continues with the statement following the loop.
Continue Statements
The continue
statement is another control flow statement used in loops to skip the rest of the current iteration and proceed with the next iteration of the loop.
When encountered, the continue statement causes the loop to jump immediately to the next iteration,
bypassing any remaining code in the loop body for the current iteration.
Example:-
Output:-
Explanation:-
- The continue statement is used to skip the iteration when i equals 3.
- As a result, the number 3 is skipped, and only the numbers 1, 2, 4, and 5 are printed.
We can also use the continue
statement with nested loops:
Output:-
Explanation:-
- The outer loop iterates from 1 to 3.
- The inner loop iterates from 1 to 3.
- When the condition j == 3 is met in the inner loop, the continue statement is executed, causing the current iteration of the inner loop to be skipped.
We can also use the continue statement in while and do-while loops:
Example with continue
in a while
Loop:
Ouput:-
Example with continue
in a do-while
Loop:
Output:-
In both examples:
- The loop iterates until the condition is satisfied.
- The continue statement is used to skip the current iteration when a certain condition is met.
- As a result, the number 3 is skipped in both loops.
Last updated on -