Skip to content

Loops in C

You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Looping Statements in C execute the sequence of statements many times until the stated condition becomes false. There are three types of loops used in the C language.

A loop in C consists of two parts, a body of a loop and a control statement. The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false.

Loops in C - Loop architechture

Advantage of loops in C

1) It provides code re-usability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

The following video will give you a wonderful overview of loops:

Types of Loops in C

C programming has three types of loops:

  1. for loop
  2. while loop
  3. do while loop

for loops in C

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance.

The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)
{
    // statements inside the body of loop
}

Loops in C - for loop architecture

How for loop works?

  • The initial value of the for loop is performed only once.
  • The test expression is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.
  • The incrementation/decrementation increases (or decreases) the counter by a set value.

Example

Lets take an example that prints table of 2 –

#include<stdio.h>  
int main()
{  
 int i,n=2; 
 for(i=1;i<=10;i++)
 {        
   printf("%d \n",n*i);      
 }     
 return 0;  
}

Output:

2
4
6
8
10
12
14
16
18
20

Properties of Expression 1 (i=1)

  • The expression represents the initialization of the loop variable.
  • We can initialize more than one variable in Expression 1.
  • Expression 1 is optional.
  • In C, we can not declare the variables in Expression 1. However, It can be an exception in some compilers.

Properties of Expression 2 (i<=10)

  • Expression 2 is a conditional expression. It checks for a specific condition to be satisfied. If it is not, the loop is terminated.
  • Expression 2 can have more than one condition. However, the loop will iterate until the last condition becomes false. Other conditions will be treated as statements.
  • Expression 2 is optional.
  • Expression 2 can perform the task of expression 1 and expression 3. That is, we can initialize the variable as well as update the loop variable in expression 2 itself.
  • We can pass zero or non-zero value in expression 2. However, in C, any non-zero value is true, and zero is false by default.

Properties of Expression 3 (i++)

  • Expression 3 is used to update the loop variable.
  • We can update more than one variable at the same time.
  • Expression 3 is optional.

Lets take one more example –

#include<stdio.h>  
void main ()  
{       
  for(;;)       
  {           
    printf("Hello World!");       
  } 
}

Output

What do you think will the output be? How many times will the statement get printed?

The answer is infinite times. This will run forever.

Video explaining for loops and live programming:

Nested for loops in C:

For loops can also be nested inside one another, i.e., for loop inside another for loop. The following video will show you the working of nested for loops

While Loops in C

In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed.

Loops in C - While loop architecture

The syntax of the while loop is:

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

How while loop works?

  • The while loop evaluates the testExpression inside the parentheses ().
  • If testExpression is true, statements inside the body of while loop are executed. Then, testExpression is evaluated again.
  • The process goes on until testExpression is evaluated to false.
  • If testExpression is false, the loop terminates (ends).

Example

Lets take the same example which we had taken in for loop -> multiplication table of 2 –

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

Output

2
4
6
8
10
12
14
16
18
20

Properties

  • A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.
  • The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.
  • In while loop, the condition expression is compulsory.
  • Running a while loop without a body is possible.
  • We can have more than one conditional expression in while loop.
  • If the loop body contains only one statement, then the braces are optional.

 

Lets take one more example –

#include<stdio.h>  
void main ()  
{     
  while()      
 {        
    printf("Hello Nerds");   
  }  
}

 

Can you guess the output of this program?

Output :

compile time error: while loop condition can't be empty

Unlike the for loop, the test Expression or the condition has to be defined in while loop.

The following video explains in details the working of a while loop with live programming:

Nested while loops and Multiple conditions in C:

Like for loops, while loops can also be nested inside another while loop. Moreover, we can also club multiple conditions together inside a while loop condition. The following video explains in details the need and working of nested while loops and multiple conditions with live programming:

Do while loop

The do..while loop is similar to the while loop with one important difference. Unlike for and while loops, which test the loop condition at the top of the loop, the do…while loop in C programming checks its condition at the bottom of the loop. do-while runs at least once even if the condition is false because the condition is evaluated, after the execution of the body of loop.

Loops in C - do while

Syntax

The syntax of a do…while loop in C programming language is −

do {
   statement(s);
} while( condition );

How do…while loop works?

  • The body of do...while loop is executed once. Only then, the condition is evaluated.
  • If condition is true, the body of the loop is executed again and condition is evaluated once more.
  • This process goes on until condition becomes false.
  • If condition is false, the loop ends.

Example

#include <stdio.h> 
int main () 
{ 
   /* local variable definition */ 
   int a = 10; 
   /* do loop execution */ 
   do { 
      printf("value of a: %d\n", a); 
      a = a + 1; 
   }while( a < 20 ); 
   return 0; 
}

Output

value of a: 10  value of a: 11  value of a: 12  value of a: 13
value of a: 14  value of a: 15  value of a: 16  value of a: 17  value of a: 18  value of a: 19

The following video explains do..while loops with live programming:

Conclusion

When checking a condition, if the first iteration is compulsory, we need to use the while loop. It can also be used if the number of iterations is unknown or uncertain.

If the number of iterations is known, we can use for loop.

Do while loop mainly requires in the case where we have to execute the loop minimum one time. The do-while loop is typically needed in a menu-driven programming language where the final condition is based upon the end-user.

Try these loops with various examples for better understanding.

 

Leave a Reply

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