Find prime number in C Programming

In this tutorial I am going to discuss about how to find prime number in C Programming. Prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. So in this program we are going to divide our input number by (2 to n-1) to check that it is divisible by any of the number other than 1, itself or not. If it is not divisible then it is a prime number. In order to divide our input number from (2 to n-1) we are going to take a for loop in our program. Let’s have a look on the source code below.

#include <stdio.h>

int prime(int n) {
	int i, a;

	for (i = 2; i < n; i++) {
		a = n%i;
		if (a == 0) {
			break;
		}
	}

	return a;
}

int main() {

	int n, a;

	printf("Enter a number:");
	scanf("%d", &n);

	a = prime(n);

    if (a == 0) {
        printf("It is not a prime number\n");
    } else {
    	printf("YES, It is a prime number\n");
    }
    
	return 0;
}

Here is a screenshot of our compiled code.

Find Prime Number

Find Prime Number

Post Tagged with ,

Leave a Reply

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

20 + fifteen =

This site uses Akismet to reduce spam. Learn how your comment data is processed.