Program to check if the given number is prime or not

To check whether a given number is prime or not in C, you can use the following code:

#include <stdio.h>
#include <stdbool.h>

bool isPrime(int n) {
    if (n <= 1) {
        return false;
    }
    for (int i = 2; i <= n / 2; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

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

    if (isPrime(n)) {
        printf("%d is a prime number.\n", n);
    } else {
        printf("%d is not a prime number.\n", n);
    }

    return 0;
}

In this code, the isPrime() function checks whether a given number n is prime or not by iterating from 2 to n/2 and checking if n is divisible by any number in that range. If n is divisible by any number, it is not prime, and the function returns false. If no number divides n, it is prime, and the function returns true.

In the main() function, we take a number n from the user using scanf() and then call the isPrime() function to check if it is prime or not. We then print a message indicating whether the number is prime or not using printf().

, , ,

Related posts

What is WebSocket?

Introduction:

WebSockets is a communication protocol that provides a persistent, bidirectional, full-duplex connection between a...

Brief on HTTP Status codes

Introduction

HTTP (Hypertext Transfer Protocol) response codes are three-digit numbers that are returned by...

Latest posts

Leave a Comment

Leave a Reply

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

Please disable your adblocker or whitelist this site!

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site