Friday, November 18, 2011

How to print a pyramid of numbers in Java


Write a program which will print the below structures according to the input provided to the program. The program should accept 3 inputs in the form of numbers between 1 and 9, both inclusive (one number per line) and then generate the corresponding structures based on the input.

Suppose the following sequence of numbers is supplied to the program:
3
2
4

Then the output should be:

  1
 2 2
3 3 3
 1
2 2
   1
  2 2
 3 3 3
4 4 4 4

Solution to above problem 

import java.util.Scanner;
class problem7{
public static void main(String args[]){
 int a,b,c;
 Scanner in = new Scanner(System.in);
 a = in.nextInt();
 b = in.nextInt();
 c = in.nextInt();
 int[] array={a,b,c};
    int k;
  for(int x=0; x<3; x++){
  int y = array[x];
  int z= y+1;
   for(int i=1;i<=y;i++){                    
   System.out.println();
   System.out.format("%"+z+"s", ""); 
    
    for(int j=1;j<=i;j++)
    {
    k=i;
    System.out.format("%"+1+"s", ""); 
    System.out.print(k);  
    }
    z--;
   }
  }
   }
}

1 comment:

  1. int spaces = 5;
    int exaat = 1;
    for( int line = 1 ; line <= 5 ; ++line )
    {
    for( int s = 1 ; s < spaces ; ++ s )
    {
    System.out.print(" ");
    }
    for( int m = 1 ; m <= exaat ; ++m )
    {
    System.out.print(line+" ");
    }
    System.out.println();
    spaces = spaces -1;
    exaat = exaat + 1;
    }

    ReplyDelete