Problems in C++ Prime Number Checker

Hi guys,

i have some problems with my program

my program should ask user ton enter two numbers

and then generate the primes between these numbers and output it on screen

and i must use a void function as our doctor say unless i will lose marks

i could not make the function void so i made it return function

and after i wrote the program i discovered that the program work correctly but it is output the primes and after the primes directly output " 1 "

so i have two problems the first that i must convert the function to void

and the second is i want to remove the " 1 " which make me crazy because its appear in every output and i hope you help me guys , this is the program :



#include<iostream>
#include<cmath>

using namespace std;

printPrimes ( int, int);


int main()

{
int num,num2;




cout<<"Enter The First Number:"<<endl;

cin>>num;

cout<<"Enter The Second Number:"<<endl;

cin>>num2;


while (num>=num2)

{
cout<<"The First Number Should Be smaller Than The Second Number"<<endl;

cout<<endl;

cout<<"Enter The First Number"<<endl;

cin>>num;

cout<<"Enter The Second Number"<<endl;

cin>>num2;

}


cout<<"The Primes Between The First Number and The Second Number are"<<endl;



cout<<printPrimes (num,num2)<<endl;



return 0;

}



printPrimes (int num,int num2)

{


bool prime = true;

int number3;

number3 =(int) floor (sqrt (num2));


while (num<=num2)

{
for ( int j = 2; j<=number3; j++)

{
if ( num!=j && num % j == 0 )

{
prime = false;
break;
}

}


if (prime)

{
cout <<" "<<num<<" "<<endl;


}

prime = true;


num++;

}

return prime;

}





and thanks in advance.
Ironically your two problems are actually the same one.

You need to use a void function but you're returning a value from your function. You're not suppose to be doing that as described by your instructor. Also, since you aren't returning anything, you obviously have to print from your function, which you did; cout<<" "<<num<<" "<<endl;. However you then return the boolean value prime, which is then printed by your statement in Main(): cout<<printPrimes (num,num2)<<endl;. This statement will print what ever is returned by printPrimes (this is why you see the 1 at the end of your list of primes. 1 is the boolean variable prime being returned by your function. 1 means that prime has a value of true.) Since you aren't suppose to be returning anything (i.e. void function) you don't want to call the printPrimes function from within a cout statement. Just call it by itself.


Do the following.

Before Main() change printPrimes ( int, int); to void printPrimes ( int, int);

In Main() change cout<<printPrimes (num,num2)<<endl; to printPrimes (num,num2);

After Main() change printPrimes (int num,int num2) to void printPrimes (int num,int num2). And remove this line: return prime;.
Last edited on
Topic archived. No new replies allowed.