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
How to print a name multiple times without loop statement using C language?
In C programming, printing a name multiple times typically requires loops. However, we can achieve this without using any loop or goto statement by implementing recursive functions or using multiple printf statements.
Syntax
void recursiveFunction(parameters) {
// Base case
if (condition)
return;
// Process
printf("text");
// Recursive call
recursiveFunction(modified_parameters);
}
Method 1: Using Recursion
This approach uses a recursive function that calls itself until a base condition is met −
#include <stdio.h>
void printname(char* name, int count) {
printf("%03d : %s<br>", count + 1, name);
count += 1;
if (count < 10)
printname(name, count);
}
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printname(name, 0);
return 0;
}
Enter your name: TutorialsPoint 001 : TutorialsPoint 002 : TutorialsPoint 003 : TutorialsPoint 004 : TutorialsPoint 005 : TutorialsPoint 006 : TutorialsPoint 007 : TutorialsPoint 008 : TutorialsPoint 009 : TutorialsPoint 010 : TutorialsPoint
Method 2: Using Multiple Print Statements
This approach manually writes multiple printf statements without any loop −
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("1. %s<br>", name);
printf("2. %s<br>", name);
printf("3. %s<br>", name);
printf("4. %s<br>", name);
printf("5. %s<br>", name);
printf("6. %s<br>", name);
printf("7. %s<br>", name);
printf("8. %s<br>", name);
printf("9. %s<br>", name);
printf("10. %s<br>", name);
return 0;
}
Enter your name: John 1. John 2. John 3. John 4. John 5. John 6. John 7. John 8. John 9. John 10. John
Comparison
| Method | Pros | Cons | Best For |
|---|---|---|---|
| Recursion | Flexible count, elegant solution | Uses stack memory, risk of overflow | Variable repetitions |
| Multiple Statements | Simple, no function calls | Fixed count, code repetition | Fixed small repetitions |
Key Points
- Recursion replaces loops by calling the same function repeatedly with modified parameters.
- The base case in recursion prevents infinite calls (like loop termination condition).
- Multiple printf statements work for small, fixed repetitions but are impractical for large counts.
Conclusion
Recursion is the most practical method to print names multiple times without loops. It provides flexibility while maintaining clean, readable code compared to multiple print statements.
Advertisements
