Complementary task for topic: 4

M Nemeth · 2023-08-29 15:21:04.618220'

Functions: Print Prime Numbers in a Range

Functions: Print Prime Numbers in a Range

Write a C function print_primes_in_range that takes two integers as input, start, and end, and prints all the prime numbers between the start and end (inclusive).

Hint:

Solution
#include 

// Function to check if a number is prime
int is_prime(int num) {
    if (num <= 1)
        return 0;

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

// Function to print prime numbers in a range
void print_primes_in_range(int start, int end) {
    printf("Prime numbers between %d and %d are: ", start, end);
    for (int i = start; i <= end; ++i) {
        if (is_prime(i))
            printf("%d ", i);
    }
    printf("\n");
}

int main() {
    int start, end;
    printf("Enter the range (start end) to find prime numbers: ");
    scanf("%d %d", &start, &end);

    if (start > end) {
        printf("Invalid range. Start value should be less than or equal to the end value.\n");
    } else {
        print_primes_in_range(start, end);
    }

    return 0;
}



Explanation
The is_prime function is the same as the one we used in a previous task to check if a number is prime.

The print_primes_in_range function takes two integers, start and end, as input and prints all the prime numbers between the start and end (inclusive). It uses a loop to iterate from start to end, and for each number, it calls the is_prime function to check if it is prime. If it is prime, the number is printed.
< < previous    next > >