w3resource

C Exercises: Find the prime numbers within a range of numbers

C For Loop: Exercise-34 with Solution

Write a program in C to find the prime numbers within a range of numbers.

Sample Solution:

C Code:

#include <stdio.h> // Include the standard input/output header file.

int main() {
    int num, i, ctr, stno, enno; // Declare variables for the number, loop counters, and range.

    // Prompt the user to input the starting number of the range.
    printf("Input starting number of range: ");
    scanf("%d", &stno); // Read the input from the user.

    // Prompt the user to input the ending number of the range.
    printf("Input ending number of range : ");
    scanf("%d", &enno); // Read the input from the user.

    // Print the message indicating the range.
    printf("The prime numbers between %d and %d are: \n", stno, enno);

    for (num = stno; num <= enno; num++) { // Loop through the numbers in the specified range.
        ctr = 0; // Initialize the counter.

        for (i = 2; i <= num / 2; i++) { // Loop through possible divisors.
            if (num % i == 0) { // If a divisor is found...
                ctr++; // ...increment the counter.
                break; // Exit the loop.
            }
        }

        if (ctr == 0 && num != 1) // If no divisors were found and the number is not 1...
            printf("%d ", num); // ...print the prime number.
    }

    printf("\n"); // Move to the next line after printing all prime numbers.

    return 0; // Return 0 to indicate successful execution.
}


Sample Output:

Input starting number of range: 1                                                                             
Input ending number of range : 50                                                                             
The prime numbers between 1 and 50 are :                                                                      
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47  

Flowchart:

Flowchart : Find the prime numbers within a range of numbers.

C Programming Code Editor:

Previous: Write a C program to display Pascal's triangle
Next: Write a program in C to display the first n terms of Fibonacci series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.