Tuesday, February 10, 2015

C program to check a number whether it is prime or not

The c program given below is able to check a number whether it is prime or not. After running the program, first of all you will be asked to provide a number. After providing the number, a for-loop will run to check the number if it is divisible by 2 or any other number.

The if-statement lying inside the for-loop will check if the number is divisible by another number except 1 and the provided number. If the if-statement found that the provided number is divisible by another number except 1 and the same number then a zero will be stored into the variable signal. In the next step the for-loop will be stopped using the statement break;

Finally the result will be displayed using if-else condition.
//c program to check a number whether it is prime or not
#include<stdio.h>
void main(){
    //declaring integer type data
    int number, i, signal=1;

    //displaying message to input a data
    printf("Enter a number: ");

    //getting input into the variable number
    scanf("%d",&number);

    //for-loop to check whether the number is divisible
    for(i=2; i<=number/2; i++){
        if(number%i==0){
            signal = 0;
            break;
        }
    }

    //displaying the result using if-else condition
    if(signal==1){
        printf("\n%d is a prime number\n",number);
    } else {
        printf("\n%d is not a prime number\n",number);
    }
}



1 comment:

  1. Thanks for sharing this c program, I was finding it for the last few days.

    ReplyDelete