+ 1

Is there any other way to show this pattern by using for loop?

https://code.sololearn.com/cF7yO740LTrQ/?ref=app Is there any other way to show this pattern by reducing the number of for loops used! If yes then please share.

3rd Jun 2020, 3:45 PM
Kashish
Kashish - avatar
5 Antworten
+ 3
// // Please ask for permission before copying the code below. Tried this one myself. import java.util.Scanner; public class Pattern3 { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n= sc.nextInt(); for(int i=0;i<n;i++){ //This loop is for the spaces that are to be printed. The formula varies according to pattern. for(int j=1;j<=n-i+1;j++){ System.out.print(" "); } //This loop is to print the stars to make a triangle for(int j=1;j<=2*i+1;j++){ System.out.print("* "); } //To start each loop with new line. System.out.println(); } } }
3rd Jun 2020, 4:00 PM
RKK
RKK - avatar
+ 1
Thank you RKK . Actually I did try this before but I made a silly mistake. But now I know what mistake I did.
3rd Jun 2020, 4:27 PM
Kashish
Kashish - avatar
+ 1
if you want your output to have four rows then you can use j<=2*i-1 for 5 rows use j<=2*i+1
3rd Jun 2020, 4:37 PM
RKK
RKK - avatar
0
Hey RKK but I guess I should use " j<=2*i-1" or the first line won't be printed correctly. Thanks for helping
3rd Jun 2020, 4:31 PM
Kashish
Kashish - avatar
0
Ohk
3rd Jun 2020, 4:48 PM
Kashish
Kashish - avatar