print the following pattern using Java programming
PYRAMID FORM..
1 121 12321 1234321.
Answers
from this method you can print following pattern
Explanation:
public class Pyramid
{
public static void main(String[] args)
{
int i=0,j=0,n=6,k=0;
for(i=0; i<n; i++)
{
k=1;
for(j=0; j<(n+i); j++)
{
if(j<n-i-1)
System.out.print(" ");
else
{
System.out.print(""+k);
if(j<(n-1))
k++;
else
k--;
}
}
System.out.println(" ");
}
}
}
OUTPUT
1
121
12321
1234321
123454321
12345654321
Program:
import java.util.Scanner;
public class oh { public static void main(String[] args)
{ Scanner scan= new Scanner (System.in);
System.out.print("Enter the highest number: ");
int n=scan.nextInt();
for (int i = 1; i < n+1; i++) {
for (int k=1; k<n+1-i; k++) {System.out.print(" ");}
for (int k=1; k<i+1; k++) {System.out.print(k);}
for (int k=i-1; k>0; k-=1) {System.out.print(k);}
System.out.println();}
} }
Explanation for what I did:
- Took n as input.
- Used a main for loop to control output per line.
- Let 1st nested for loop control spaces.
- Let 2nd nested loop control numbers till highest number per line (1,12,123 and so on).
- Let 3rd nested loop print till 2nd highest number in each line in reverse (1,21,321 etc).
Note: consider the attachment for output and program in IDE.