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

Time:01-09

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();
      }
   }
}

CodePudding user response:

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.

CodePudding user response:

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 

CodePudding user response:

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();
    }

}

}

CodePudding user response:

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.

  •  Tags:  
  • Related