ADVERTISEMENT
Check A Number It Is Prime or Not
This code takes an integer input (the number to be checked for primality), counts its factors by iterating through numbers from 1 to that number, and determines whether it’s prime based on the number of factors (2 factors for prime numbers). If the number is not prime, it also provides a list of divisors.
#include<stdio.h>
main()
{
int num,i,count=0;
printf("Enter a number to check whether it is prime or not\n");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
if(num%i==0)
{
count++;
}
}
if(count==2)
{
printf("The given number %d is Prime Number\n",num);
}
else
{
printf("The given number %d is not Prime Number\nbecause The number is divisible by\n",num);
for(i=1;i<=num;i++)
{
if(num%i==0)
{
printf("%d\n",i);
}
}
}
}C Programming ExamplesOUTPUT
Enter a number to check whether it is prime or not
6
The given number 6 is not Prime Number
because The number is divisible by
1
2
3
6C Programming ExamplesExplanation:
This C program checks whether a given number is prime and displays the result. Here’s a step-by-step explanation of the code:
Header File:
- The program includes the standard C library header <stdio.h> for input and output operations.
Main Function:
- The main function is the entry point of the program.
Variable Declaration:
Two variables are declared:
- num (int): It stores the user input, which is the number to be checked for primality.
- i (int): It is used as a loop variable to iterate through numbers from 1 to num.
- count (int): This variable is used to count the factors of the given number.
User Input:
- The program prompts the user to enter a number:
- “Enter a number to check whether it is prime or not” for num.
- The user’s input is read and stored in the variable num using scanf.
Factor Counting Loop:
- A for loop is used with i ranging from 1 to num. This loop iterates through numbers from 1 to the given number to determine if it’s prime.
- Inside the loop, the count variable is initialized to 0 for each number i.
Factor Check:
- For each number i, it is checked if num is divisible by i. If num is evenly divisible by i (i.e., num % i == 0), the count is incremented.
- The count variable keeps track of how many factors (divisors) the given number num has.
Prime Check:
- After the loop completes, the program checks if count is equal to 2. If count is 2, it means that the number only has two factors (1 and itself), making it a prime number.
- If count is 2, the program displays a message stating that the given number is a prime number.
- If count is not equal to 2, the program displays a message stating that the number is not prime and provides a list of divisors of the number, indicating that it’s divisible by more than just 1 and itself.
End of Program:
- The program reaches the end of the main function and terminates.