Looping Statements in C

In this tutorial, we will learn about Looping Statements in C. Looping statements helps us to run a piece of code for multiple time. There are many situations while coding when we need to run a piece of code multiple times. There are a total of three looping statements available in C.

  • for loop
  • while loop
  • do-while loop

for loop:

For loop is the most common looping statement. Which helps us to run a piece of code for multiple time. Before going further please check out the syntax to define for loop in C.

Syntax to define for loop in C:

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

As in above Syntax of for loop you can for loop take a total of three expressions which are as follow:

  • Initialization Expression: In this expression, we initialize the counter of the loop from some value. int i=0;
  • Test Expression: In this expression, we add a condition. For example, we want to write 0 to 10 on the screen as in the last expression we have initialise i as 0. It means we will write condition like this 1<=10. It means the loop will run until the value of i<10 to i==10.
  • Update Expression: In this expression, we update the value of the variable which we defined in first expression(Initialization Expression). Most of the time we increment or decrement the values. For Example i++.

To Understand it more wisely check out the following flow chart diagram:

Example Program:

#include <stdio.h>

int main()
{
    int num=2; //change value here to write different table
    for (int i=1; i<=10; i++)
    {
        printf("%d * %d = %d\n",num,i,(num*i));
    }
}

In the above example of for loop. I have written an example program using for loop to show the table of two on-screen.

While Loop:

While loop takes a single expression and it allows to execute code multiple time until the condition goes wrong. To understand it more clearly. Please check out the following syntax to define while loop in C.

while(condition)
   {
      //body of loop
   }

To understand the flow of the while loop you can check the following flow chart diagram.

Looping Statements in C

Example Program:

#include <stdio.h>

int main()
{
    int i=1; 
    while(i<=10)
    {
      printf("Value of i= %d\n",i);
      i++;
    }
}

do-while loop:

The do-while loop is almost similar to while loop except for one difference. do-while loop will run at least once even in the wrong condition Let’s check the syntax of the do-while loop.

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

To understand the flow of the do-while loop. Please check out the following flow chart diagram.

Looing statements in C

Example Program:

#include <stdio.h>

int main()
{
    int i=1; 
    do{
       printf("Value of i= %d\n",i);
       i++;
    }while(i<=10);
}
Spread the love