Write a C++ Program to Display Prime Numbers Between Two Intervals.
#include <iostream>
using namespace std;
bool isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) return false;
}
return true;
}
int main() {
int start, end;
cout << "Enter the starting number: ";
cin >> start;
cout << "Enter the ending number: ";
cin >> end;
cout << "Prime numbers between " << start << " and " << end << " are: ";
for (int i = start; i <= end; i++) {
if (isPrime(i)) cout << i << " ";
}
return 0;
}
//===========
OUTPUT:
Enter the starting number: 10
Enter the ending number: 30
Prime numbers between 10 and 30 are: 11 13 17 19 23 29
Explanation:
- We define a function isPrime that takes an integer as input and returns a boolean value indicating whether the number is prime or not.
- In the isPrime function, we first check if the number is less than or equal to 1, because any number less than or equal to 1 is not prime.
- We then use a loop to check if the number is divisible by any number between 2 and half the number (inclusive). If the number is divisible by any of these numbers, then it is not prime and we return false. Otherwise, we return true indicating that the number is prime.
- In the main function, we first ask the user to input the starting and ending numbers.
- We then use a loop to iterate through all the numbers between the starting and ending numbers (inclusive) and check if each number is prime using the isPrime function.
- If a number is prime, we print it to the console.
Notes:
- The program makes use of a function to check if a number is prime, which makes the code more modular and easier to read.
- The program takes user input for the starting and ending numbers, which makes it more flexible and reusable.
- The program uses a for loop to iterate through the numbers between the starting and ending numbers, which is a simple and efficient way to accomplish the task.
- The program uses the modulus operator to check if a number is divisible by another number, which is a common technique in programming for checking divisibility.
- The program uses the cout and cin objects from the iostream library to output messages to the console and input data from the user.
No comments:
Post a Comment