Problem: Write a program in C to print all prime numbers till the given number n.
A Prime number is a number that is only divisible by itself and 1. For example 5.
To print all prime numbers up to n, we have to check each number individually whether it is Prime or not. To do this, we:
- Loop from 1 to N (
i
).- Nest another loop from 2 to less than
i
(j
).- Inside the nested loop, we check
if(i%j == 0)
.- If
true
theni
is not a prime number. - Therefore,
break
out of the nested loop.
- If
- Inside the nested loop, we check
- Otherwise, if the iteration loops till the end, then
i
is a prime number.- Print
i
.
- Print
- Nest another loop from 2 to less than
Note: The value of n should be entered by the user and should be positive.
Here is the implementation of the steps in C:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int n;
printf("Enter value of n \n");
scanf("%d",&n);
printf("Prime Number between 1 to %d are: \n",n);
//Iterate through all numbers till n
for(int i=1; i<=n; i++){
//boolean variable to mark whether i is prime or not
bool isPrime = true;
for(int j=2; j<i; j++){
/*
*If i is divisble by j then,
*it means i is not prime
*/
if(i%j == 0){
//mark as not prime
isPrime = false;
break;
}
}
//If isPrime remains true, then output i because its a prime number
if(isPrime)
printf("%d, ",i);
}
return 0;
}
Output for All Prime Numbers from 1 to 100:
In this programming example, we learned to write a program in C to print all prime number till the given number ‘n’. If you have any doubt then do comment below.