I have to write a program to determine if a number is odd or even. I have written the program and it works fine. But my instructor told me I need the logic that determines if the number is odd or even to be contained in a separate function; as in, not just logic floating in the main function.
I'm new to C++ and have no idea what he means or what to do. Here is the original working code, Thanks!
// Even and Odd solving program
#include <iostream>
usingnamespace std;
int main ()
{ int integer;
// Prompt user for integer and obtain integer.
cout << "Please enter an integer"
<< endl;
cin >> integer;
// determine if integer is even or odd
if ( integer % 2== 0 )
// if the integer when divided by 2 has no remainder then it's even.
cout << integer << " is even "
<<endl;
else
// the integer is odd
cout << integer << " is odd "
<<endl;
return 0;
}
I read those and I'm still a little confused as to what exactly I can do to change my code to include the logic in a separate function. If I declare another function won't I need parameters? Wouldn't it change how I solved it, or would I be using type void?
// Even and Odd solving program
#include <iostream>
usingnamespace std;
bool isOdd(int integer);
int main ()
{ int integer;
// Prompt user for integer and obtain integer.
cout << "Please enter an integer"
<< endl;
cin >> integer;
// determine if integer is even or odd
if(isOdd(integer) == true)
cout << integer << "is odd." << endl;
else
cout << integer << "is even." << endl;
return 0;
}
bool isOdd( int integer )
{
if ( integer % 2== 0 )
returntrue;
elsereturnfalse;
}
Of course using functions alters how you solve the problem.
Of course you have to use parameters.
I suggest you try playing around with some very simple function calls until things become clear as you won't be able to do very much at all in C++ without understanding the concept.