C Program to Print Odd Numbers from 1 to n
for loop starting from 1 to n incrementing by 2 and print each number with printf, like for(int i=1; i<=n; i+=2) printf("%d\n", i);.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int n; printf("Enter the value of n: "); scanf("%d", &n); for (int i = 1; i <= n; i += 2) { 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 loop variable
i = 1
Check condition
Is i (1) <= n (5)? Yes, continue
Print i
Print 1
Increment i
i = i + 2 = 3
Repeat condition check
Is i (3) <= n (5)? Yes, continue
Print i
Print 3
Increment i
i = i + 2 = 5
Repeat condition check
Is i (5) <= n (5)? Yes, continue
Print i
Print 5
Increment i
i = i + 2 = 7
Repeat condition check
Is i (7) <= n (5)? No, stop loop
| i |
|---|
| 1 |
| 3 |
| 5 |
Why This Works
Step 1: Start from 1
We start the loop at 1 because 1 is the first odd number.
Step 2: Increment by 2
Adding 2 each time ensures we only get odd numbers (1, 3, 5, ...).
Step 3: Stop at n
The loop stops when the number exceeds n, so we print only odd numbers up to n.
Alternative Approaches
#include <stdio.h> int main() { int n; printf("Enter the value of n: "); scanf("%d", &n); for (int i = 1; i <= n; i++) { if (i % 2 != 0) { printf("%d\n", i); } } return 0; }
#include <stdio.h> int main() { int n, i = 1; printf("Enter the value of n: "); scanf("%d", &n); while (i <= n) { printf("%d\n", i); i += 2; } return 0; }
Complexity: O(n/2) time, O(1) space
Time Complexity
The loop runs roughly n/2 times because it increments by 2, so time complexity is O(n/2), which simplifies to O(n).
Space Complexity
The program uses a fixed amount of memory for variables, so space complexity is O(1).
Which Approach is Fastest?
Incrementing by 2 is faster than checking each number with a condition because it skips even numbers entirely.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Increment by 2 | O(n) | O(1) | Efficient and simple for printing odd numbers |
| Check each number | O(n) | O(1) | Simple logic but less efficient |
| While loop increment by 2 | O(n) | O(1) | Alternative loop style, same efficiency |