In this tutorial, you’ll learn how to write a simple C program that prints the first N odd numbers using a for
loop.
This is a perfect beginner-level problem that helps you understand how loops and number sequences work in C.
📌 What Are Odd Numbers?
Odd numbers are numbers that are not evenly divisible by 2 — they leave a remainder of 1. Examples are: 1, 3, 5, 7, 9, 11... and so on. So, when we say "print the first N odd numbers," we just need to display the first N numbers from this sequence.
🧠 How Does the Program Work?
We use a loop that starts from 1 and checks each number one by one. We check if the number is odd using i % 2 != 0
. If it is odd, we print it and increase the count. We stop when we’ve printed N odd numbers.
📝 Program Description
This C program asks the user to enter a number N
and then prints the first N
odd numbers on the screen.
It uses a for
loop to check each number starting from 1 and prints it only if it’s odd.
A separate counter keeps track of how many odd numbers have been printed so far.
The loop continues until exactly N
odd numbers are displayed.
✅ C Program to Print First N Odd Numbers
#include <stdio.h>
int main()
{
int n, i, count = 0;
printf("Enter the value of N: ");
scanf("%d", &n);
printf("First %d Odd Numbers:\n", n);
for(i = 1; count < n; i++)
{
if(i % 2 != 0) // If i is odd
{
printf("%d ", i);
count++;
}
}
return 0;
}
🔍 Sample Output
Enter the value of N: 5
First 5 Odd Numbers:
1 3 5 7 9
💡 Alternate Way Using Formula
You can also generate odd numbers using a direct formula: 2 * i - 1
.
This approach skips the odd/even check and directly gives you odd numbers.
#include <stdio.h>
int main()
{
int n, i;
printf("Enter the value of N: ");
scanf("%d", &n);
printf("First %d Odd Numbers:\n", n);
for(i = 1; i <= n; i++)
{
printf("%d ", 2 * i - 1);
}
return 0;
}
📌 Conclusion
This small program is a great way to practice using for
loops and conditional logic in C.
Understanding how to work with number patterns like odd or even numbers builds a strong foundation for more complex logic ahead.
Try extending this code to print even numbers or calculate the sum of odd numbers!
❓ Frequently Asked Questions
👉 What is the difference between odd and even numbers?
Odd numbers leave a remainder of 1 when divided by 2 (like 1, 3, 5...), while even numbers are divisible by 2 with no remainder (like 2, 4, 6...).
👉 Why use a counter variable in the first program?
Because we don’t know how many numbers we’ll need to check to get exactly N odd numbers. The counter keeps track of how many odd numbers we’ve printed so far.
👉 Which method is better: using modulo or formula?
The formula method 2*i - 1
is faster and simpler when you only need odd numbers. The modulo method is better when you need to perform extra checks or logic inside the loop.
👉 Can this logic be used for even numbers too?
Yes, just modify the condition to check i % 2 == 0
or use the formula 2 * i
to generate even numbers instead.