Prime numbers are fundamental in computer science, mathematics, and cryptography. If you’re learning C programming, understanding how to work with prime numbers is a must. In this blog, we’ll walk through a simple yet efficient C program to print all prime numbers from 1 to a user-specified number n
.
Whether you’re a student or preparing for coding interviews, this practical guide will help you grasp the concept of prime number logic and enhance your C programming skills.
β What is a Prime Number?
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples include 2, 3, 5, 7, 11, etc.
Note: 1 is not a prime number, and 2 is the smallest (and only even) prime number.
π§ Logic to Find Prime Numbers
To determine if a number is prime:
- Skip numbers less than or equal to 1.
- For numbers greater than 2, check if they are divisible by any number from 2 to βn.
- If divisible, it’s not a prime number.
- If not divisible by any, it’s a prime number.
π» C Program to Print Prime Numbers from 1 to n
cCopyEdit#include <stdio.h>
#include <math.h>
int isPrime(int num) {
if (num <= 1) return 0;
if (num == 2) return 1;
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) return 0;
}
return 1;
}
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Prime numbers from 1 to %d are:\n", n);
for (int i = 1; i <= n; i++) {
if (isPrime(i)) {
printf("%d ", i);
}
}
return 0;
}
π Sample Output
sqlCopyEditEnter the value of n: 20
Prime numbers from 1 to 20 are:
2 3 5 7 11 13 17 19
π Key Takeaways
- Prime number checking is a classic C programming problem.
- Always optimize using
sqrt(n)
for better performance. - Wrap logic in a reusable function for cleaner code.
π Apply now and take your first step towards a successful career in tech!
Explore our placement guarantee programs