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!
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 |
#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:
1 2 3 |
Find the entered number is Prime or not Enter the number: 5 5 is a prime number |
2) Output 2:
1 2 3 |
Find the entered number is Prime or not Enter the number: 6 6 is not a prime number |
Thanks for your time. Enjoy Learning!