Question1:
Create Pyramid of "*"
package abc;
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter the number: ");
int x = scanner.nextInt();
if(x%2==0) {
x=x-1; //if 10 is entered, take 9 only,
because the number of x in each row is odd number only.
System.out.println("Value of x is changed to nearest odd number = "+x);
}
else {
System.out.println("There is no change in x value = "+x);
}
int numberOfRow = x/2+1;
int numberofSpacesOnFirstRow=x/2;
System.out.println("number of rows = "+numberOfRow);
System.out.println("numberofSpacesOnFirstRow = "+numberofSpacesOnFirstRow);
// row
1, 1*, 4 space, row 2, 3*, 3 space, Row 3 5* 2 space , Row 4 7* 1 space
// space
decreases by 1 in each row, star increates by 2 in each row
int counter =0;
for(int star=1;star<=x;star=star+2) {
for(int spaces=numberofSpacesOnFirstRow-counter;spaces>0;spaces--) {
System.out.print(" ");
}
for(int row=1; row<=star;row++) {
System.out.print("*");
}
System.out.println("\n");
counter++;
}
}
}
Enter the number 12
Value of x is changed to nearest odd number = 11
number of rows = 6
numberofSpacesOnFirstRow = 5
*
***
*****
*******
*********
***********
No comments:
Post a Comment