Why is it the output enters new line after 3? like this:
9
8 7
6 5 4
3
2 1
any number i input it always enters a new line after 3. My target output should be like this when i input 9:
9
8 7
6 5 4
3 2 1 0
Will you please clarify to me why is it enters a new line after 3?
public class TriangleWithInput {
/**
* @param args
*/
@SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int input = sc.nextInt();
while (input >= 0) {
int c = 1;
while ( c <= input) {
int r = 1;
while (r <= c) {
System.out.print(input + " ");
input--;
r++;
}
System.out.println();
c++;
}
}
}
}
You seem to have one too many nested loops. You are getting a new line because of the test
c <= input; wheninputreaches 3 andc >= 3, you do a line break and resetcto 1.I’d write your loops like this: