C: Loops

C prorgamming supports four types of loops:

  • for loop
  • while loop
  • do ... while loop
  • nested loops

C loops also support three additional statements to alter the program sequence:

  • break
  • continue
  • goto

Example: for loop in C


	#include 

	int main()
	{
		int i;
		for(i = 1; i <= 5; i++)
		{
			printf("counter: %d\t\n", i);
		}
		return 0;
	}
	

Output:

  counter: 1
  counter: 2
  counter: 3
  counter: 4
  counter: 5


Example: while loop in C


	#include 

	int main()
	{
		int i = 1;
		while (i <= 5)
		{
			printf("counter: %d\t\n", i);
			i++;
		}
		return 0;
	}
	

Output:

  counter: 1
  counter: 2
  counter: 3
  counter: 4
  counter: 5


Example: do ... while loop in C

A do .... while loop differs from a for and while looop in that the code inside the loop is garunteed to execute at least once as the test condition is at the end/bottom of the loop versus the top.


	#include 

	int main()
	{
		int i = 1;
		do
		{
			printf("counter: %d\t\n", i);
			i++;
		}
		while (i <= 5);
		return 0;
	}
	

Output:

  counter: 1
  counter: 2
  counter: 3
  counter: 4
  counter: 5


Example: Nested loop in C


	#include 

	int main()
	{
		int i = 1, y;
		do
		{
			printf("counter: %d\t\n", i);
			i++;
			for (y = 10; y <= 11; y++)
			{
				printf("   sub-counter: %d\t\n", y);
			}
		}
		while (i <= 2);
		return 0;
	}
	

Output:

  counter: 1
    sub-counter: 10
    sub-counter: 11
  counter: 2     sub-counter: 10
    sub-counter: 11