javafor-loopnested-loops

Print a given number pattern from user input using nested for loop


I am new to programming. Am currently learning Java, on nested loop now, and got stuck.

So what I want to do is to write a program that takes an integer from user and

print lines, for example if user input was 4 then the result should be like:

1

1 2

1 2 3

1 2 3 4

Here is my code so far:

import java.util.Scanner;

public class Hello {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter number of rows:");
        int number = input.nextInt();
        for (int i = 1; i <= number; i++) {
            System.out.println(i);
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
        }
    }
}

But it prints one extra line at the end, like:

1

1 2

1 2 3

1 2 3 4

1 2 3 4

And it is hard for me to figure out why.

I guess it is my first for loop but I don't know how to fix the for loop to get the result I want.

Any help will be appreciated. Thanks!


Solution

  • Don't print anything from the outer loop, only new line

    for (int i = 1; i <= number; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print(j + " ");
        }
        System.out.println();
    }
    

    Output

    1 
    1 2 
    1 2 3 
    1 2 3 4