diamond star pattern in cpp
Here is an example of how to create a diamond star pattern using C++:
#include <iostream>
using namespace std;
int main() {
int n, i, j, space = 1;
cout << "Enter number of rows: ";
cin >> n;
space = n - 1;
for (j = 1; j<= n; j++) {
for (i = 1; i<= space; i++) {
cout << " ";
}
space--;
for (i = 1; i <= 2 * j - 1; i++) {
cout << "*";
}
cout << endl;
}
space = 1;
for (j = 1; j<= n - 1; j++) {
for (i = 1; i<= space; i++) {
cout << " ";
}
space++;
for (i = 1; i<= 2 * (n - j) - 1; i++) {
cout << "*";
}
cout << endl;
}
return 0;
}
Explanation:
- First, we include the necessary header file
iostream
to use the input/output stream. - We declare the main function where our program execution begins.
- We declare variables
n
,i
,j
, andspace
.n
represents the number of rows,i
andj
are loop counters, andspace
represents the number of spaces in each row. - We prompt the user to enter the number of rows using the
cout
object and then store the input in the variablen
using thecin
object. - We set the value of
space
ton - 1
to determine the number of spaces in the first row. - We start a loop for the upper half of the diamond pattern, which runs
n
times. In each iteration, we print the required number of spaces using the nestedfor
loop and then decrement the value ofspace
by 1. - Inside the nested loop, we print a space using the
cout
object. - After the nested loop, we start another nested loop to print the asterisks (
) in each row. The number of asterisks is given by the formula
2 j - 1
. - Finally, we print a newline character using
cout << endl;
to move to the next row. - After the upper half is printed, we reset the value of
space
to1
for the lower half of the diamond. - We start another loop for the lower half, which runs
n - 1
times. In each iteration, we print the required number of spaces using the nestedfor
loop and then increment the value ofspace
by 1. - Inside the nested loop, we print a space using the
cout
object. - After the nested loop, we start another nested loop to print the asterisks (
) in each row. The number of asterisks is given by the formula
2 (n - j) - 1
. - Finally, we print a newline character using
cout << endl;
to move to the next row. - We return
0
from themain
function to indicate successful program execution.