Introduction
In this lab, we will learn how to write a C++ program to print a diamond pattern using asterisks (*). We will create this program step by step.
In this lab, we will learn how to write a C++ program to print a diamond pattern using asterisks (*). We will create this program step by step.
We will create a new file named main.cpp
in the ~/project
directory using the following command:
touch ~/project/main.cpp
We will take the number of rows as input from the user.
int rows;
cout << "Enter Diamond Star Pattern Row = ";
cin >> rows;
To display the pattern, we will use nested loops. The outer loop will be responsible for the number of rows and the inner loop will print the asterisk symbols and spaces.
cout << "Diamond Star Pattern\n";
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
cout << " ";
}
for (int k = 1; k <= i * 2 - 1; k++) {
cout << "*";
}
cout << "\n";
}
for (int i = rows - 1; i > 0; i--) {
for (int j = 1; j <= rows - i; j++) {
cout << " ";
}
for (int k = 1; k <= i * 2 - 1; k++) {
cout << "*";
}
cout << "\n";
}
We use two loops to draw the diamond. We begin by drawing the top half of the diamond.
The outer loop (the first for
loop) loops through each row of the diamond. We use a nested loop inside the outer loop.
The inner loops (the twofor
loops) print the spaces and asterisks for each row of the diamond.
We then draw the bottom half of the diamond. We begin by using a similar loop as used in the first half of the diamond. The outer loop counts down to zero (in reverse).
To compile and run the code, use the following command in the terminal:
g++ main.cpp -o main && ./main
Here is the full code for the Diamond pattern program.
#include <iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter Diamond Star Pattern Row = ";
cin >> rows;
cout << "Diamond Star Pattern\n";
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
cout << " ";
}
for (int k = 1; k <= i * 2 - 1; k++) {
cout << "*";
}
cout << "\n";
}
for (int i = rows - 1; i > 0; i--) {
for (int j = 1; j <= rows - i; j++) {
cout << " ";
}
for (int k = 1; k <= i * 2 - 1; k++) {
cout << "*";
}
cout << "\n";
}
return 0;
}
In this lab, we learned how to write a C++ program to print a diamond pattern using asterisks (*). We used nested loops to display the pattern. We began with a simple input and step by step created a C++ program that can be used to print a diamond using asterisks.