Hello C language lovers, school/college students here is another interesting program that will help you to understand the basic concepts of C language such as how to get a value from the user, How to print a value etc.,
In this post, we are going to write a simple C program to find the entered number is a Prime number or not!
#include <stdio.h>
int main()
{
int num, i, j, c=0;
//print a string about the program
printf("Find the entered number is Prime or not \n");
printf("Enter the number: ");
//get the limit
scanf("%d", &num);
//loop till i equals to limit
for (i = 1; i <= num; i++) {
//check if the num is divisible by itself and 1
// % modules will give the reminder value, so if the reminder is 0 then it is divisible
if (num % i == 0) {
//increment the value of c
c++;
}
}
//if the value of c is 2 then it is a prime number
//because a prime number should be exactly divisible by 2 times only (itself and 1)
if (c == 2) {
printf("%d is a prime number \n", num);
}else{
printf("%d is not a prime number \n", num);
}
return 0;
}Read the comments in the above C program to understand it.
Example Outputs of the program:
1) Output 1:
Find the entered number is Prime or not Enter the number: 5 5 is a prime number
2) Output 2:
Find the entered number is Prime or not Enter the number: 6 6 is not a prime number
Thanks for your time. Enjoy Learning!