C Program to Check Prime Number

1. Introduction

A prime number is a number greater than 1 that is divisible only by 1 and itself. Prime numbers play a pivotal role in number theory, encryption, and other areas of mathematics and computer science. In this article, we will develop a C program that checks whether a given number is prime.

2. Program Overview

The sequence of our program will be:

1. Ask the user for a number.

2. Check if the number is prime or not.

3. Display the result to the user.

3. Code Program

#include <stdio.h>  // Integrate the Standard I/O library for input and output functionalities

int main() {  // Main function commencement

    int num, flag = 0;

    // Prompting user for input
    printf("Enter a positive integer: ");
    scanf("%d", &num);  // Acquire the user's number

    // Prime numbers are greater than 1
    if (num <= 1) {
        printf("%d is not a prime number.\n", num);
        return 1;
    }

    // Check from 2 to num/2
    for (int i = 2; i <= num / 2; ++i) {

        // If num is divisible by any number other than 1 and itself
        if (num % i == 0) {
            flag = 1;
            break;
        }
    }

    // If flag remains 0, num is prime
    if (flag == 0) {
        printf("%d is a prime number.\n", num);
    } else {
        printf("%d is not a prime number.\n", num);
    }

    return 0;  // Indicate successful execution of the program
}

Output:

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

4. Step By Step Explanation

1. #include <stdio.h>: This header file inclusion equips us with the standard input-output functionalities.

2. int main(): This is the main function where the program execution starts.

3. Initialization of num and flag: The variable num will store the user's input, while flag is used as an indicator. If the number is divisible by any number other than 1 and itself, flag will be set to 1.

4. The prime number check:

- If the number is less than or equal to 1, it's not prime.

- Otherwise, we use a loop to check divisibility from 2 up to num/2. If num is divisible by any number in this range, it's not prime. By checking only up to num/2, we optimize the program, as no number is divisible by a number larger than its half.

5. Output: The program displays whether the entered number is prime or not based on the flag value.

This approach offers an intuitive method to check for prime numbers and highlights the importance of optimization (checking only up to num/2) in programming.

Comments