0

I am trying to print the pattern shown below:

*
**
***
****

but I am getting a pattern like this:

*

*
*

*
*
*

*
*
*
*

I am using nested for loops.

public class Patterns
{
    public static void main(String[] args)
    {
        Scanner s=new Scanner(System.in);
        System.out.println ("enter rows");
        int n=s.nextInt();

        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=i; j++)
            {
                System.out.println("*");
            }
            System.out.println("");
        }
        s.close();
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Neha Arora
  • 27
  • 1
  • 4

2 Answers2

3

The problem is that println is adding a newline after printing the * on each line. To fix this, use System.out.print instead of System.out.println in the inner loop:

for (int i=1; i<=n; i++) {
    for(int j=1; j<=i; j++) {
        System.out.print("*");
    }
    System.out.println("");
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

Use System.out.print("*"); instead of println.

Hexronimo
  • 122
  • 1
  • 10