w3resource

C Exercises: Check whether a given number is prime or not

C For Loop: Exercise-32 with Solution

Write a C program to determine whether a given number is prime or not.

Visual Presentation:

Check whether a given number is prime or not

Sample Solution:

C Code:

#include <stdio.h> // Include the standard input/output header file.

int main() {
    int num, i, ctr = 0; // Declare variables for user input, loop control, and a counter.

    // Prompt the user to input a number.
    printf("Input a number: ");
    scanf("%d", &num); // Read the input number from the user.

    // Start a loop to check for factors of the input number.
    for (i = 2; i <= num / 2; i++) {
        if (num % i == 0) { // If the input number is divisible by 'i'.
            ctr++; // Increment the counter.
            break; // Exit the loop since a factor has been found.
        }
    }

    // If no factors were found and the number is not 1.
    if (ctr == 0 && num != 1)
        printf("%d is a prime number.\n", num); // Print that the number is prime.
    else
        printf("%d is not a prime number.\n", num); // Print that the number is not prime.

    return 0; // Return 0 to indicate successful execution.
}


Sample Output:

Input  a number: 13                                                                                           
13 is a prime number. 

Flowchart:

Flowchart : Check whether a given number is prime or not

C Programming Code Editor:

Previous: Write a program in C to display the pattern like a diamond.
Next: Write a C program to display Pascal's triangle

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.