+ 1
Question about for loops
Can someone please break down, step by step, what is happening in this program? I'm having trouble understanding the how and why. Please and thank you public class StarTest{ public static void main(String [] args){ int row=1; int n = 10; for(int i=1; i<=n; i++) { for(int j = 1 ; j<=row; j++){ System.out.print(j); } for(int j = row+1; j<=n; j++){ System.out.print("*"); } System.out.println(); row++; } } } /* 1********* 12******** 123******* 1234****** 12345***** 123456**** 1234567*** 12345678** 123456789* 1234567890 */
3 Answers
+ 2
@John Wells Perfect! Thank you!
0
public class StarTest{
public static void main(String [] args){
// Initialize row and n. Note: row isn't needed as
// it's value is the same as i.
int row=1;
int n = 10;
// For each line to output, process the line
for(int i=1; i<=n; i++)
{
// For the columns we need to output a number, do so.
for(int j = 1 ; j<=row; j++){
System.out.print(j);
}
// For the remaining columns, output a star.
for(int j = row+1; j<=n; j++){
System.out.print("*");
}
// Finish the line off and increment the row to switch
// from numbers to stars.
System.out.println();
row++;
}
}
}
0
Any other questions?