Nested for loop in java to print the following -
how print following in java:
5 55 555 55 5
using nested loop no if statements.
what have far:
public static void main(string[] args) { for(int = 1; < 6; i++) { for(int k = 3; k > i; k--) { system.out.print(" "); } for(int k = 3; k < i; k++) { system.out.print(" "); } for(int j = i; j > 0; j--) { system.out.print("5"); } system.out.println(); } }
as can see, got spaces correct not number of 5
's on each line yet. somehow feel there must possible use 1 loop spaces?
you need first break pattern in 2 parts :
upper half
5 55 555
lower half
55 5
in upper half there 3 rows printed. analyze each row.
- for row no. 1 there 2 blanks , 1 "5".
- for row no. 2 there 1 blank space , 2 "5"s.
- for row no. 3 there no blank space , 3 "5"s.
so if represents rows when 1 i.e. row no. 1 no. of blank spaces printed (3-i) i.e. 2 , no. of "5"s printed i.e. 1.
on similar lines can break complete problem. solution:
class main{ public static void main(string args[]) { for(int i=1;i<=3;i++) { for(int j=1;j<=(3-i);j++) { system.out.print(" "); } for(int j=1;j<=i;j++) { system.out.print("5"); } system.out.println(); } for(int i=1;i<3;i++) { for(int j=1;j<=i;j++) { system.out.print(" "); } for(int j=1;j<=(3-i);j++) { system.out.print("5"); } system.out.println(); } } }
Comments
Post a Comment