C program to print a name multiple times without using loop or function:
In this post, we will learn how to print a name or a string multiple times without using any loop or function. We can easily do it by using a loop that will run for n times and print the name for n times. Similarly, we can also write one recursive function to print the name n times. But, it is tricky to do that without using a loop or function.
goto:
We can solve it by using goto. goto can be used to move the current control to a specific line. So, we will use one counter variable that will count the number of times the name is printed and by using goto, the program will run in a loop.
Below is the complete program:
C program:
Below is the complete C program:
#include <stdio.h>
int main()
{
int count = 1;
char nameStr[20];
printf("Enter your name: ");
fgets(nameStr, 20, stdin);
start_printing:
count++;
printf("%s", nameStr);
if (count <= 5)
goto start_printing;
}
Here,
- count is a variable initialized as 1. We will print one string until it becomes 5.
- nameStr is used to hold the user input name.
- It reads the name using fgets and stores that value in nameStr.
- start_printing is the initial point where the loop starts. It increments the value of count by 1, prints the nameStr and checks if count is less than and equal to 5 or not. If yes, it uses goto to repeat these steps.
It will run until the value of count is equal to 5. Then it quits.
Output:
If you run this program, it will print output as like below:
Enter your name: Mike
Mike
Mike
Mike
Mike
Mike
You can change 5 to any other value to change the total lines to print.