Break from loop
Write a program that takes a user-input and finds the next prime number.
Use break to stop the loop when a prime number is found.
You can refer back to task 1.5.6-1 for more information about how to find a prime number.
Example
7
11
500
503
Answer
#include <iostream>
#include <cmath>
int main()
{
// Get the input from the user
int input;
std::cout << "Input a number to get the following prime number.\n";
std::cin >> input;
// This is our counter variable.
// It will be incremented until we find the prime number we are looking for.
int prime_counter = input + 1; // +1 so that it doesn't start at the same number as the input
//Infinite counting loop
for (;; prime_counter++)
{
//Check if the number is prime
bool is_prime = true;
for (int j = 2; j <= sqrt(prime_counter); j++)
{
if (prime_counter % j == 0)
{
// If the number is not prime, update `is_prime`.
is_prime = false;
// Once is_prime is set to false, there's no reason to continue the inner loop, so we break from it for performance optimization.
break;
}
}
// If the number is 1 or 0, it is not prime
if (prime_counter <= 1)
is_prime = false;
// If a prime number is found `prime_counter` will contain the next prime number after `input`.
if (is_prime)
break;
}
// Output the result
std::cout << "The next prime number after " << input << " is " << prime_counter << std::endl;
}