Loops in C – Types and Examples

In this article, we will learn about Loops in C which is an important topic. So let’s start!!!

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is a loop?

In a programming language, the purpose of a loop is for executing a block of code repeatedly until the required condition satisfies. 

Look at the image below. If the condition is not true, then it will exit out of the program. And if the condition is true then it will execute the conditional code. 

Why use loops in C?

1. It is a very useful and efficient feature of C.

2. If you want to write some blocks of code again and again, then you will require a loop for this kind of work. It will become lazy work if you want to do it manually.

Advantages of Loop in C

1. It provides code reusability.

2. And we do not have to write the same code again and again.

3. It makes your programming easy.

Types of Loop in C

Looping in C further categorized into two types:-

1. Entry Controlled Loop:-

Also known as pre-checking loop. Before executing the loop, the condition is checked first. 

2. Exit Controlled Loop:-

Also known as post-checking loop. The condition is checked after executing the loop.

Following are the types of loop available in the C programming language:-

1. For loop in C:-

Suppose, a programmer knows the number of iteration in advance and he wants to execute some block of code until the provided condition satisfies, then in that case a for loop is a better option for him. 

Syntax of C for loop:-

for(initialization;condition;incr/decr){  
//statements 
}

Working of for loop in C

1. initialization executed only once. In this statement, you need to initialize a variable.
2. If the condition is false, then it terminates the for loop. And if the condition is true then it continues.
3. If the condition is true, the statements inside the body of the for loop get executed. And it gets updated.

Working of For Loop in C

Example of for loop in C:-

#include <stdio.h>
int main() {
int num=10,sum=0,incr;
for(incr = 1; incr <= num; ++incr)
  {
    	sum += incr;
  }
printf("Welcome to TechVidvan Tutorials...\n\n");
printf("Sum of the first %d numbers = %d", num,sum);
  return 0;
}

Output

Welcome to TechVidvan Tutorials…
Sum of the first 10 numbers = 55

2. While loop in C

In case if you do not know the number of iterations in advance then while loop is a suitable option for you to use. In a while loop, a block of code gets executed until the condition satisfies.

Syntax of while loop in C:-

while(condition){  
//body of the loop  
}

Working of C while loop:-

1. First the while loop checks for the condition.
2. If the condition is true, the statements inside the body of the while loop get executed until the condition is false.
3. If the condition is false, the while loop terminates.

Working of While Loop in C

Example of while loop in C:-

#include<stdio.h>  
int main(){   
printf("Welcome to TechVidvan Tutorials...\n");
int i=1,number=10;    
while(i<=10){
printf("%d * %d = %d \n", number, i, (number*i));    
i++;    
}    
return 0;  
}

Output

Welcome to TechVidvan Tutorials…
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

3. Do while loop in C:-

Do while loop is similar to while loop, but there is a difference between them. The difference is that the statements inside the body of this loop get executed at least once.

Syntax of C do while loop:-

do
{
   // the body of the loop
}
while (condition);

Working of do while loop:-

1. Body of the do while loop gets executed at least once.
2. If the condition is true, then the body of the do while loop gets executed again until the given condition is false.
3. If the condition is false, the do while loop gets terminated.

Do While Loop in C

Example of do-while loop in C:-

#include<stdio.h>
int main(){
int number = 10;
int factorial = 1;
printf("Welcome to TechVidvan Tutorials...\n\n");
do {
  factorial *= number--;
} while (number > 0);

printf("factorial of 10 is %d\n", factorial);  
}

Output

Welcome to TechVidvan Tutorials…
factorial of 10 is 3628800

4. Infinite for loop in C:-

If the condition never becomes false then the loop becomes an infinite loop. Generally for this, you can use a for loop.
To do an infinite loop in C, use for( ; ; ).

Following is the code to do an infinite loop:-

#include <stdio.h>
int main () {
for( ; ; ) {
printf("Welcome to TechVidvan Tutorials..\n");
}
return 0;
}

If you want to terminate the infinite loop, press Ctrl + C keys.

5. Infinite while loop in C:-

If we pass any non zero value to the condition, then it will do an infinite loop.
Example:-

#include <stdio.h>
int main () {
while(1){
  printf("Welcome to TechVidvan Tutorials...\n");
}
return 0;
}

Output

infinite loop

6. Infinite do while loop in C:-

If we pass any non zero value to the conditional expression, then it will result in an infinite loop.

For Example:-

