Computer Science, asked by tanmaymandal2316, 12 hours ago

12345
22345
33345
44445
55555
nested loops pattern in java ​

Answers

Answered by kamalrajatjoshi94
3

Answer:

Program:-

public class Main

{

public static void main(String args[])

{

int i,j,p=2;

for(i=1;i<=5;i++)

{

for(j=1;j<=i;j++)

System.out.print(i+" ");

for(int k=p;k<=5;k++)

System.out.print(k+" ");

System.out.println();

p++;

}

}

}

Logic:-

  • The pattern is divided in 2 parts

1. 1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

2. 2 3 4 5

3 4 5

4 5

5

  • The first pattern is printed just using a simple 2 loops as I have given.
  • But for the second pattern we notice that the value is changing after each iteration so I initialised a variable p=2 as the next pattern is starting with 2. And after each iteration of the outer loop the value of p will increment to 1.
  • After each iteration it prints value from p.
  • In the first iteration it prints 2 3 4 5 as p is 2.
  • In the second iteration it prints 3 4 5 as p is 3.
  • In the same way next it prints 4 5 and finally it prints 5.
  • Hence the Pattern is made.

Attachments:
Similar questions