Half Square Number Triangle in Java





package demo;
import java.util.Scanner;
public class NumberTriangle
{
 public static void main(String[] args) 
 {
  int num;
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any number : ");
  num = sc.nextInt();
  for (int r = 1, n = num; r <= num; r++, n--) 
  {
   for (int sp = r; sp > 1; sp--) {
    System.out.print(" ");
   }
   for (int c = r, p = n; c <= num; c++, p--) 
   {
    System.out.print(p);
   }
   for (int c = num - r, p = 2; c >= 1; c--, p++) 
   {
    System.out.print(p);
   }
   System.out.println();
  }
 }
}

Output:

Enter any number : 5

543212345
 4321234
  32123
   212
    1


BUILD SUCCESSFUL (total time: 7 seconds)


No comments:

Post a Comment