For Loop in C

In this tutorial, we will learn about for and nested for loop in C. For loop is also known as a counter-controlled loop, it means it is used whenever we know the number of repetition. For loop has three parameter, initialisation, condition, and increment/decrement. Below syntax and several examples will explain in detail about for loop.

The Syntax of For Loop

for(initialisation; condition; increment/decrement)
{
	//statements
}

Here we will learn, how for loops work and sequence of the process in the for loop.

  1. Initialisation – First step in for loop is to assign an initial value. It occurs only one time.
  2. Condition – This is the second step, and the number of iteration depends on condition.
  3. statements – If the condition is true, then statements are executed.
  4. increment/decrements – At the end (after execution), increment or decrements occurs.

Example 1: C Program to print 10 to 1, using for loop.

#include<stdio.h>
int main()
{
int n;
	for(n=10;n>=1;n--)
	{
		printf("%d\t",n);
	}	
return 0;
}
Sample Output:
10 9 8 7 6 5 4 3 2 1

Nested For Loop in C.

When a loop is used as a statement in another loop, it is known as a nested loop. The main loop is called the outer loop and, the loop inside the main loop is called the inner loop. When outer loop executes once, then the inner loop completes the cycle every time, till the condition of the outer loop is not false.

Example 2: C example of nested loop in C language.

#include<stdio.h>
int main()
{
int i,k;
	for(i=1;i<=5;i++)
	{
		for(k=1;k<=5;k++)
		{
			printf("%d",k);
		}
	printf("\n");
	}
return 0;
}
Sample Output:
12345
12345
12345
12345
12345

In the above nested for loop example, when the outer loop executes once, then the inner loop repeat for five times, then print the value of k, 1 2 3 4 5, after that changed the line on each execution.

Example 3: Another nested for example in C.

#include<stdio.h>
int main()
{
int i,k;
	for(i=1;i<=5;i++)
	{
		for(k=1;k<=i;k++)
		{
			printf("%d",k);
		}
	printf("\n");
	}
return 0;
}
Sample Output:
1
12
123
1234
12345

Example 4: One more example of nested for in C language.

#include<stdio.h>
int main()
{
int i,k;
	for(i=5;i>=1;i--)
	{
		for(k=1;k<=i;k++)
		{
			printf("%d",k);
		}
	printf("\n");
	}
return 0;
}
Sample Output:
12345
1234
123
12
1