Tuesday, March 19, 2013

C Programming: Prime or Composite?

Leave a Comment
C Programming: Prime Numbers? This program shows you how to check if the number inputted by the user is a prime number. There are two versions of the program here, one has function and the other doesn't.


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


int main()
{
    int num, ctr = 2;
   
    printf("Enter a number: ");
    scanf("%d", &num);

    if(num == 1)
    {
           printf("\n%d is neither a prime or a composite number!", num);
           getch();
           exit(0);
    }
    if(num == 2)
    {
           printf("\n%d is a prime number!", num);
           getch();
           exit(0);
    }
    while((num % ctr) != 0)
    {
               ctr++;
               if(ctr == num)
               {
                      printf("\n%d is a prime number!", num);
                      getch();
                      exit(0);
               }
    }
    printf("\n%d is a composite number!", num);
   
    getch();
    return 0;
}

Program with function:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>


void isPrime(int);
int main()
{
    int num;
  
    printf("Enter a number: ");
    scanf("%d", &num);
    isPrime(num);
  
    getch();
    return 0;
}
void isPrime(int num)
{
     int ctr = 2;
   
     if(num == 1)
     {
            printf("\n%d is neither a prime or a composite number!", num);
            getch();
            exit(0);
     }

     if(num == 2)
     {
           printf("\n%d is a prime number!", num);
           getch();
           exit(0);
     }
     while((num % ctr) != 0)
     {
                ctr++;
                if(ctr == num)
                {
                       printf("\n%d is a prime number!", num);
                       getch();
                       exit(0);
                }
     }
     printf("\n%d is a composite number!", num);
}

Here's the output of the program:



0 comments:

Post a Comment