Types of Loops in C and C++?
In this in-depth article, learn about the types of loops in C and C++.
Join the DZone community and get the full member experience.
Join For FreeLoops in a programming language is a piece of code that get executed repeatedly until the specified condition becomes false. A loop consists of two parts, a block of statements and a condition that control the loop.
Loops mainly consisted of three statements – initialization condition, test condition, update condition.
For example, if we want to print “Hello Codies” 5 times, we can do this in two ways. Writing the statement 5 times (#1) or use loops which save time and effort (#2).
xxxxxxxxxx
#1
#include <stdio.h>
int main()
{
printf("Hello Codies\n");
printf("Hello Codies\n");
printf("Hello Codies\n");
printf("Hello Codies\n");
printf("Hello Codies\n");
return 0;
}
xxxxxxxxxx
#2
#include <stdio.h>
int main()
{
int i;
// Writing a for loop
// to print Hello Codies 5 times
for (i = 1; i <= 5; i++) {
printf("Hello Codies\n");
}
return 0;
}
Output:
xxxxxxxxxx
Hello Codies
Hello Codies
Hello Codies
Hello Codies
Hello Codies
In this tutorial, you will learn-
- Types of Loops
- While Loop
- Do-While loop
- For loop
- Nested loop
- Break Statement
- Continue Statement
Types of Loops in C/C++
Loops are classified into two types depending upon the position control statements:
- Entry controlled loop
- Exit controlled loop
Entry controlled loop: A conditional statement is evaluated before executing the body of a loop. It is also called as a pre-checking or Counter controlled loops where the programmer already know how many times the loop get executed. Counter controlled loops are often called definite iteration because the number of repetitions is known before the loop begins execution.
Exit controlled loop: In this type of loops conditional statement are evaluated after executing the loop body once irrespective of whether the test condition is true or false. It is also called as a post-checking or Sentinel controlled Loop because the programmer don’t know exactly know how many times loop will be executed. Sentinel-controlled loop also known as indefinite repetition.
The control conditions must be specified properly otherwise the loop will execute infinite number of times (infinite loop). An infinite loop occurs when no termination condition is specified or specified conditions never meet.
C programming language provides us with 3 types of loop and C++ has 4th extra loop:
- while loop
- do-while loop
- for loop
- Nested Loop (only in C++)
The syntax of these loops mainly differs in the placement of these three statements initialization condition, test condition, update condition.
While Loop in C/C++
The while loop specify that a program should repeat set of instruction inside the block till the condition remains true. While loop used in place where we don’t know number of iteration before and it depends on the update inside the block. While loop is Entry Controlled loop and widely used in C/C++.
Syntax of WHILE Loop:
xxxxxxxxxx
initialization condition;
while (test_ condition)
{
// statements
update_ condition;
}
Flow Chart of While loop.
In While loop, condition evaluated first if condition is TRUE than block of statements get executed and update condition then control again goes back at the beginning, and the condition is checked again if it is true, the same process is executed until the given condition becomes false. Once the test condition results FALSE control goes back to main program. While Loop is Entry-Controlled Loop.
Note: If Loop contains only one statement, then the curly braces are not compulsory. Though It is a good practice to include braces.
Following program illustrates a while loop:
xxxxxxxxxx
#include<stdio.h>
int main()
{
int num=1; //initializing the variable
while(num<=5) //while loop with test condition
{
printf("%d ",num);
num++; //incrementing (update condition)
}
return 0;
}
Output:
xxxxxxxxxx
1 2 3 4 5
The above program prints series of numbers from 1 to 5 using a while loop.
Let’s see what happening in above program step by step.
Step 1: We have initialized variable ‘num = 1’.
Step 2: In while condition we are evaluating is ‘num’ value is less than or equal to 5, if ‘num’ becomes greater than 5 than this condition become False.
Step 3: For now ‘num = 1’, we enter the loop comparing 1 <= 5 which result true so the body of loop i.e. ‘num’ value 1 got printed.
Step 4: In this step ‘num’ value increased by 1 i.e now ‘num = 2’.
Now step 3 get repeated again with ‘num = 2’ and print the ‘num’ value 2, similarly 3,4,5. When ‘num’ got increase to 6 (num =6) while condition become FALSE & loop terminated than control goes back to main() function as there is nothing after loop do program exits with returning 0 indicating that everything went well.
Do-While Loop in C/C++
Do-while loop is almost similar to the while loop except that the body of a loop executed once before test condition is evaluated. It is an Exit-controlled loop.
The basic syntax of do-while loop is as follows:
xxxxxxxxxx
do {
statements
} while (test condition);
Flow Chart of Do – While loop.
Do–while loop used in cases where we have to execute a body of the loop at least once irrespective of the condition. Unlike while loop, In do-while loop the body of a loop is always executed at least once then checks the condition. If the condition is true, then it will again execute the body of a loop else if condition becomes FALSE control goes out of the loop to main program.
Following program illustrates the do-while loop:
xxxxxxxxxx
#include<stdio.h>
int main()
{
int num=6; //initializing the variable
do
{
printf("%d\n",num);
num++; //incrementing (update condition)
}while(num<=5); //while loop with test condition
return 0;
}
Output:
xxxxxxxxxx
6
In the above program, we have initialized ‘num = 6’ and printed the ‘num =6’ without involving while condition which will result in FALSE as 6 > 5. After printing 6 we compared which turned out to be FALSE thus terminating the loop.
Important NOTE about while and Do-while loop:
We can use multiple test condition in both While and Do-while loop using binary operators, follow below program.
Multiple test conditions using binary operators in while loop.
xxxxxxxxxx
#include <stdio.h>
int main()
{
int num=1; //initializing the variable
while(num<=5 && num!=3) //while loop with multiple test condition
{
printf("%d ",num);
num++; //incrementing (update condition)
}
return 0;
}
Output:
xxxxxxxxxx
1 2
Here the while loop body executed only if number is less than equal to 5 and less than 3. To manually compile you need to know Truth table.
Manually compiling above program.
xxxxxxxxxx
num = 1
num < = 5 (true i.e. 1) and num < 3 (true i.e. 1)
1 & 1 = 1(which is true, so the loop executed)
1 got printed (num increased by 1, num=2)
Similarly, 2 got printed (num increased by 1, num=3)
But when
num = 3
num < = 5 (true i.e. 1) and num < 3 (False i.e. 0)
1 & 0 = 0 (Which is False, so loop terminated)
Multiple test conditions in Do-While loop.
xxxxxxxxxx
#include <stdio.h>
int main()
{
int num=6; //initializing the variable
do
{
printf("%d ",num);
num--; //decrementing (update condition)
}while(num<=5 && num > 0); //while loop with test condition
return 0;
}
Output:
xxxxxxxxxx
6 5 4 3 2 1
Here the loop body executed once irrespective of condition than ‘num’ value decreased & compared with while condition. Loop gets terminated only if either one or both the conditions become. To manually compile you need to know Truth table.
xxxxxxxxxx
num = 6 ( 6 got printed irrespective of while condition)
num = 5 (decremented after printing 6)
num < = 5 (true i.e. 1) and num > 0 (true i.e. 1)
1 & 1 = 1(which is true, so the loop executed)
5 printed (num decreased by 1, num=4)
Similarly, 4 got printed (num decreased by 1, num=3)
Similarly, 3 got printed (num decreased by 1, num=2)
Similarly, 2 got printed (num decreased by 1, num=1)
Similarly, 1 got printed (num decreased by 1, num=0)
When
num = 0
num < = 5 (true i.e. 1) and num > 0 (False i.e. 0)
1 & 0 = 0 (Which is False, so loop terminated)
For Loop in C/C++
A for loop is a more efficient loop structure in C/C++ programming. A for loop is a repetition control structure which allows us to execute piece of code a specific number of times. The general syntax of for loop is as follows:
xxxxxxxxxx
for (initial value; condition; increment or decrement)
{
statements;
}
Flow Chart of FOR loop.
- The variable assigned initial value only once in for loop.
- The condition is a Boolean expression that tests and compares the counter (initialized value) for a fixed iteration and stops the for loop when the condition is false.
- The increment/decrement increases (or decreases) the counter by a set value.
Following program illustrates the use of FOR loop:
xxxxxxxxxx
#include<stdio.h>
int main()
{
int i;
for(i=0;i<=10;i++) //for loop to print 0-10 numbers
{
printf("%d ",i); //to print the number
}
return 0;
}
Output:
xxxxxxxxxx
0 1 2 3 4 5 6 7 8 9 10
The above program prints the number series from 0-10 using FOR loop.
Step 1. Declared a variable i of int data type to store values.
Step 2. In loop, we have initialized variable i = 1, than the condition part and the increment part.
Step 3. In loop body, we have a print function to print the value of variable i on a new line in the console. After printing i = 1, the value of i will be incremented, and it will become 2. Now the variable has the value 2. The condition will be evaluated again and since the condition is true loop will be executed, and it will print two on the screen. This loop will keep on executing until the value of the variable becomes 10. After that, the loop will be terminated, and a series of 0-10 will be printed on the screen.
In C/C++, the for loop can have multiple condition separated by commas in each part.
For example:
xxxxxxxxxx
#include<stdio.h>
int main()
{
int i;
for(i=0;i>5,i<=10;i++) //for loop to print 0-10 numbers
{
printf("%d ",i); //to print the number
}
return 0;
}
Output:
xxxxxxxxxx
0 1 2 3 4 5 6 7 8 9 10
Above loop compile without any error, but the twist is the output will be 0-10 because 2nd condition is considered 1st condition is just evaluated and kept aside, whole loop executed on the basis of 2nd condition.
Now, if we you want to test both conditions, use the && operator.
xxxxxxxxxx
#include<stdio.h>
int main()
{
int i;
for(i=6;i>5 && i<10;i++) //for loop to print 6-9 numbers
{
printf("%d ",i); //to print the number
}
return 0;
}
Output:
xxxxxxxxxx
6 7 8 9
And in FOR loop, we can skip the initial value assignment, condition and/or increment by adding a semicolon.
For example:
xxxxxxxxxx
#1 //Skip initialization
i=1
for(;i<5;i++) {
statements;
}
#2 //skip whole for loop statement
int main()
{
int i=1;
for(;;) //for loop to print 1-4 numbers
{
if(i<5){
printf("%d ",i);
i++;}
else
break; //terminate loop when i>=5
}
return 0;
}
Nested Loops
Nested loops mean loop inside other loop for each iteration of the outer loop, the inner loop repeats its entire cycle.
Consider the following example printing a multiplication table:
xxxxxxxxxx
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 3; i++) { // outer loop
for (j = 1; j <= 5; j++) { // inner loop
printf("%d x %d = %d\n", i, j, i*j);
}
printf("\n"); /* blank line between tables */
}
return 0;
}
Output:
xxxxxxxxxx
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
Break Statement
The break in C/C++ is a loop control statement mainly in the switch statement to jump out of switch block after the desired case is met. BREAK also used to terminate the loop when encountered from within a loop, the loop iterations stops and control returns from the loop immediately to the first statement after the loop.
Syntax:
xxxxxxxxxx
break;
Basically break statements are used in the situations where the actual number of iterations not known or we want to terminate the loop based on some condition.
xxxxxxxxxx
#include <stdio.h>
int main() {
int n = 5;
while (n > 0) {
if (n == 3)
break;
printf("%d ", n);
n--;
}
return 0;
}
Output:
xxxxxxxxxx
5 4
Continue Statement
Continue statement is similar to BREAK statement in opposite way, whenever continue statement encountered instead of terminating the loop, it forces loop to execute the next iteration and skips the current iteration in loop.
For example:
xxxxxxxxxx
#include <stdio.h>
int main() {
int n = 0;
while (n < 10) {
n++;
if (n == 5)
continue;
printf("%d ", n);
}
return 0;
}
Output:
xxxxxxxxxx
1 2 3 4 6 7 8 9 10
So, the value 5 is skipped.
Explanation
Consider the above situation where you need to write a program which prints number from 10 to 0 and but not 5. What we did here is we run a loop from 10 to 0 and every time we have to compare the value of iterator ‘n’ with 5. If n equal to 5 than the continue statement executed to force loop continue to next iteration without printing 5.
Please comment if you find anything incorrect or any error.
Published at DZone with permission of Chand Pasha. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Operator Overloading in Java
-
SRE vs. DevOps
-
Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
-
Chaining API Requests With API Gateway
Comments