समस्या
फॉर लूप का उपयोग करके केंद्र में नाम के साथ हार्ट आकार का पैटर्न प्रिंट करने के लिए एक प्रोग्राम लिखें।
समाधान
उपयोगकर्ता को वह नाम दर्ज करना होगा जिसे केंद्र में प्रिंट किया जाना चाहिए साथ ही पंक्तियों की संख्या जो स्टार्स को प्रिंट करनी है।
एल्गोरिथम
फॉर लूप का उपयोग करके नाम को हार्ट पैटर्न में प्रिंट करने के लिए नीचे दिया गया एल्गोरिथम देखें।
चरण 1 - वेरिएबल्स डिक्लेयर करें।
चरण 2 - रनटाइम पर वह नाम पढ़ें जिसे केंद्र में प्रिंट किया जाना चाहिए।
चरण 3 - पंक्तियों की संख्या पढ़ें।
चरण 4 - नाम की लंबाई खोजें।
चरण 5 - हार्ट का ऊपरी भाग प्रिंट करें।
चरण 6 - हार्ट का निचला भाग प्रिंट करें।
चरण 7 - नाम को स्क्रीन पर प्रिंट करें।
उदाहरण
निम्नलिखित C प्रोग्राम फॉर लूप का उपयोग करके नाम को हार्ट पैटर्न में प्रिंट करता है:
#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;
}
आउटपुट
Enter your name: Tutorials POint
Enter no of rows: 10
***** *****
******* *******
********* *********
**Tutorials POint*
*****************
***************
*************
***********
*********
*******
*****
***
*