C program to print name inside heart pattern using for loop.

CServer Side ProgrammingProgramming

Problem

Write a program to print heart shaped pattern with the name in centre using for loop.

Solution

The user has to enter the name that should be printed in centre along with the number of rows the stars has to be print.

Algorithm

Refer an algorithm given below to print the name in heart pattern by using for loop.

Step 1 − Declare variables.

Step 2 − Read a name at runtime that should be printed on centre.

Step 3 − Read number of rows.

Step 4 − Find the length of name.

Step 5 − Print upper part of the heart.

Step 6 − Print lower part of the heart.

Step 7 − Print the name on screen.

Example

Following is the C program to print the name in heart pattern by using for loop −

 Live Demo

#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("\n");
   }
   // 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("\n");
   }
   return 0;
}

Output

When the above program is executed, it produces the following output −

Enter your name: Tutorials POint
Enter no of rows: 10
      ***** *****
    ******* *******
  ********* *********
   **Tutorials POint*
   *****************
    ***************
     *************
      ***********
       *********
        *******
         *****
          ***
           *
raja
Published on 26-Mar-2021 08:01:52
Advertisements