English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C language basic tutorial

C language flow control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C language structures

C language files

C others

C language reference manual

C program to check if a number is prime

Comprehensive Collection of C Programming Examples

In this example, you will learn to check if the integer entered by the user is a prime number.

To understand this example, you should understand the followingC programming languageTopic:

A prime number is a positive integer that can only be1divisible by itself. For example:2,3,5,7,11,13,17

Program to check prime numbers

#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
        if (n % i == 0) {
            flag = 1;
            break;
        }
    }
    if (n == 1) {
        printf("1neither prime nor composite.");
    }
    else {
        if (flag == 0)
            printf("%d is a prime number.", n);
        else
            printf("%d is not a prime number.", n);
    }
    return 0;
}

Output the result

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

In the program, the for loop starts from iteration i = 2to i < n/2.

In each iteration, check if n can be completely divided by i:

if (n % i == 0) {
   
}

If n can be divided by i, n is not a prime number. In this example, set the flag to1, and use the break statement to terminate the loop.

After the loop, if n is a prime number, the flag is still 0. However, if n is not a prime number, the flag is1.

Visit this page to learn howPrint all prime numbers between two intervals.

Comprehensive Collection of C Programming Examples