Prime number Program:

A prime number is a number that is divisible only by itself and by 1. To check if the number that the user has entered we need to check if it is divisible by any number other than 1 and itself.

The code for checking whether a number is prime or not is:

 
#include<stdio.h>

int  main()
    
    {
    
       int  num;
    
       int  c = 2;
    
       printf("Enter a number:");
    
       scanf("%d", & amp; num);
    
       for  (c = 2 ; c & lt; = num - 1 ; c++)
    
       {
    
          if  (num % c == 0 ) // we are checking if num is divisible by any number other than 1 and itself
    
          {
    
             printf("%d isn't prime.\n", num);
    
             break;
    
          }
    
       }
    
       if  (c == num)
    
          printf("%d is prime.\n", num);
    
       return  0;
    
    }

The output for the above code is:

 
Enter a number: 7

7 is prime.
  • We have created the variable num to store the user input and the variable c as a counter variable for the loop.
  • We are running the for loop from 2to num-1. If num is divisible by any value of c it will imply that it is divisible by a number other than 1 or itself. Therefore, it is a prime number. Otherwise, it is not a prime number.

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019