Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

I was trying to print the star pattern in Java but it is not working properly. Herewith I have attached by code:

public class q3 {

    public static void main(String[] args) {

        for (int i = 10; i >= 1; i--){

            for (int j = i; j >= 1; j--){

                System.out.print("*");              

            }           

            System.out.println("");

        }

    }

}

Can anyone help me with this?

1 Answer

0 votes
by (26.7k points)

You can try with the below code which will work properly:

public static void main(String[] args) {

    final int length = 10;

    for (int i = 1; i < length; i++) {

        //Print spaces first

        for (int j = length - 1; j > i; j--) {

            System.out.print(" ");

        }

        //Then print "*"

        for (int j = 1; j <= i; j++) {

            System.out.print("*");

        }

        System.out.println();

    }

}

I hope this will help.

Want to know more about Java? Prefer this tutorial on Java Tutorial.

Want to become a Java Expert? Join Java Certification now!!

Related questions

0 votes
1 answer
0 votes
1 answer
asked Apr 6, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Jul 13, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 13, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer

Browse Categories

...