Bitcoin

Bitcoin
Bitcoin

Java Code for Pyramid of Numbers and Reverse

Here Is Your Pyramid
                  9
                8 9 8
              7 8 9 8 7
            6 7 8 9 8 7 6
          5 6 7 8 9 8 7 6 5
        4 5 6 7 8 9 8 7 6 5 4
      3 4 5 6 7 8 9 8 7 6 5 4 3
    2 3 4 5 6 7 8 9 8 7 6 5 4 3 2
  1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
In this problem, at the end of each row we print ‘j’ where ‘j’ value will be from i to noOfRows and from noOfRows-1 to i.
  1. import java.util.Scanner;
  2. public class MainClass {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. //Taking noOfRows value from the user
  6. System.out.println("How Many Rows You Want In Your Pyramid?");
  7. int noOfRows = sc.nextInt();
  8. //Initializing rowCount with 1
  9. int rowCount = 1;
  10. System.out.println("Here Is Your Pyramid");
  11. //Implementing the logic
  12. for (int i = noOfRows; i >= 1; i--) {
  13. //Printing i*2 spaces at the beginning of each row
  14. for (int j = 1; j <= i*2; j++) {
  15. System.out.print(" ");
  16. }
  17. //Printing j where j value will be from i to noOfRows
  18. for (int j = i; j <= noOfRows; j++) {
  19. System.out.print(j+" ");
  20. }
  21. //Printing j where j value will be from noOfRows-1 to i
  22. for (int j = noOfRows-1; j >= i; j--) {
  23. System.out.print(j+" ");
  24. }
  25. System.out.println();
  26. //Incrementing the rowCount
  27. rowCount++;
  28. }
  29. }
  30. }
Java program to print reverse pyramid of numbers
Here Is Your Pyramid
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
  1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
    1 2 3 4 5 6 7 6 5 4 3 2 1
      1 2 3 4 5 6 5 4 3 2 1
        1 2 3 4 5 4 3 2 1
          1 2 3 4 3 2 1
            1 2 3 2 1
              1 2 1
                1
In this problem, we iterate outer loop in the reverse order i.e from 1 to noOfRows and initialize the rowCount to noOfRows.
  1. import java.util.Scanner;
  2. public class MainClass {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. //Taking noOfRows value from the user
  6. System.out.println("How Many Rows You Want In Your Pyramid?");
  7. int noOfRows = sc.nextInt();
  8. //Initializing rowCount with noOfRows
  9. int rowCount = noOfRows;
  10. System.out.println("Here Is Your Pyramid");
  11. //Implementing the logic
  12. for (int i = 0; i < noOfRows; i++) {
  13. //Printing i*2 spaces at the beginning of each row
  14. for (int j = 1; j <= i*2; j++) {
  15. System.out.print(" ");
  16. }
  17. //Printing j where j value will be from 1 to rowCount
  18. for (int j = 1; j <= rowCount; j++) {
  19. System.out.print(j+" ");
  20. }
  21. //Printing j where j value will be from rowCount-1 to 1
  22. for (int j = rowCount-1; j >= 1; j--) {
  23. System.out.print(j+" ");
  24. }
  25. System.out.println();
  26. //Decrementing the rowCount
  27. rowCount--;
  28. }
  29. }
  30. }

No comments:

Post a Comment

Facebook