Generate Pyramid For a Given Number

  1. /*

  2. Generate Pyramid For a Given Number Example

  3. This Java example shows how to generate a pyramid of numbers for given

  4. number using for loop example.

  5. */

  6.  

  7. import java.io.BufferedReader;

  8. import java.io.InputStreamReader;

  9.  

  10. public class GeneratePyramidExample {

  11.  

  12. public static void main (String[] args) throws Exception{

  13.  

  14. BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in));

  15.  

  16. System.out.println("Enter Number:");

  17. int as= Integer.parseInt (keyboard.readLine());

  18. System.out.println("Enter X:");

  19. int x= Integer.parseInt (keyboard.readLine());

  20.  

  21. int y = 0;

  22.  

  23. for(int i=0; i<= as ;i++){

  24.  

  25. for(int j=1; j <= i ; j++){

  26. System.out.print(y + "\t");

  27. y = y + x;

  28. }

  29.  

  30. System.out.println("");

  31. }

  32. }

  33. }

  34.  

  35. /*

  36. Output of this example would be

  37.  

  38. Enter Number:

  39. 5

  40. Enter X:

  41. 1

  42.  

  43. 0

  44. 1 2

  45. 3 4 5

  46. 6 7 8 9

  47. 10 11 12 13 14

  48.  

  49. ----------------------------------------------

  50.  

  51. Enter Number:

  52. 5

  53. Enter X:

  54. 2

  55.  

  56. 0

  57. 2 4

  58. 6 8 10

  59. 12 14 16 18

  60. 20 22 24 26 28

  61.  

  62. ----------------------------------------------

  63.  

  64. Enter Number:

  65. 5

  66. Enter X:

  67. 3

  68.  

  69. 0

  70. 3 6

  71. 9 12 15

  72. 18 21 24 27

  73. 30 33 36 39 42

  74. */

0 comments: