Problem 43

author
By Supreme2023-03-15
Problem Statement :
Write a function in the program to return 1 if number is prime otherwise return 0
Code:

#include <stdio.h>

int prime(int n);

int main() {

//43. Write a function in the program to return 1 if number is prime otherwise return 0

int n;

printf("\tPrime Number");
printf("\n====================================\n\n");

printf("Enter The Number : ");
scanf("%d",&n);
int result = prime(n);

printf("\n------------------------------------\n\n");

if (result == 1) {
printf("%d is a prime number\n", n);
} else {
printf("%d is not a prime number\n", n);
}
printf("\n------------------------------------\n\n");

return 0;
}

int prime(int n) {
int i;
if (n <= 1) {
return 0;
}
for (i = 2; i < n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}

Description :
  • This program checks if a given number is a prime number or not.
  • The program first prompts the user to enter a number.
  • The main function then calls the function prime and passes the user input as an argument to it.
  • The prime function takes an integer argument n.
  • If the value of n is less than or equal to 1, the function returns 0 as the number is not a prime number.
  • Otherwise, the function checks if the number is divisible by any number between 2 and n-1.
  • If it is divisible by any number, it returns 0 as the number is not a prime number.
  • If it is not divisible by any number, it returns 1 as the number is a prime number.
  • The main function then checks the return value of prime and displays an appropriate message.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.