A Learning Platform

SUCCESS

Success = Discipline + Consistency + Sacrifice.
Discipline - in what you do.
Consistency - in what you do.
Sacrifice - for what you do.

                   -- Manjunatha C. P. --

C Program: To check whether a number is prime or not

 To check whether given number is Prime Number or Not – C program

Prime number is a number that is divided by 1 and itself. Prime numbers are greater than 1.

Examples: 2, 3, 5, 7, 11, 13, 17 ….

Now let us write a C program to find whether a given number is prime or not. In this program we are using the concepts of loop and if statement.

We can use any loop to write the program, here we are using for loop. for loop is the easiest among all other loops and it is widely used loop.

Description:

n – input number.
i – loop variable.
flag – indicator : its value changes when number is divided by 2.
flag = 0 (initial value)– number is prime.
flag = 1 – number is not a prime.

Algorithm to find the number is prime or non prime:

STEP 1: START
STEP 2: SET the initial value of flag
              flag = 0
STEP 3: READ a number greater than 1
              READ n
STEP 4: LOOP from i=2 to ( n/2 )
              if (n mod i) IS EQUAL TO zero
                             CHANGE the value of flag to 1
                             SET flag = 1
                             EXIT loop
STEP 5: CHECK the value of flag
              If flag = 0
                             PRINT “It is a prime number”
              Otherwise
                             PRINT “It is not a prime number”
 STEP 7: END

C Program: To find whether given number is prime or not.

#include<stdio.h>  
#include<conio.h>
int main(){    
    int n,i,flag=0;    
    printf("Enter a number greater than 1: ");    
    scanf("%d",&n);    
    for(i=2;i<=n/2;i++)    
    {    
        if(n%i==0)    
        {    
            flag=1;    
            break;    
        }    
    }    
    if(flag==0)    
        printf("It is a prime number");     
    else
        printf("It is not a prime number"); 
    getch();  
    return 0;  
 }   

Output 1:

Enter a number greater than 1: 2
It is a prime number

Output 2:

Enter a number greater than 1: 18
It is not a prime number

Additional information:

Remember Zero (0) and 1 are not considered as prime numbers.
Two (2) is the only even prime number because all the even numbers are divided by 2.