Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Printing Heart Pattern in C
In this program we will see how to print heart shaped pattern in C. The heart shape pattern consists of two rounded peaks at the top and an inverted triangle forming the base.
Now if we analyze this pattern, we can find different sections. The base of the heart is an inverted triangle; the upper portion has two different peaks with a gap between them. To make this pattern we have to manage these parts into our code −
Syntax
// Heart pattern logic: // 1. Upper part: Two peaks with gap // 2. Lower part: Inverted triangle
Example
#include <stdio.h>
int main() {
int a, b, line = 12;
// For the upper part of the heart
for (a = line/2; a <= line; a = a+2) {
// Create space before the first peak
for (b = 1; b < line-a; b = b+2)
printf(" ");
// Print the first peak
for (b = 1; b <= a; b++)
printf("*");
// Create space between peaks
for (b = 1; b <= line-a; b++)
printf(" ");
// Print the second peak
for (b = 1; b <= a-1; b++)
printf("*");
printf("<br>");
}
// The base of the heart is inverted triangle
for (a = line; a >= 0; a--) {
// Generate space before triangle
for (b = a; b < line; b++)
printf(" ");
// Print the triangle
for (b = 1; b <= ((a * 2) - 1); b++)
printf("*");
printf("<br>");
}
return 0;
}
Output
*** **
****** *****
******** *******
********** *********
***********************
***********************
*********************
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
How It Works
- Upper Part: Creates two peaks with calculated spacing between them using nested loops.
- Lower Part: Forms an inverted triangle by decreasing the number of stars in each row.
- Spacing: Uses appropriate spaces to center the pattern and create the heart shape.
Conclusion
The heart pattern in C combines two main parts − the upper curved section with two peaks and the lower inverted triangle. Proper spacing and loop control create the distinctive heart shape.
Advertisements
