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
How will you print numbers from 1 to 100 without using loop in C?
You can print numbers from 1 to 100 without using traditional loops by employing alternative control structures like recursive functions and goto statements. These methods achieve the same repetitive behavior through different mechanisms.
Method 1: Using Recursion
Recursion allows a function to call itself repeatedly until a base condition is met. We can use this property to print numbers sequentially without explicit loops −
#include <stdio.h>
void printNumbers(int n) {
if (n > 100)
return;
printf("%d ", n);
printNumbers(n + 1);
}
int main() {
printNumbers(1);
printf("
");
return 0;
}
The output of the above code is −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
Method 2: Using goto Statement
The goto statement provides unconditional jumps to labeled statements, allowing us to create loop-like behavior without actual loop constructs −
#include <stdio.h>
int main() {
int i = 1;
start:
if (i <= 100) {
printf("%d ", i);
i++;
goto start;
}
printf("
");
return 0;
}
The output of the above code is −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
Comparison
| Method | Pros | Cons | Memory Usage |
|---|---|---|---|
| Recursion | Clean, elegant code | Stack overflow risk for large ranges | O(n) stack space |
| goto Statement | No stack overhead | Poor readability, considered bad practice | O(1) space |
Conclusion
Both recursion and goto statements can replace traditional loops for printing sequential numbers. While recursion offers cleaner code, goto statements are more memory-efficient for large ranges.
