C - Prime Number or not
Problem Statement
Brief Description
According to the problem statement we have to write a program in C that will take an integer value as input from the user through the keyboard and will check whether it is a prime number or not.
A positive number is prime if it is greater than 1 and if it has exactly two factors i.e. 1 and the number itself.Â
For example, if the user enters 7 as input, the program will generate an output indicating that 7 is a prime number since the number 7 is greater than 1 and it has only two factors i.e. 1 and 7. But if the user enters 8 as input, the program will generate an output indicating that 8 is not a prime number since the number 8 is divisible by 1, 2, 4 and 8.
Program
#include
void main()
{
int num,i,count=0;
printf("Enter a number: ");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
if(num%i==0)
count=count+1; //OR count+=1;
}
if(count==2)
printf("%d is a prime number",num);
else
printf("%d is not a prime number",num);
}
Output
Output 1
Output 2
Explanation
- 3 integer variable namely num, i and count are declared.
- Initially 0 is stored in count.
- The integer value entered by the user is stored in num.
num | i<=num | num%i==0 | count=count+1; | count | i++ OR i=i+1 | i | Comment |
---|---|---|---|---|---|---|---|
3 | ----- | ----- | ----- | 0 | ----- | 1 | Initial Values |
3 | 1<=3 ↓ 1(True) | 3%1==0 ↓ 0==0 ↓ 1(True) | count=0+1; | 1 | i=1+1 | 2 | Iteration 1 |
3 | 2<=3 ↓ 1(True) | 3%2==0 ↓ 1==0 ↓ 0(False) | ----- | 1 | i=2+1 | 3 | Iteration 2 |
3 | 3<=3 ↓ 1(True) | 3%3==0 ↓ 0==0 ↓ 1(True) | count=1+1; | 2 | i=3+1 | 4 | Iteration 3 |
3 | 4<=3 ↓ 0(False) | ----- | ----- | ----- | ----- | ----- | For loop stops working as condition is evaluated to 0(False) |
- At first 1 is stored in i.
- The condition i<=num is evaluated.
- The condition i<=num will produce either 1(True) or 0(False) after evaluation.
- If it is 1(True), the statement written within for loop is executed and the loop continues to iterate till the condition is 1(True).
- If it is 0(False) then the loop stops working and the control goes to the statement written immediately after the loop.
- At the end of each iteration the value of i is incremented by 1 by executing the statement i++.
- Within for loop it is checked to see whether the value stored in i is a proper positive divisor of the value stored in num or not.
- If it is then the value stored in count is incremented by 1.
- If it is not then the statement written within if statement is not executed.
Thus the above process is repeated to count the number of proper positive divisors of the value stored in num.
The final result is stored in count.
Finally it is checked to see whether the value stored in count is equal to 2 or not. If it is then we can conclude that the value stored in num is a prime number otherwise not and an appropriate message is displayed on the output screen.