Prime numbers, those divisible only by 1 and themselves, are fundamental in number theory and have various applications in computer science and cryptography. Writing a C program to print prime numbers within a given range from 1 to ‘n’ involves an efficient approach to identifying and displaying these numbers.
Table of Contents
Understanding Prime Numbers
Prime numbers are integers greater than 1 that have no divisors other than 1 and the number itself. To determine prime numbers within a range, we will create a C program that checks each number between 1 and ‘n’ to identify those numbers that are only divisible by 1 and themselves.
Implementing the C Program to print prime Numbers from 1 to n
Below is a sample C program that prints prime numbers from 1 to a given ‘n’:
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) return 0; // Numbers less than or equal to 1 are not prime
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // Not a prime number
}
}
return 1; // Prime number
}
void printPrimes(int n) {
printf("Prime numbers between 1 and %d are: ", n);
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
printf("%d ", i);
}
}
printf("\n");
}
void main() {
int limit;
printf("Enter the value of n: ");
scanf("%d", &limit);
printPrimes(limit);
}
Output
Explanation of the Above C Program
- The
isPrime()
function checks if a given number ‘num’ is prime by iterating from 2 to the square root of ‘num’. If the number has any divisors other than 1 and itself, it returns 0; otherwise, it returns 1 indicating a prime number. - The
printPrimes()
function takes the user-defined limit ‘n’ as input and displays all prime numbers between 1 and ‘n’. - In the
main()
function, the user inputs the value of ‘n’, and the program calls theprintPrimes()
function to print prime numbers within the specified range.
Implementing a C program to print prime numbers from 1 to ‘n’ is a basic yet crucial exercise in understanding algorithms and logical reasoning in programming. Such programs help reinforce the concept of prime numbers and their identification within a given range, contributing to a foundational understanding of number theory in computer science.
2 thoughts on “C Program to Print Prime Numbers from 1 to n”