Search code examples
javaeclipseasterisknested-loops

Asterisk in Nested loops, Java


I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code:

public class Assn4 {
    public static void main(String[] args) {
        for (int i = 0; i <= 3; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print("*");
            }

            for (int x = 0; x <= 1; x++) {
                System.out.println(" ");
            }

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

enter image description here


Solution

  • Matrix problems are really helpful to understand loops..

    Understanding of your problem:

    1) First, printing star at the end- That means your first loop should be in decreasing order

    for(int i =7;i>=0; i+=i-2)

    2) Printing star in increasing order- That means your second loop should be in increasing order

    for(int j =0;j<=7; j++)

    Complete code:

    for(int i =7;i>=0; i=i-2){ // i=i-2 because *s are getting incremented by 2
         for(int j =0;j<=7; j++){
             if(j>=i){ // if j >= i then print * else space(" ")
                System.out.print("*");
             }
             else{
                System.out.print(" ");
             }
        }
        System.out.println();// a new line just after printing *s
    
    }