Prime numbers are those numbers greater than 1 that are only divisible by 1 and themselves. For example, 2, 3, 5, 7, and 11 are prime numbers. Now, let’s write a C program to print all the prime numbers from 1 to a given number n.
The Code
#include <stdio.h>
// Function to check if a number is prime
int isPrime(int num) {
if (num <= 1) {
return 0; // 0 and 1 are not prime numbers
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // If divisible, it's not prime
}
}
return 1; // If not divisible, it is prime
}
int main() {
int n;
// Ask the user for input
printf("Enter a number: ");
scanf("%d", &n);
printf("Prime numbers from 1 to %d are:\n", n);
// Loop to check each number from 1 to n
for (int i = 1; i <= n; i++) {
if (isPrime(i)) {
printf("%d ", i); // Print prime number
}
}
return 0;
}
How It Works
- isPrime function: This function checks if a number is prime. It returns
0if the number is not prime and1if it is prime.- The function works by trying to divide the number by all integers from 2 up to the square root of the number. If it finds any divisor, it returns
0(not prime). Otherwise, it returns1(prime).
- The function works by trying to divide the number by all integers from 2 up to the square root of the number. If it finds any divisor, it returns
- Main Function:
- We ask the user to input a number
n, which defines the range from 1 tonfor which we want to print prime numbers. - Then, the program loops through all numbers from 1 to
n, checks if each number is prime using theisPrimefunction, and prints it if it is prime.
- We ask the user to input a number
Example Output
Enter a number: 30
Prime numbers from 1 to 30 are:
2 3 5 7 11 13 17 19 23 29
How to Improve
You can improve this program by:
- Optimizing the prime check further, maybe by skipping even numbers after checking for 2.
- Printing prime numbers in a more user-friendly format (e.g., in rows or columns).
Conclusion
That’s all! Now you can use this program to print prime numbers for any given value of n. It’s a simple approach, but perfect to help you understand how prime numbers work and how to check them in a loop.







