How to make a program in java to get a pyramid star?
*
* *
* * *
* * * *
* * * * *
The Program -
Got it?
*
* *
* * *
* * * *
* * * * *
The Program -
class PrintPyramidStar
public static void main(String args[]) {
int c = 1;
for (int i = 1; i <= 5; i++) {
for (int j = i; j < 5; j++) {
System.out.print(" ");
}
for (int k = 1; k <= c; k++) {
if (k % 2 == 0)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
c += 2;
}
}
}
public static void main(String args[]) {
int c = 1;
for (int i = 1; i <= 5; i++) {
for (int j = i; j < 5; j++) {
System.out.print(" ");
}
for (int k = 1; k <= c; k++) {
if (k % 2 == 0)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
c += 2;
}
}
}
Now the best way to know how it works is by making some changes in the code. Lets do that.
I will mark the changes I have made in the above program with red.
CASE 1 -
class PrintPyramidStar
public static void main(String args[]) {
int c = 1;
for (int i = 1; i <= 5; i++) {
for (int j = i; j < 5; j++) {
System.out.print(" ");
}
for (int k = 1; k <= c; k++) {
if (k % 2 == 0)
System.out.print("1");
else
System.out.print("*");
}
System.out.println();
c += 2;
}
}
}
public static void main(String args[]) {
int c = 1;
for (int i = 1; i <= 5; i++) {
for (int j = i; j < 5; j++) {
System.out.print(" ");
}
for (int k = 1; k <= c; k++) {
if (k % 2 == 0)
System.out.print("1");
else
System.out.print("*");
}
System.out.println();
c += 2;
}
}
}
That resulted in this
*
*1*
*1*1*
*1*1*1*
*1*1*1*1*
*1*
*1*1*
*1*1*1*
*1*1*1*1*
Ah! So I guess it was for the free spacing between the stars/asterik marks.
Now What if we tweak the numbers.
Case 2
Assigning c =10;
class PrintPyramidStar {
public static void main(String args[]) {
int c = 10;
for (int i = 1; i <= 5; i++) {
for (int j = i; j < 5; j++) {
System.out.print(" ");
}
for (int k = 1; k <= c; k++) {
if (k % 2 == 0)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
c += 2;
}
}
}
public static void main(String args[]) {
int c = 10;
for (int i = 1; i <= 5; i++) {
for (int j = i; j < 5; j++) {
System.out.print(" ");
}
for (int k = 1; k <= c; k++) {
if (k % 2 == 0)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
c += 2;
}
}
}
Output -
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
Got it?
Can you print this?
* *** ***** ******* ********* *
Leave it in the comments.