# using function to display prime numbers before user input not working.

#### Killerbee65

Joined May 15, 2017
243
C++:
#include <iostream>
using namespace std;

void display_purpose();
void get_input(int&, int&, int&);
bool isPrime(int);

int main()
{
display_purpose();
int num;
bool flag;

cout << "Enter any number(should be positive integer): ";
cin >> num;

if (num == 0 || num == 1) {
cout << num << " is not a prime number, nor does it have any before it\n";
}
else {
flag = isPrime(num);
if (flag == true)
cout << num << " is a prime number\n";
else
cout << num << " is not a prime number\n";
}
int min, max;
get_input(min, max, num);

cout << "\nPrime numbers smaller than " << num << " are: ";

// Smallest prime number is 2
for (int i = min; i <= max; i++)
{
if (isPrime(i))
cout << i << " ";
}
cout << endl;
return 0;
}

void display_purpose() {
cout << "The purpose of this program is to display all the prime numbers smaller than or equal to the given integer.\n";
}

bool isPrime(int num)
{
bool flag=true;

for(int i = 2; i <= num / 2; i++) {
if(num % i == 0) {
flag = false;
break;
}
}
static int times = 0;
if (times == 0)
{
cout << "This function is called for first time\n";
times++;
}
else
{
times++;
cout << "This function has been called " << times << " times so far\n";
}
return flag;
}
void get_input(int &maximum, int &mininum, int &num)
{
maximum = 10000;
mininum = 1;
if(num < mininum || num > maximum)
{
cout << "Error: the input must be between 1 and 10,000\n";
}
}
I'm not exactly sure why the code doesn't work when I input let's say 7 the program is supposed to display all the prime numbers before 7 and 7 (doesn't display user input if the input isn't a prime number). The problem is I'm not really sure why it doesn't work, comparing it to online solutions I can't see much of a difference.

#### WBahn

Joined Mar 31, 2012
26,308
Does this even compile? Unless the rules for C++ are significantly different than C, I don't see how?

What have you done to test it?

Have you tested the three functions you define at the bottom?