This C program finds all prime numbers in a given range. It prompts the user to enter the starting and ending numbers of the range, then loops through each number in the range to check if it’s a prime number. If a number is a prime number, the program prints it to the screen.

## Problem Statement

Write a C program that finds all prime numbers in a given range. The program should prompt the user to enter the starting and ending numbers of the range, then loop through each number in the range to check if it’s a prime number. If a number is a prime number, the program should print it to the screen.

## Solution

#include <stdio.h> int main() { int start, end, i, j, flag; // Get the range from user printf("Enter the starting number of range: "); scanf("%d", &start); printf("Enter the ending number of range: "); scanf("%d", &end); // Validate input if (start < 2) { start = 2; } // Loop through each number in the range printf("Prime numbers between %d and %d are:\n", start, end); for (i = start; i <= end; i++) { // Check if i is a prime number flag = 1; for (j = 2; j <= i/2; j++) { if (i % j == 0) { flag = 0; break; } } // Print i if it's a prime number if (flag == 1) { printf("%d\n", i); } } return 0; }

## Output

## Explanation

The program starts by declaring variables to hold the starting and ending numbers of the range (start and end), a loop counter (i), another loop counter (j), and a flag variable to indicate whether a number is prime or not (flag).

The program then prompts the user to enter the starting and ending numbers of the range, and stores the values in the start and end variables.

Next, the program checks if the starting number is less than 2. If it is, it sets the starting number to 2, since 2 is the smallest prime number.

The program then loops through each number in the range using a for loop with i as the loop counter. For each number i, the program checks if it’s a prime number using a nested for loop with j as the loop counter. The inner for loop checks if i is divisible by any number between 2 and half of i. If i is divisible by any of these numbers, it means i is not a prime number, so the program sets the flag variable to 0 and breaks out of the inner loop.

After the inner loop, the program checks if the flag variable is still 1. If it is, it means i is a prime number, so the program prints i to the screen.

After looping through all the numbers in the range, the program exits.

## Conclusion

This C program demonstrates how to find all prime numbers in a given range. It prompts the user to enter the starting and ending numbers of the range, then loops through each number in the range to check if it’s a prime number. If a number is a prime number, the program prints it to the screen.

## Leave a Review