Ahmad Al Otaibi
Ahmad Al Otaibi

Reputation: 1

How to make a numbers triangle in Java using loops, numbers starting from right

my project to create a triangle in Java with numbers starting from the right

enter image description here


import java.util.Scanner;
public class Pyramid {

   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);

      // loop
      for (int i=1; i <= 6; i++) {
         // space
         for(int j=1; j <= 6-i; j++)
         System.out.print(" ");

         // numbers
         for(int k= 1; k <= i; k++)
         System.out.print(k);

         // new line
         System.out.println();
      }
   }
}

Upvotes: 0

Views: 1260

Answers (4)

rxf113
rxf113

Reputation: 1

import java.util.Scanner;

public class Pyramid {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int lines = scanner.nextInt();
        for (int i = 0; i <= lines; i++) {
            //space
            int spaceNum = lines - I;
            for (int j = 0; j < spaceNum; j++) {
                System.out.print("  ");
            }
            //numbers
            int numbers = lines - spaceNum;
            for (int j = numbers; j > 0; j--) {
                System.out.print(" " + j);
            }
            System.out.println();
        }

    }
}

Upvotes: 0

WJS
WJS

Reputation: 40034

Here is one way. It uses String.repeat() to pad with leading spaces.

  • outer loop controls the rows.
  • Then print the leading spaces
  • inner loop iterates backwards, printing the value and a space
  • then print a newline
int rows = 6;
for (int i = 1; i <= rows; i++) {
    System.out.print("  ".repeat(rows-i));
    for (int k = i; k > 0; k--) {
        System.out.print(k+ " ");
    }
    System.out.println();
}

prints

          1 
        2 1 
      3 2 1 
    4 3 2 1 
  5 4 3 2 1 
6 5 4 3 2 1 

If you don't want to use String.repeat() then use a loop.

Upvotes: 1

Sither Tsering
Sither Tsering

Reputation: 1308

start k=i then decrement it till k>=1.

for(int k= i; k >=1 ; k--)
     System.out.print(k+" ");

output

          1 
        2 1 
      3 2 1 
    4 3 2 1 
  5 4 3 2 1 
6 5 4 3 2 1 

Upvotes: 0

Aarush Kumar
Aarush Kumar

Reputation: 167

Well the only thing you have to do is change order like you are first adding space and then number instead add number and then space. code -

import java.util.Scanner;
public class Pyramid {
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

      // loop
      for (int i=1; i <= 6; i++) {
          // numbers
         for(int k= 1; k <= i; k++)
         System.out.print(k);
         
         // space
         for(int j=1; j <= 6-i; j++)
         System.out.print(" ");
         
         // new line
         System.out.println();

      }
  }
}

Now we get the result -

Pyramid right to left.

Upvotes: 0

Related Questions