#include <stdio.h>
int main () {
do{
  printf("Welcome to TechVidvan Tutorials...\n");
}while(1);
return 0;
}

Output

infinite loop

7. Infinite loop using goto statement:-

Using a goto statement to do an infinite loop.

infinite_loop;  
// body  
goto infinite_loop;

8. Infinite loop using macro:-

We can also do an infinite loop by using a macro constant.

For Example:-

#include <stdio.h>  
#define do_infinite for(;;)  
int main()  
{  
do_infinite{  
printf("Welcome to TechVidvan Tutorials...\n");  
}  
return 0;  
}

Output

Infinite loop…

9. Unintentional infinite loops:-

Sometimes, an infinite loop happens unintentionally. It can happen due to a bug in the code. To avoid this type of mistakes, you have to examine the code carefully. Look into the semicolons. Sometimes, we put semicolons in the wrong place.

For Example:-

#include <stdio.h>  
int main()  
{  
int a=1;  
while(a<=5);  
{  
printf("Welcome to TechVidvan Tutorials...\n");  
}  
return 0;  
}

The above code will result in an infinite loop. Because we put the semicolon after the condition of the while loop.

1. We should also check the assignment operator correctly. Sometimes instead of ‘=’, we put ‘==’ operator which results in an infinite loop.

For Example:-

#include <stdio.h>  
int main()  
{  
char s='T';  
while(s='D')  
{  
printf("Infinite Loop..\n");  
}  
return 0;  
}

2. If you use the wrong loop condition in your code then it will result in an infinite loop.

For Example:-

#include <stdio.h>  
int main()  
{  
for(int i=5;i>=5;i++)  
{  
printf("infinite loop..\n");  
}  
return 0;  
}

In the above code, we put i>=5 and it will always result true for every condition.

3. You should be careful when you are using break statements inside the nested loops. If you make any mistake then it will result in an infinite loop.

For Example:-

while(1)  {  
for(int a=10;a>0;a--)  {  
if(i%2==0)  {  
break;
}  
}  
}

In the above code, we use the break statement inside the inner loop. And it will result in an infinite loop.

When to use an infinite loop in C?

1. This is useful for those applications which take user input and generate the output continuously until the user exits.
2. You play games. But you know that these games also run in an infinite loop. It won’t end until the user wants to.
3. All the operating systems and servers run in an infinite loop. It does not exit until the user shuts the computer or the server.

Nested Loops in C

By the help of this technique, you can use one loop inside of another loop.

Syntax of C nested loop:-

Outer-loop  {  
Inner-loop  {  
     	// statements of inner loop!  
 }  
   	// statements of outer loop!  
}

Syntax of nested for loop:-

for ( initialization; condition; increment ) {
for ( init; condition; increment ) {
//statements
}
//statements
}

Example of nested for loop:-

#include <stdio.h>
int main () {
int num=2;
printf("Welcome to TechVidvan Tutorials..\n");
for(int i=1;i<=num;i++){
  for(int j=1;j<=2;j++){
    	printf("%d * %d = %d\t",i,j,(i*j));
  }
}
return 0;
}

Output

Welcome to TechVidvan Tutorials..
1 * 1 = 1 1 * 2 = 2 2 * 1 = 2 2 * 2 = 4

Syntax of nested while loop:-

while(condition)  
{  
while(condition)  
{  
// inner loop statements.  
}  
// outer loop statements.  
}

Example of nested while loop in C:-

#include <stdio.h>
int main () {
int a=1;
printf("Welcome to TechVidvan Tutorials!\n\n");
while(a<=2){
  printf("It is inner loop!\n");
  int b=2;
  while(b<=4){
    	printf("It is outer loop!\n");
    	b++;
  }
  a++;
}
return 0;
}

Output

Welcome to TechVidvan Tutorials!It is an inner loop!
It is an outer loop!
It is an outer loop!
It is an outer loop!
It is an inner loop!
It is an outer loop!
It is an outer loop!
It is an outer loop!

Syntax of nested do-while loop in C:-

do  
{  
do  
{   
// Statements of inner loop  
}while(condition);  
// Statements of outer loop  
}while(condition);

Example of nested do while loop:-

#include <stdio.h>
int main () {
int a=1;
do  
{
int b=1;
do  
{   
printf("Welcome To TechVidvan Tutorials..\n"); // inner loop statements.  
b++;
}while(b<=2);  
printf("*\n");// outer loop statements.  
a++;
}while(a<=2);
return 0;
}

