for loop in C programming with examples

This post was written and published to describe the "for" loop, which is one of the most well-known and widely used loops in the C programming language. So, without further ado, let's get started.

The "for" loop is used to execute a block of code a specified number of times. The general form of the "for" loop in the C programming language is as follows:

for (initialization; condition-checking; update)
{
   // body of the "for" loop
}

The "initialization" statement executes first, but only once. This part is used to either initialize the loop variable or define and initialize the loop variable. For example:

i = 1;

Or

int i = 1;

The "condition-checking" statement executes every time before entering the body of the "for" loop. And to enter the body of the "for" loop, this condition-checking statement must be evaluated to true. Otherwise, the execution of the "for" loop stops.

After execution of the body of the "for" loop, the program flow goes to the "update," the parameter of the "for" loop. This statement is used to update the loop variable to evaluate the condition, and if the condition evaluates to true, then execute the body of the loop using the new value of the loop variable.

for loop example in C

Consider the following program as an example program demonstrating the "for" loop in the C programming language:

#include <stdio.h>
int main()
{
   for(int i=1; i<10; i++)
   {
      printf("The value of 'i' = %d \n", i);
   }

   return 0;
}

The output should be:

The value of 'i' = 1
The value of 'i' = 2
The value of 'i' = 3
The value of 'i' = 4
The value of 'i' = 5
The value of 'i' = 6
The value of 'i' = 7
The value of 'i' = 8
The value of 'i' = 9

In the above program, as I already said, "int i = 1,"  the first statement will be executed at first but only once. Therefore, 1 will be initialized to the variable "i." And the condition "1<10" (on putting the value of "i") evaluates to true, therefore program flow enters the body of the loop and executes the "printf()" statement, then program flow goes to the update part, which is "i++," which increments the value of "i." Now that "i=2," the condition "2<10" evaluates to true once more, and program flow returns to the loop's body. This process continues until the condition is evaluated as false.

Let me modify the above program for your understanding.

#include <stdio.h>
int main()
{
   int num, i, res;

   printf("Enter a number: ");
   scanf("%d", &num);

   for(i=1; i<=10; i++)
   {
      res = num*i;
      printf("%d x %d = %d\n", num, i, res);
   }

   return 0;
}

The above C example program that shows how to use the "for" loop made the first output shown below.

c for loop example

Now type a number, say 5, and hit the ENTER key to see the following output:

c for loop program

More Examples

C Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!