#include <stdio.h>

// Function to check if a number is prime
int isPrime(int num) {
    if (num <= 1) return 0; // Numbers less than 2 are not prime
    for (int i = 2; i * i <= num; i++) { // Check divisibility up to the square root of num
        if (num % i == 0) return 0; // If divisible, it's not prime
    }
    return 1; // If not divisible, it's prime
}

int main() {
    int start, end;

    // Prompt user for input range
    printf("Enter the starting number of the range: ");
    scanf("%d", &start);
    printf("Enter the ending number of the range: ");
    scanf("%d", &end);

    printf("Prime numbers between %d and %d are:\n", start, end);

    // Loop through the range and check for prime numbers
    for (int num = start; num <= end; num++) {
        if (isPrime(num)) {
            printf("%d ", num); // Print the prime number
        }
    }
    printf("\n"); // New line after the list of prime numbers

    return 0;
}

Explanation of the Code

Loops through each number in the range and uses the isPrime function to check if it’s prime. If it is, the number is printed.

Header Files: The stdio.h library is included for input and output functionalities.

Function isPrime(int num):

Checks if a number is prime.

Returns 0 for numbers less than or equal to 1 (not prime).

Uses a loop to test for factors from 2 up to the square root of num. If num is divisible by any of these, it’s not prime and returns 0.

If no factors are found, it returns 1, indicating the number is prime.

Main Function:

Prompts the user for the starting and ending numbers of the range.

Prints a header for the prime numbers found.

Output

Enter the starting number of the range: 10
Enter the ending number of the range: 30
Prime numbers between 10 and 30 are:
11 13 17 19 23 29

Leave a Reply

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

Verified by MonsterInsights