Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple java program of pyramid [closed]

Tags:

java

I am a beginner in Java programing and I want to print a pyramid ,but due to mistake in coding I am not getting favorable output.

class p1 {
    public static void main(String agrs[]) {
        System.out.println("The Pattern is");
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (j <= i) {
                    System.out.print("  $");
                } else {
                    System.out.print("   ");
                }
            }
            System.out.println();
        }
    }
}

which is showing

The Pattern is

  $            
  $  $         
  $  $  $      
  $  $  $  $   
  $  $  $  $  $

but I want to print

The Pattern is


        $            
       $  $         
      $  $  $      
     $  $  $  $   
    $  $  $  $  $ 
like image 502
user2849331 Avatar asked Nov 27 '22 13:11

user2849331


2 Answers

This code will print a pyramid of dollars.

public static void main(String[] args) {

     for(int i=0;i<5;i++) {
         for(int j=0;j<5-i;j++) {
             System.out.print(" ");
         }
        for(int k=0;k<=i;k++) {
            System.out.print("$ ");
        }
        System.out.println();  
    }

}

OUPUT :

     $ 
    $ $ 
   $ $ $ 
  $ $ $ $ 
 $ $ $ $ $
like image 192
Qadir Hussain Avatar answered Dec 11 '22 15:12

Qadir Hussain


Try this one

 public static void main(String[] args) 
{
     int x=11;
     int y=x/2; // spaces
     int z=1; // *`s

     for(int i=0;i<5;i++)
    {
         for(int j=0;j<y;j++)
        {
             System.out.print(" ");
        }
        for(int k=0;k<z;k++)
        {
            System.out.print("*");
        }

        y=y-1;
        z=z+2;
        System.out.println();  
    }

}
like image 37
Aravin Avatar answered Dec 11 '22 14:12

Aravin