-1
class Starr {
    public static void main(String[] args) {
        int res;
        for(int i=1;i<=5;i++) {
            for(int j=1;j<=5;j++) {
                res=i+j;
                if(res>=6) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();   
        }
    }
}

Output:

    *
   **
  ***
 ****
*****

Expected:

        *
      * *
    * * *
  * * * *
* * * * * 

To get the above expected result i made the following changes,

  {
    System.out.print(" *"); /* Added a space before '*' */
  }
  else
  {
    System.out.print("  "); /* Added 2 spaces */
  }

I would like to know if this expected result can be achieved in another logic where i don't have to change the print statement. Whatever changes i have done is a right approach?

beginnr
  • 5
  • 1
  • 5
  • 1
    Considering that the spacing between asterisks is controlled somewhat by the println statement...I'm not sure what you're asking exactly. – Makoto Oct 23 '14 at 19:17
  • Why would you want to do it any other way? The solution is the simplest possible and works well. – Gumbo Oct 23 '14 at 19:19

3 Answers3

0

Check this code, It works!

int res;
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 5; j++) {
        res = i + j;
        String sp = (j != 1) ? " " : "";
        if (res >= 6) {
            System.out.print(sp + "*");
        } else {
            System.out.print(sp + " ");
        }
    }
    System.out.println();
}

Output:

        *
      * *
    * * *
  * * * *
* * * * *
Community
  • 1
  • 1
0

You cannot achieve a way of printing whitespaces between the stars without printing anything, although you can achieve the desired output without using whitespaces. This could be done with System.out.format() or System.out.printf(). format and printf are actually the same thing in practice. For you particularly:

System.out.printf("%2s", "*");

This means that this output should print two characters, out of which the first one should be '*'. The rest will be whitespaces.

Olavi Mustanoja
  • 2,045
  • 2
  • 23
  • 34
0
public class StarPattern {
    public static void main(String[] args) {
        // This loop print the number of * rows
        for (int i = 5; i >= 1; i--) {
            // This prints the empty space instead of *
            for (int j = 1; j < i; j++) {
                System.out.print(" ");
            }
            // Print the * in the desired position
            for (int k = 5; k >= i; k--) {
                System.out.print("*");
            }
            // Move the caret to the next line
            System.out.println();
        }
    }
}

Output:

    *
   **
  ***
 ****
*****
Community
  • 1
  • 1