Nested for loop in C

Previous
Next

Nested for loop:

  • Defining for loop inside another for loop.
  • Using nested loops, we can process 2 dimensional data (rows & columns).
  • Outer loop represents number of rows
  • Inner loop represents number of columns.
#include<stdio.h>
int main()
{
	int i, j;
	for(i=1 ; i<=5 ; i++)
	{
		for(j=1 ; j<=5 ; j++)
		{
			printf("*");
		}
		printf("\n");
	}
	return 0;
}
#include<stdio.h>
int main()
{
	int i, j;
	for(i=1 ; i<=5 ; i++)
	{
		for(j=1 ; j<=5 ; j++)
		{
			printf("(%d,%d)\t", i, j);
		}
		printf("\n");
	}
	return 0;
}

Output:

(1,1)   (1,2)   (1,3)   (1,4)   (1,5)
(2,1)   (2,2)   (2,3)   (2,4)   (2,5)
(3,1)   (3,2)   (3,3)   (3,4)   (3,5)
(4,1)   (4,2)   (4,3)   (4,4)   (4,5)
(5,1)   (5,2)   (5,3)   (5,4)   (5,5)

Break statement in nested loop:

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

Output:

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

Output:
1 , 1
2 , 2
3 , 3
4 , 4
5 , 5

Continue Statement in Nested for loop:

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

Output:
(1,2)   (1,3)   (1,4)   (1,5)
(2,1)   (2,3)   (2,4)   (2,5)
(3,1)   (3,2)   (3,4)   (3,5)
(4,1)   (4,2)   (4,3)   (4,5)
(5,1)   (5,2)   (5,3)   (5,4)

Crack this code:

#include<stdio.h>
int main()
{
	int i=0;
	for(i=-1 ; i<=12 ; i++)
	{
		if(i<4)
			continue;
		else
			break;
		printf("i val : %d \n", i);
	}
	return 0;
}
Previous
Next

Add Comment

Courses Enquiry Form