PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Program Based on Loops

Program to check whether a number is prime or not

Input - Output

Input
Enter the number : 19

Output
19 is a prime number

Input
Enter the number : 16

Output
16 is not a prime number

Algorithm

Step 1: START

Step 2: Enter a number 'num' as input,count = 0.

Step 3: Start a loop for(int i=2;i<=num/2;i++){
      if( num % i == 0){
           count=1
            break;
            } }

Step 4: if count == 0 && num != 1
        print prime number
else
        print not a prime number

Step 5: END

CODE


/* Check whether a number is prime or not */

#include<stdio.h>
int main()
{
      int num,count=0;
      printf(" Enter the number : ");
      scanf("%d",&num);
      for(int i=2;i<=num/2;i++)
   {
       if(num % i == 0)
     {
        count=1;
        break;
     }
   }
      if(count == 0 && num != 1)
        printf(" %d is a prime number",num);
      else
        printf(" %d is not a prime number",num);
    return 0;
}


/* Check whether a number is prime or not */

#include<iostream>
using namespace std;
int main()
{
      int num,count=0;
      cout<<" Enter the number : ";
      cin>>num;
      for(int i=2;i<=num/2;i++)
   {
       if(num % i == 0)
     {
        count=1;
        break;
     }
   }
      if(count == 0 && num != 1)
        cout<<" "<<num<<" is a prime number";
      else
        cout<<" "<<num<<" is not a prime number";
    return 0;
}

OutPut

Enter the number : 19

19 is a prime number