Write a program in C to check whether the number is prime or not.

/*Write a program in C to check whether the number is prime or not.*/


/*Note: Prime numbers are those numbers which is divisible by 1 or itself */

/* Solution 1: */

#include<stdio.h>
#include<conio.h>

void main()
 {
   int num,i=2;        /* Variables Declaration of integer type num and i  and             initialize the value of i*/
   clrscr();                        /* Function to clear the console screen */
   printf("Enter a number\n");  /* General message for the user */
   scanf("%d",&num);     /* Input a number by the user/through the keyboard*/
   while(i<num)             /* Starting of while loop */    
    {
      if(num%i==0)        /* Check whether the input number is divisible by i */
       {
         printf("%d is not a prime number",num); /* Print message if num is                     divided  by current value of i */
         break;  /* If the above condition matches, it comes out from the loop */
       }
      i++; /* It increments the value of i by 1 */
    }
   if(i==nun) /* This is the only condition that tells none other values of i                 between 2 and num-1 divides num */
    printf("%d is a prime number",num); /* Output message for prime */
   getch();  /* It stays on the console screen unit it gets a character */
 }

/* Solution 2: By Using For Loop */

#include<stdio.h>
#include<conio.h>

void main()
 {
   int num,i;
   clrscr();
  printf("Enter a number\n"); 
  scanf("%d",&num);
  for(i=2;i<num;i++)
   {
     if(num%i==0)
      {
       printf("%d is not a prime number",num);
       break;
      }
   }
  if(i==num)
   printf("%d is a prime number",num);
  getch();
}

/* Solution 3: */

#include<stdio.h>
#include<conio.h>

void main()
 {
   int num,i,count=0;
   clrscr();
  printf("Enter a number\n"); 
  scanf("%d",&num);
  for(i=1;i<=num;i++)
   {
     if(num%i==0)
      count++;
   }
  if(count==2) /* It checks the factors of the input number is equal to 2 or not */
   printf("%d is a prime number",num);
  else
   printf("%d is not a prime number",num);
  getch();
}



/*Solution 4: By using Do-While Loop */

#include<stdio.h>
#include<conio.h>

void main()
 {
   int num,i=1,count=0;
   clrscr();
  printf("Enter a number\n"); 
  scanf("%d",&num);
   do
   {
     if(num%i==0)
      count++;
   }while(i<=num);
  if(count==2)
   printf("%d is a prime number",num);
  else
   printf("%d is not a prime number",num);
  getch();
}

/*
OUTPUT:
Enter a number
31
31 is a prime number

Enter a number
25
25 is not a prime number
*/

To read about


Popular posts from this blog

IGNOU Solved Assignment 2023-24 | BCS-012 Basic Mathematics BCA(I)012/Assignment/2023-24

MCS-051 : ADVANCED INTERNET TECHNOLOGIES | 1. (a) Write a web application using JSP and JDBC that takes a bank account number as input and displays the account balance.

MCS054 TEE June 2021 Q1(b) | Bisection Method