Introduction
In this lab, we will learn how to use C++ programming language to print a Heart-Shaped Pattern program using stars. We will learn how to use Control statements to make the heart pattern according to user input.
In this lab, we will learn how to use C++ programming language to print a Heart-Shaped Pattern program using stars. We will learn how to use Control statements to make the heart pattern according to user input.
We will create a new file named main.cpp
in the ~/project
directory using the following command:
touch ~/project/main.cpp
In this step, we will include the necessary libraries in our C++ code. Open the main.cpp
file in your text editor and write the following code:
#include<iostream>
using namespace std;
In this step, we will define a variable to take input from the user. We will later use this variable to make the heart pattern. Add the following code after the previous step code:
int main()
{
int n;
// take user input
cout << "Enter Heart Size (4-8): ";
cin >> n;
// check if input is 0
if (n == 0) {
return 0;
}
// check if input is even
if (n % 2 != 0) {
n++;
}
return 0;
}
In this step, we will use Control statements to make the heart pattern according to the user input. Add the following code after the previous step code:
int main()
{
int n;
// take user input
cout << "Enter Heart Size (4-8): ";
cin >> n;
// check if input is 0
if (n == 0) {
return 0;
}
// check if input is odd
if (n % 2 != 0) {
n++;
}
// print heart pattern
for (int row = 0; row < n; row++) {
for (int col = 0; col < n + 1; col++) {
if ((row == 0 && col % 3 != 0) ||
(row == 1 && col % 3 == 0) ||
(row - col == 2) ||
(row + col == n + 3))
{
cout << "*";
}
else {
cout << " ";
}
}
cout << endl;
}
return 0;
}
In this step, we will compile and run the code in the Ubuntu terminal. Save the main.cpp
file and open the terminal. Run the following command:
g++ main.cpp -o main && ./main
Now, enter any number between 4 and 8 in the terminal window to see the heart-shaped pattern made of stars.
In this lab, we learned how to use C++ programming language to print a Heart-Shaped Pattern program using stars. We used Control statements to make the heart pattern according to user input. We created a C++ code file in the ~/project
directory, compiled and executed the code to print a heart-shaped pattern in the Ubuntu terminal.