Home > Article > Backend Development > C program to print names in heart-shaped pattern using for loop
Write a program that uses a for loop to print a heart-shaped pattern with a name in the center.
The user must enter the name that should be printed in the center and the number of rows on which the star must be printed.
See the algorithm given below to print names in heart pattern by using for loop.
Step 1 - Declare variables.
Step 2 - At runtime read the name that should be printed in the center.
Step 3 - Read the number of lines.
Step 4 - Calculate the length of the name.
Step 5 - Print the top half of the heart.
Step 6 - Print the lower half
Step 7 - Print the name on the screen.
The following is a C program loop that uses for to print names in a heart shape -
Live demonstration
#include <stdio.h> #include <string.h> int main(){ int i, j, n; char name[50]; int len; printf("Enter your name: "); gets(name); printf("Enter no of rows: "); scanf("%d", &n); len = strlen(name); // Print upper part of the heart shape with stars for(i=n/2; i<=n; i+=2){ for(j=1; j<n-i; j+=2){ printf(" "); } for(j=1; j<=i; j++){ printf("*"); } for(j=1; j<=n-i; j++){ printf(" "); } for(j=1; j<=i; j++){ printf("*"); } printf("</p><p>"); } // Prints lower triangular part with stars for(i=n; i>=1; i--){ for(j=i; j<n; j++){ printf(" "); } // Print the name on screen if(i == n){ for(j=1; j<=(n * 2-len)/2; j++){ printf("*"); } printf("%s", name); for(j=1; j<(n*2-len)/2; j++){ printf("*"); } }else{ for(j=1; j<=(i*2)-1; j++){ printf("*"); } } printf("</p><p>"); } return 0; }
When executing the above program, the following output will be produced-
Enter your name: Tutorials POint Enter no of rows: 10 ***** ***** ******* ******* ********* ********* **Tutorials POint* ***************** *************** ************* *********** ********* ******* ***** *** *
The above is the detailed content of C program to print names in heart-shaped pattern using for loop. For more information, please follow other related articles on the PHP Chinese website!