C Online Compiler
Example: Find Primes in Range using Basic Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Primes in Range using Basic Function #include <stdio.h> #include <stdbool.h> // For using bool data type // Function to check if a number is prime bool isPrime(int num) { if (num <= 1) { return false; // Numbers less than or equal to 1 are not prime } // Check for divisibility from 2 up to num-1 for (int i = 2; i < num; i++) { if (num % i == 0) { return false; // If divisible, it's not prime } } return true; // If no divisors found, it's prime } int main() { // Step 1: Declare variables for the range int lowerBound, upperBound; // Step 2: Get input for the range from the user printf("Enter the lower bound of the range: "); scanf("%d", &lowerBound); printf("Enter the upper bound of the range: "); scanf("%d", &upperBound); // Step 3: Ensure valid range (lower <= upper) if (lowerBound > upperBound) { int temp = lowerBound; lowerBound = upperBound; upperBound = temp; } // Step 4: Print a header for the output printf("Prime numbers between %d and %d are:\n", lowerBound, upperBound); // Step 5: Iterate through the range and check each number for primality for (int i = lowerBound; i <= upperBound; i++) { if (isPrime(i)) { printf("%d ", i); } } printf("\n"); // Newline for better formatting return 0; }
Output
Clear
ADVERTISEMENTS