Java program to print alternative number-star pyramid.





package demo;
import java.util.Scanner;
public class NumberWithStar
{
 public static void main(String[] args) 
 {
  int num, z = 1, p, n;
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter maximum number : ");
  //Input 5 for desire output
  num = sc.nextInt();
  for (int r = 1; r <= num; r++, z = z + 2) 
  {
   for (int c = 1; c <= z; c++) 
   {
    if (c % 2 == 0) {
     System.out.print("*");
    } else {
     System.out.print(r);
    }
   }
   System.out.println();
  }
  n = num + 3;
  p = num - 1;
  for (int r = num; r >= 1; r--, n = n - 2, p--) 
  {
   for (int c = 1; c <= n; c++) 
   {
    if (c % 2 == 0) {
     System.out.print("*");
    } else {
     System.out.print(p);
    }
   }
   System.out.println();
  }
 }
}

Output:

Enter maximum number : 5

1
2*2
3*3*3
4*4*4*4
5*5*5*5*5
4*4*4*4*
3*3*3*
2*2*
1*


BUILD SUCCESSFUL (total time: 5 seconds)



No comments:

Post a Comment