Pyramid Star Pattern
Print a centered pyramid of stars with n rows.
Sample input
4
Sample output
*
***
*****
*******
Solution
n = 4
for i in range(1, n + 1):
spaces = " " * (n - i)
stars = "*" * (2 * i - 1)
print(spaces + stars)
const n = 4;
for (let i = 1; i <= n; i++) {
const spaces = " ".repeat(n - i);
const stars = "*".repeat(2 * i - 1);
console.log(spaces + stars);
}
public class Main {
public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
StringBuilder sb = new StringBuilder();
for (int s = 0; s < n - i; s++) sb.append(" ");
for (int j = 0; j < 2 * i - 1; j++) sb.append("*");
System.out.println(sb.toString());
}
}
}
fun main() {
val n = 4
for (i in 1..n) {
val spaces = " ".repeat(n - i)
val stars = "*".repeat(2 * i - 1)
println(spaces + stars)
}
}
let n = 4
for i in 1...n {
let spaces = String(repeating: " ", count: n - i)
let stars = String(repeating: "*", count: 2 * i - 1)
print(spaces + stars)
}
void main() {
int n = 4;
for (int i = 1; i <= n; i++) {
String spaces = ' ' * (n - i);
String stars = '*' * (2 * i - 1);
print(spaces + stars);
}
}
#include <iostream>
using namespace std;
int main() {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int s = 0; s < n - i; s++) cout << " ";
for (int j = 0; j < 2 * i - 1; j++) cout << "*";
cout << endl;
}
return 0;
}
#include <stdio.h>
int main() {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int s = 0; s < n - i; s++) printf(" ");
for (int j = 0; j < 2 * i - 1; j++) printf("*");
printf("\n");
}
return 0;
}