Construct a paztriangle up to the given N number. If the triangle is not formed then Print remaining elements with X.
N=23
X X
18 20 22
10 12 14 16
0 2 4 6 8
N=18
18
14 16
8 10 12
0 2 4 6
//Java Code
import java.util.Scanner; public class Main { static void triangle(int n){ int total=0;int _x=0;int count=0; for(int i=1;i<n;i++){ total+=i; if((2*total)>n) break; } String []a= new String[total]; if(n%2!=0) n-=1; for(int i=0;i<total;i++){ if(count<=n) { a[i] = count+ ""; count+=2; } else a[i] = "X"; } int right=1; while(total!=0){ _x+=right; count=a.length-_x; for(int i=1;i<=right;i++){ System.out.print(a[count++]+" "); } System.out.println(); total-=right; right++; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); triangle(sc.nextInt()); } }
Comments
Post a Comment