211k views
0 votes
C++ NEEDED HELP!! I have a test in a few days and I also got a new teacher this year that doesn't explain anything at all. No one in the class knows anything so please someone help. I left questions after the // in my code in the picture. I need some explanations. This is what the program is about:

The user enters an interval (from x to y), the program has to print all the prime numbers in that interval.
***Note: if somebody is willing to helpme out more leave ur snps users as well


C++ NEEDED HELP!! I have a test in a few days and I also got a new teacher this year-example-1
User Stakenborg
by
7.8k points

1 Answer

2 votes

Final answer:

To print all the prime numbers in an interval, use a loop to iterate through the numbers, check if each number is prime, and print it if it is. Here's an example code snippet to help you.

Step-by-step explanation:

To print all the prime numbers in an interval, you can follow these steps:

  1. Take input for the starting and ending points of the interval.
  2. Use a loop to iterate through all numbers in the interval.
  3. Check if each number is prime by dividing it by all numbers from 2 to its square root.
  4. If the number is divisible by any number other than 1 and itself, it is not prime.
  5. If the number is not divisible by any other number, it is prime, so print it.

Here's an example code snippet:

#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}

int main() {
int start, end;
cout << "Enter the starting point: ";
cin >> start;
cout << "Enter the ending point: ";
cin >> end;

cout << "Prime numbers in the interval are: ";
for (int i = start; i <= end; i++) {
if (isPrime(i))
cout << i << " ";
}
return 0;
}

User Cvsguimaraes
by
8.4k points