Output

Welcome To TechVidvan Tutorials..
Welcome To TechVidvan Tutorials..
*
Welcome To TechVidvan Tutorials..
Welcome To TechVidvan Tutorials..
*

Loop Control Statements in C

If a programmer wants to change the execution from its normal sequence then loop control statements like break, continue will make that work easy for him.

1. Break Statement in C:-

The purpose of the break control statement is mainly in terminating the loop or in switching statements. A programmer can use C break statements in following two scenarios:-

1. With switch case

2. With loop

Syntax:-

break;

Flowchart of Break:-

Loops in Working of Break Statement

Example of a break statement:-

#include<stdio.h>  
#include<stdlib.h>  
void main ()  
{  
int num;  
for(num = 1; num<8; num++)  
{  
printf("%d\n",num);  
if(num == 4)  
break;  // breakpoint at number 4!
}  
printf("Welcome To TechVidvan Tutorials..\n");
}

Output

1
2
3
4
Welcome To TechVidvan Tutorials..

Example of break statement with while loop:-

#include <stdio.h>
int main () {
int a = 10;
while( a < 15 ) { // doing a while loop
printf("value of a: %d\n", a);
a++;
if( a >= 13) {
// terminate the loop using break statement
break;
}}
return 0;
}

Output

value of a: 10
value of a: 11
value of a: 12

Example of break statement with nested for loop:-
NOTE:- Only breaks the inner loop, not outer loop.

#include<stdio.h>  
int main(){  
for(int i=1;i<=3;i++){ 	 
for(int j=1;j<=3;j++){    
printf("%d Welcome to TechVidvan Tutorials..\n",i,j);    
if(i==2 || j==2){    
break;  // breaking inner loop 
}    
}
}
return 0;  
}

Output

1 Welcome to TechVidvan Tutorials..
1 Welcome to TechVidvan Tutorials..
2 Welcome to TechVidvan Tutorials..
3 Welcome to TechVidvan Tutorials..
3 Welcome to TechVidvan Tutorials..

Example of break statement using do while loop:-

#include <stdio.h>
int main () {
int b = 10;
printf("Welcome to TechVidvan Tutorials..\n");
do {
printf("value of b: %d\n", b);
b = b + 1;
if(b==12){
  break;
}
}while( b < 20 );
return 0;
}

Output

Welcome to TechVidvan Tutorials..value of b: 10
value of b: 11

Continue Statement in C:-

Suppose, if a programmer wants to skip an iteration but he also wants to remain in the loop then a continue statement is a good choice for him to use.

Syntax:-

continue;

Following is the code to perform continue control statement in C:-

#include <stdio.h>
int main () {
int i = 10;
do { // doing a do while loop
if( i == 12) {
i = i + 1; //incrementing the value of i by 1
continue;
}
printf("value of i: %d\n", i);
i++;
} while( i < 14 );
return 0;
}

Output

i = 10
i = 11
i = 13

Example of continue statement with nested loop:-
NOTE:- It only continues the statement in the inner loop not in the outer loop.

#include<stdio.h>  
int main(){  
int i=2,j=2;    
for(i=2;i<=4;i++){ 	 
for(j=3;j<=5;j++){    
if(i==2 && j==3){    
continue;//loop of j will continue    
}    
printf("%d-->%d\t",i,j);    
}    
}    
return 0;  
}

Output

2–>4 2–>5 3–>3 3–>4 3–>5 4–>3 4–>4 4–>5

Goto Statement in C:-

You can also call it a jump statement. Mainly used for transferring control to a labelled statement.
Syntax:-

jump_to_statement:   
//body   
goto jump_to_statement;

Example:-

#include <stdio.h>
int main () {
int a = 10;
printf("Welcome to TechVidvan Tutorials...\n");
LOOP:do { // setting label
if( a == 12) {
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 15 );
return 0;
}

Output

Welcome to TechVidvan Tutorials…
value of a: 10
value of a: 11
value of a: 13
value of a: 14

Which loop to select in C?

1. First, analyze the problem.
2. If it requires a pre-test loop, then use for or while loop.
3. But if it requires a post-test loop, then use do while loop.

Summary

Loops are one of the powerful and key features of C. Loops are of 2 types:- Entry-controlled and Exit-controlled.

Following types of loop available in C:- for loop, while loop, do while loop

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.