Hey there!
Welcome to ClearUrDoubt.com.
I would recommend you to go through the below post before you continue with this.
C Program to find whether a number is a prime number or not.
In this post, we will look at a C program to print the prime numbers up to a given number.
This can be achieved using any of the below iterative statements in C.
do-while loop
while loop
for loop
We will use the for loop and print the prime numbers:
Here is the C program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
/* C program to print prime numbers to up to a given number */ #include<stdio.h> int main() { int initial_number, num, final_number, isPrime, i; initial_number = 1; printf("Enter a number up to which the primes to be printed: "); scanf("%d", &num); printf("\nPrime numbers: "); for(initial_number = 1; initial_number <= num; initial_number++) { isPrime = 1; for(i = 2; i <= initial_number/2; i++) { if(initial_number % i == 0) { isPrime = 0; break; } } if(isPrime == 1) { printf("%d ", initial_number); } } return 0; } |
Output:
Happy Learning! 🙂
Please leave a reply in case of any queries.