In this article, you’ll learn how to check a given number is prime or not in C language without giving input from the keyboard or giving input from the keyboard.
Q: what is a prime number
Ans: A natural number which only divided by itself and 1 is called a prime number and you also say that a prime number is a natural number which is greater than 1 and cannot be formed by multiplying two natural number.
- 1 is not a prime number.
- 2 is the smallest prime number and only even prime number.
- Example of prime number 2,3,5,7,11,13 etc.
To check a given number is prime or not we generally use the following steps:
- Let the given number be x.
- Then we create a loop for checking the given number is prime or not.
- Loop i=2 to x-1, we start the loop at 2 and check up to the given number – 1. Here i is a variable and its initial value is 2, check up to i=x-1.
- If (x % i==0) is false then the given number is prime otherwise it is not prime.
Loop is terminated two times:
- First time, when the condition is true, terminated from the loop and with the help break keyword print on the screen number is not prime.
- Second time, when the condition is false ( it means when the loop is fully executed) and print on the screen number is prime
- If (i==x) is true then the number is prime
- Else
- The number is not prime.
Example 1: write a program in C language to check whether a number is prime or not, without input from keyboard
#include <stdio.h>
#include <conio.h> int main() { int x=17,i; for(i=2;i<=x;i++) if(x%i==0) break; if (i==x) printf(“%d is a prime number”,x); else printf(“%d is not a prime number”,x); getch(); } |
The Output of this program:
17 is a prime number |
Calculate H.C.F of two number in C++ language
Calculate L.C.M of two number in C language
Calculate H.C.F of two number in C language
Check odd-even number in C language