C Program to Print Numbers 1 to n
for loop like this: for(int i = 1; i <= n; i++) printf("%d\n", i); inside your main function.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int n, i; scanf("%d", &n); for(i = 1; i <= n; i++) { printf("%d\n", i); } return 0; }
Dry Run
Let's trace the program with input n = 5 through the code
Input
User enters n = 5
Initialize counter
Set i = 1
Check condition
Is i (1) <= n (5)? Yes, continue
Print number
Print 1
Increment counter
i becomes 2
Repeat loop
Check if i (2) <= 5, print 2, increment i to 3, and so on until i = 6
End loop
When i = 6, condition i <= 5 is false, stop loop
| i | Condition i <= n | Action |
|---|---|---|
| 1 | true | Print 1, i++ to 2 |
| 2 | true | Print 2, i++ to 3 |
| 3 | true | Print 3, i++ to 4 |
| 4 | true | Print 4, i++ to 5 |
| 5 | true | Print 5, i++ to 6 |
| 6 | false | Exit loop |
Why This Works
Step 1: Reading input
The program reads the number n from the user using scanf to know how many numbers to print.
Step 2: Looping from 1 to n
The for loop starts at 1 and runs until it reaches n, printing each number in order.
Step 3: Printing numbers
Inside the loop, printf outputs the current number followed by a new line, so each number appears on its own line.
Alternative Approaches
#include <stdio.h> int main() { int n, i = 1; scanf("%d", &n); while(i <= n) { printf("%d\n", i); i++; } return 0; }
#include <stdio.h> int main() { int n, i = 1; scanf("%d", &n); if(n > 0) { do { printf("%d\n", i); i++; } while(i <= n); } return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so it executes n times, making the time complexity O(n).
Space Complexity
The program uses a fixed number of variables and prints output directly, so space complexity is O(1).
Which Approach is Fastest?
All loop methods (for, while, do-while) have the same time and space complexity; choice depends on readability and style.
| Approach | Time | Space | Best For |
|---|---|---|---|
| for loop | O(n) | O(1) | Simple counting with known range |
| while loop | O(n) | O(1) | When condition checked before each iteration |
| do-while loop | O(n) | O(1) | When at least one iteration is needed |