FYBCom(CA) C Practical Slip 4 Q 1.B

Check if a Number is Prime in C Using Function

1. Introduction

Prime numbers are integers greater than 1 that have no divisors other than 1 and themselves. Checking for prime numbers using functions helps beginners understand modular programming in C.

2.Problem Statement

Question: Write a C program to check if a number is prime or not using a function.

3. Logic

To check whether a number is prime:

  1. Create a function that accepts an integer as input.
  2. Check if the number is less than 2; if yes, it is not prime.
  3. Loop from 2 to the square root of the number and check if any number divides it evenly.
  4. If no divisor is found, the number is prime; otherwise, it is not.
  5. Call the function from main() and display the result.

4. Source Code

Here is a beginner-friendly C program using a function:

#include <stdio.h>
#include <math.h>

// Function to check prime
int isPrime(int num) {
    if(num < 2)
        return 0; // Not prime
    for(int i = 2; i <= sqrt(num); i++) {
        if(num % i == 0)
            return 0; // Not prime
    }
    return 1; // Prime
}

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

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

    return 0;
}

5. Sample Output

Enter a number: 17
17 is a prime number.
Enter a number: 20
20 is not a prime number.

6.Viva Questions

  1. Q: What is a prime number?
    A: A prime number is greater than 1 and divisible only by 1 and itself.
  2. Q: Why do we check up to the square root of the number?
    A: Because if a number has a factor larger than its square root, the corresponding smaller factor will already be found.
  3. Q: Can negative numbers be prime?
    A: No, prime numbers are always positive integers greater than 1.
  4. Q: What is the purpose of using a function here?
    A: To modularize the code and make it reusable.
  5. Q: What does return 0 in the function indicate?
    A: That the number is not prime.

Spread the love

Leave a Comment

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

Scroll to Top