Call us at 0700-922-6559 or Click here

Write a program to find whether the given number is a prime number.

#include <stdio.h>

int main() {

  int n, i, flag = 0;

  printf(“Enter a positive integer: “);

  scanf(“%d”, &n);

  // 0 and 1 are not prime numbers

  // change flag to 1 for non-prime number

  if (n == 0 || n == 1)

    flag = 1;

  for (i = 2; i <= n / 2; ++i) {

    // if n is divisible by i, then n is not prime

    // change flag to 1 for non-prime number

    if (n % i == 0) {

      flag = 1;

      break;

    }

  }

  // flag is 0 for prime numbers

  if (flag == 0)

    printf(“%d is a prime number.”, n);

  else

    printf(“%d is not a prime number.”, n);

  return 0;

}

Output-

Enter a positive integer: 29

29 is a prime number.

Leave a Reply

Your email address will not be published. Required fields are marked *