c
  1. c-program-to-check-whether-a-number-is-prime-or-not

Program to Check Whether a Number is Prime or Not - (C Programs)

Introduction

In this article, we will discuss how to write a C program to check whether a given integer number is prime or not. Prime numbers are those numbers that are divisible only by 1 and itself. For example, 2, 3, 5, 7, 11, 13, 17, 19, 23, and so on are prime numbers.

Example

Let's take an example to understand how this program works:

Input: 17

Output: 17 is a prime number

Explanation

To check whether a number is prime or not, we need to divide that number by every integer number starting from 2 to the number itself. If the number is divisible by any integer, other than 1 and itself, it is not a prime number. If the number is not divisible by any integer, other than 1 and itself, it is a prime number.

Program

#include <stdio.h>

int main()
{
    int n, i, flag = 0;

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

    for(i = 2; i <= n/2; ++i)
    {
        // condition for non-prime number
        if(n%i == 0)
        {
            flag = 1;
            break;
        }
    }

    if (n == 1)
    {
        printf("1 is not a prime number.");
    }
    else
    {
        if (flag == 0)
        {
            printf("%d is a prime number.", n);
        }
        else
        {
            printf("%d is not a prime number.", n);
        }
    }

    return 0;
}

Output

If we run the program with the input value as 17, it will output:

Enter a positive integer: 17
17 is a prime number.

Use

This program can be used to check whether a given number is prime or not. It is useful in various mathematical calculations and algorithms.

Summary

In this article, we have discussed how to write a C program to check whether a given number is prime or not. We have also provided an example and explained the logic of the program. This program can be used in various mathematical calculations and algorithms.

Published on: