Friday, October 18, 2013

C Programming Prime Number Program

Prime Number Program In C Language

This is the program written in c language to take the user input and detect whether it is a prime number or not. there is a little learning curve in this program regarding the if statements so if you stick with the program and read the important outlines you will be able to understand properly.

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

 void main()
{
   int n,c;

   printf("Enter a number to check if it is prime\n");
   scanf("%d",&n);

   for ( c = 2 ; c <= n - 1 ; c++ )
   {
      if ( n%c == 0 )
      {
         printf("%d is not prime.\n", n);
     break;
      }                                       
      }

   if ( c == n )
   {   

printf("%d is prime.\n", n);
}
getch();
}



Note the important instruction which will be able to understand.

it means the loop will start from 2 and it will end the user input - 1 . It means it will end on n-1 .

We have take the user input in the variable "n" . and if the "c" is greater than n-1 the statement becomes false and it came from loop. After the end of first "if" statement the value of  will be c=n so we have given the second statement of "if" . which will print the number . The number will be equal to prime numbers

No comments:

Post a Comment