student_it
student_it

Reputation: 89

Drawing stars up and down

I want to get this result, where _ space characters :

*___*
_*_*_
__*__
    public static void main(String args[]) {

        int level = 2; // quantity line
        int stars = 5; //quantity drawing stars

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

So far, I have drawn,

*__
_*_
__*

And I don't know how to draw up ?

Upvotes: 0

Views: 87

Answers (3)

Pradnya Bolli
Pradnya Bolli

Reputation: 1943

You can try below code and output is what you want..

for(int i=3;i>=1;i--)
{
    for(int j=i;j<3;j++)
       {
          System.out.print(" ");
        }
     for(int j=1;j<=(2*i-1);j++)
        {
            if(j==1 || j==(2*i-1))

            System.out.print("*");

     else
            System.out.print(" ");
          }
            System.out.println("");
 }

Upvotes: 0

Nitika Bansal
Nitika Bansal

Reputation: 749

Steps to solve these type of questions:

  1. consider * as 1 and spaces as 0. Now i need this output :
     10001
     01010
     00100
  1. first 1 is appearing according to row no. Row 0 - 1 at Col 0, Row 1 - 1 at Col 1
  2. Second 1 is appearing at (total columns-current Row index-1)
  3. print 1 for above two condition otherwise zero.
        int rows=3; // quantity line
        int cols=5; //quantity drawing stars
        for(int i=0;i<rows;i++)
        {
            for(int j=0;j<cols;j++)
            {
                int k=cols-i-1;
                if(i==j || j==k)
                    System.out.print("*");
                else System.out.print(" "); 
            }
            System.out.println();
        }

Upvotes: 1

Khalid Shah
Khalid Shah

Reputation: 3232

  int size=10; // Only one parameter is required which is quantity drawing stars
  int length= size%2==0?size/2:size/2+1; // in case of odd one more line need to be print at last on which one Asteric appears.

    for (int i = 0; i < length; i++) { 
      for (int j = 0; j < size; j++) {
        if (i == j || i + j == size - 1) { //condition for diagonals
          System.out.print("*");
        } else {
          System.out.print(" ");
        }
      }
      System.out.println();
    }

Output :

when size = 10;

*        *
 *      * 
  *    *  
   *  *   
    **   

when size = 11

*         *
 *       * 
  *     *  
   *   *   
    * *    
     *   

Upvotes: 0

Related Questions