LAST UPDATED ON: SEPTEMBER 17, 2024
Loops in C
During programming, sometimes we might need to execute a certain code statement again and again. We can write the code statement as many times as we need it to execute but that would be very inefficient, because what if you want a code statement to execute a 100 times? This is why we use loops.
In any programming language including C language, loops are used to execute a single statement or a set of statements, repeatedly, until a particular condition is satisfied.
How Loops in C works?
The below diagram depicts a loop execution,
As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false then the execution breaks out of the loop. After the loop is successfully executed the execution again starts from the Loop entry and again checks for the Test condition, and this keeps on repeating.
The sequence of statements to be executed is kept inside the curly braces { }
known as the Loop body. After every execution of the loop body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check returns false, the loop body is not executed, and execution breaks out of the loop.
Loops are broadly classified into two types:
1. Entry controlled loops
In this kind of loop, the condition is checked before executing the loop's body. So, if the condition is never true, it won't execute even once. For example, for
and while
loop.
2. Exit controlled loops
In this kind of loop, the condition is checked after the loop's body is executed, i.e., in the end. Hence, even if the condition is not fulfilled, this loop will execute one time. The do-while loop is an example of exit controlled loop.
Types of Loop in C
There are 3 types of Loop in C language, namely:
while
loop
for
loop
do while
loop
1. while
loop in C
The while
loop is an entry controlled loop. It is completed in 3 steps.
- Variable initialization.(e.g
int x = 0;
)
- condition(e.g
while(x <= 10)
)
- Variable increment or decrement (
x++
or x--
or x = x + 2
)
Syntax of while
Loop:
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
The following flowchart shows the flow of execution when we use a while
loop.
Here, we can see that firstly, we initialize our iterator. Then we check the condition of while
loop. If it is false, we exit the loop and if it is true, we enter the loop. After entering the loop, we execute the statements inside the while
loop, update the iterator and then again check the condition. We do the same thing unless the condition is false.
Program to print your name n times using while
loop
In this program we will use the while
looop to print a word a given number of time.
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of times you want to print your name:");
scanf("%d", &n);
char name[30];
printf("Enter your name:");
scanf("%s", name);
while(n) {
//here we are checking if n is non-zero
printf("%s\n", name);
n--; //decrementing n
}
return 0;
}
Enter the number of times you want to print your name:3
Enter your name:studytonight
studytonight
studytonight
studytonight
Run Code →
Let's dry run of the above code:
Firstly, we input n = 3, then name = studytonight?.
Now, we reach the while
loop so we check the condition; n = 3, which is nonzero, so we enter the loop. We execute the printf()
statement and print name on the console and then decrement n
, so now n = 2. We again check the condition; n = 2, which is nonzero, so we enter the loop and print name and decrement n
. Now n = 1. We check the condition again; n is 1 which is nonzero so we again enter the loop and execute the statements. Now we have n = 0. We check the condition; n is zero now so we don't enter the loop. We exit the loop and start executing the statements after it.
Let's see another example.
Program to print first 10 natural numbers using while
loop
#include<stdio.h>
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1 */
x++;
}
}
1 2 3 4 5 6 7 8 9 10
2. for
loop in C
The for
loop in C is used to execute a set of statements repeatedly until a particular condition is satisfied. We can say it is an open ended loop. General format is,
for(initialization; condition; increment/decrement)
{
statement-block;
}
In the for
loop in C language, we have exactly two mandatory semicolons, one after initialization and second after the condition. In this loop we can have more than one initialization or increment/decrement as well, separated using comma operator. But it can have only one condition.
The for
loop is executed as follows:
- It first evaluates the initialization code.
- Then it checks the condition expression.
- If it is true, it executes the for-loop body.
- Then it evaluate the increment/decrement condition and again follows from step 2.
- When the condition expression becomes false, it exits the loop.
Following is a flowchart explaining how the for
loop executes.
We first initialize our iterator. Then we check the condition of the loop. If it is false, we exit the loop and if it is true, we enter the loop. After entering the loop, we execute the statements inside the for
loop, update the iterator and then again check the condition. We do the same thing unless the test condition returns false.
Program to print your name n times using for
loop
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of times you want to print your name:");
scanf("%d", &n);
char name[25];
printf("Enter your name:");
scanf("%s", name);
for(int i = 1; i <= n; i++) { //here we are checking if n is non-zero
printf("%s\n", name);
}
return 0;
}
Enter the number of times you want to print your name:4
Enter your name:studytonight
studytonight
studytonight
Run Code →
Let's dry run of the above code:
Firstly, we input n = 3, then name = studytonight.
Now, we reach the for
loop so we initialize i with 1. We check the condition; 1 <= 3, so we enter the loop. We execute the printf()
statement and print name on the console. We again reach the for
loop. We increment i by 1; so now i = 2. We again check the condition; 2 <= 3, so we enter the loop and print name. Now i is incremented again to 3. We check the condition again; 3 <= 3, so we enter the loop and execute the statements. Now we have i = 4. We check the condition; 4 > 3, so we don't enter the loop. We exit the loop and start executing the statements after it.
Program to print first 10 natural numbers using for
loop
#include<stdio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
1 2 3 4 5 6 7 8 9 10
3. Nested for
loop in C
We can also have nested for
loops, i.e one for
loop inside another for
loop in C language. This type of loop is generally used while working with multi-dimensional arrays. To learn more about arrays and how for
loops are used in arrays, check out our tutorial on arrays in C. Basic syntax for nested for
loop is,
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
Program to print half Pyramid of numbers using Nested loops
#include<stdio.h>
void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}
1
21
321
4321
54321
4. do while
loop in C
In some situations it is necessary to execute body of the loop once before testing the condition. Such situations can be handled with the help of do-while
loop. The do
statement evaluates the body of the loop first and at the end, the condition is checked using while
statement. It means that the body of the loop will be executed at least once, even though the starting condition inside while
is initialized to be false. General syntax is,
do
{
.....
.....
}
while(condition)
Remember that the semicolon at the end of do-while loop is mandatory. It denotes end of the loop.
Following is the flowchart for do-while loop:
We initialize our iterator. Then we enter body of the do-while loop. We execute the statement and then reach the end. At the end, we check the condition of the loop. If it is false, we exit the loop and if it is true, we enter the loop. We keep repeating the same thing unless the condition turns false.
Program to print your name N times using do-while
loop
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of times you want to print your name:");
scanf("%d", &n);
char name[25];
printf("\nEnter your name:");
scanf("%s", name);
do{
printf("%s\n", name);
n--;
}while(n < 0);
return 0;
}
Enter the number of times you want to print your name: 10
Enter your name: studytonight
studytonight
Run Code →
Dry run of the above code:
Firstly, we input n = 10, then name = studytonight.
Now, we enter the do-while loop because we check the condition only at the end. When we reach the end, we check the condition; n = 10, which is greater than zero, so we exit the loop and start executing the statements after it. Here we can see that even if the condition was always false, the loop got executed once.
Program to print first 10 multiples of 5 using do-while
loop
#include<stdio.h>
void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}
5 10 15 20 25 30 35 40 45 50
Infinite Loops in C
We come across infinite loops in our code when the compiler does not know where to stop. It does not have an exit. This means that either there is no condition to be checked or the condition is incorrect. This is why an iterator is very important in our loops. And a proper condition that ends.
Let's see a few examples of infinite loops in C:
#include <stdio.h>
int main()
{
for(int i = 0; ; i++)
printf("Infinite loop\n");
return 0;
}
The above code has no condition in place, hence it will keep on executing.
#include <stdio.h>
int main()
{
int i = 0;
while(i == 0)
printf("Infinite loop\n");
return 0;
}
In the code above, we are not changing the value on i
, hence the condition in the while
loop will never fail.
#include <stdio.h>
int main()
{
do{
printf("Infinite loop\n");
} while(1);
return 0;
}
Another example, with a constant value as condition, which is always true hence the code will keep on executing.
Jumping Out of Loops in C
Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becomes true. This is known as jumping out of loop.
1. break statement in C
When break
statement is encountered inside a loop, the loop is immediately exited and the program continues to execute with the statements after the loop.
Let's see a code example,
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of times you want to print your name:");
scanf("%d", &n);
char name[25];
printf("\nEnter your name:");
scanf("%s", name);
for(int i = 1; i <= n; i++) {
if(i % 5 == 0)
break;
printf("%s\n", name);
}
return 0;
}
Enter the number of times you want to print your name:7
Enter your name:studytonight
studytonight
studytonight
studytonight
studytonight
In the above code, as soon as we find an index which is divisible by 5, the loop breaks and control is shifted out of the loop.
2. continue statement in C
It causes the control to go directly to the test-condition and then continue the loop execution. On encountering continue
, the execution leaves the current cycle of loop, and starts with the next cycle.
Let's see a code example,
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of times you want to print your name:");
scanf("%d", &n);
char name[25];
printf("\nEnter your name:");
scanf("%s", name);
for(int i = 1; i <= n; i++) {
if(i % 2 == 0)
continue;
printf("%d : %s\n",i,name);
}
return 0;
}
Enter the number of times you want to print your name:5
Enter your name:studytonight
1 : studytonight
3 : studytonight
5 : studytonight
In the above example, whenever we come across an even index, we move on to the next index because of the continue statement.
Conclusion
In this tutorial, we have learned about for
, while
and do-while
loops in C and why they are important, along with seeing them in action with multiple code examples. We also learnt about break
and continue
statements.