Skip to main content

Loops in C programming with example

Loops in C programming with example

A loop is used for executing a block of statements repeatedly until a given condition returns false.

Example of For loop

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

Output:

1
2
3

Nested For Loop in C

Nesting of loop is also possible. Lets take an example to understand this:

#include <stdio.h>
int main()
{
   for (int i=0; i<2; i++)
   {
	for (int j=0; j<4; j++)
	{
	   printf("%d, %d\n",i ,j);
	}
   }
   return 0;
}

Output:

0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3

Example of while loop

#include <stdio.h>
int main()
{
   int count=1;
   while (count <= 4)
   {
	printf("%d ", count);
	count++;
   }
   return 0;
}

Output:

1 2 3 4

Example of while loop using logical operator

In this example we are testing multiple conditions using logical operator inside while loop.

#include <stdio.h>
int main()
{
   int i=1, j=1;
   while (i <= 4 || j <= 3)
   {
	printf("%d %d\n",i, j);
	i++;
	j++;
   }
   return 0;
}

Output:

1 1
2 2
3 3
4 4

Example of do while loop

#include <stdio.h>
int main()
{
	int j=0;
	do
	{
		printf("Value of variable j is: %d\n", j);
		j++;
	}while (j<=3);
	return 0;
}

Output:

Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3

Comments