Nested for loop in java

Previous
Next

Nested for loop:

  • Defining a loop inside another loop.
  • Nested loops are used to process the information of 2 dimensional form(rows & columns).
  • Outer loop represents rows and inner loop represent columns while processing the information.
class Test 
{
	public static void main(String[] args) 
	{
		for (int i=1 ; i<=5 ; i++)
		{
			for (int j=1 ; j<=5 ; j++)
			{
				System.out.print("* ");
			}
			System.out.println();
		}
	}
}

Printing below pattern:

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Code:

class Test 
{
	public static void main(String[] args) 
	{
		for (int i=1 ; i<=5 ; i++)
		{
			for (int j=1 ; j<=5 ; j++)
			{
				System.out.print(j + " ");
			}
			System.out.println();
		}
	}
}

Printing Characters pattern:

A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
class Test 
{
	public static void main(String[] args) 
	{
		for (int i=1 ; i<=5 ; i++)
		{
			for (char j='A' ; j<='E' ; j++)
			{
				System.out.print(j + " ");
			}
			System.out.println();
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form