C Exercises: Check if a given integer is prime using an inline function
C inline function: Exercise-8 with Solution
Write a C program to check if a given integer is prime using an inline function.
Sample Solution:
C Code:
#include <stdio.h>
// inline function to check if a given integer is prime
inline int is_Prime(int n) {
if (n <= 1) {
return 0;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int num;
printf("Input a positive integer: ");
scanf("%d", & num);
if (is_Prime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
Sample Output:
Input a positive integer: 13 13 is a prime number. Input a positive integer: 18 18 is not a prime number.
Explanation:
The is_prime() function takes an integer as an argument and returns 1 if it is prime and 0 otherwise. It works by iterating through all numbers from 2 up to the square root of the given number. It checks if the number is divisible by any of those numbers. If it is, it's not prime and the function returns 0. If it's not divisible by any of those numbers, it's prime and the function returns 1.
The main() function asks the user to input a positive integer, then uses the isPrime() inline function to check if the number is prime or not, and prints the result.
Flowchart:
C Programming Code Editor:
Previous: Count the number of vowels in a given string using an inline function.
Next: Check if a given integer is even or odd using an inline function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/inline_function/c-inline-function-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics