C programming for loop


In this tutorial, you will learn about c programming for loop and how it is used in programs. Relevant examples will follow to highlight for loop concept in C.

c programming for loop

for loop in C programming


While writing programs we might need to repeat same code or task again and again. For this C provides a feature of looping which allows a certain block of code to be executed repeatedly unless or until some sort of condition is satisfied even though the code appears once in a program. There are three types of loops in C programming.

There are three types of loops in C programming.

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

for loop in c


Structure of for Loop

for ( statement1; statement2; statement3)
 	{
 	  //body of for loop
 	}

Here, statement1 is the initialization of loop, statement2 is the continuation of the loop. Normally, it is a test condition and statement3 is increment or decrement of a control variable as per need.

For example:

for ( i = 1; i <= 5; i++)
 	{
 	 printf("Hello World!);  //body of for loop
        }

Here in example ‘i’ is the control variable and statement1 is 'i=1' which initializes control variable to 1 and 'i <= 5' is a continuation of the loop which will repeat until the value of ‘i’ exceeds 5.'i++' is statement3 which increases the value of control variable ‘i’ every time by 1. So the above piece of code will print ‘Hello World!’ five times.

Common programming errors
Using commas instead of semicolon in the header expression of for loop

 

Good Programming Practice
If you forget to write statement1, statement2 and statement 3 the loop will repeat forever. To prevent from infinite repetition write conditions carefully and don’t forget to increment or decrement.

 

Here is the block diagram to show how a for loop works:

for loop

Working of typical for repetition statement

for ( counter = 1; counter <= 5; counter++)
      printf("hello\n");

Flowchart

working for loop

Example of for loop

#include<stdio.h>
int main()
{
  int n;
  printf("How many time you want to print?"\n);
  scanf(" %d ", &n);
  for ( i= 1; i<=n; i++) //for loop which will repeat n times
  {
    printf("simple illustration of for loop"\n);
  }
  return 0;
}

Output 

How many time you want to print?
2
simple illustration of for loop
simple illustration of for loop

Explanation:

Suppose user entered value 2. The value of variable ‘i’ is assigned 2. The program will now check test expression 'i <=n', which is true and the program will print ‘simple illustration of for loop. Now the value of ‘i’ is incremented by one and again program will check test expression, which is true and program will print ‘simple illustration of for loop’. Again the value of ‘i’ is incremented by 1. This time test expression will be false and the program will terminate.