Well I'm learning C++ and according to the site I'm using this code can be shortened to half the size.
Code:
// declaring functions prototypes
#include <iostream>
using namespace std;
void odd (int a);
void even (int a);
int main ()
{
int i;
do {
cout << "Type a number (0 to exit): ";
cin >> i;
odd (i);
} while (i!=0);
return 0;
}
void odd (int a)
{
if ((a%2)!=0) cout << "Number is odd.\n";
else even (a);
}
void even (int a)
{
if ((a%2)==0) cout << "Number is even.\n";
else odd (a);
}
This example is indeed not an example of efficiency. I am sure that at
this point you can already make a program with the same result, but
using only half of the code lines that have been used in this example.
Anyway this example illustrates how prototyping works. Moreover, in this
concrete example the prototyping of at least one of the two functions
is necessary in order to compile the code without errors.
This is what I am came up with:
Code:
#include <iostream>
using namespace std;
int main ()
{
int i;
do {
cout << "Type a number (0 to exit): ";
cin >> i;
if ((i%2)!=0) cout << "Number is odd.\n";
else cout << "Number is even.\n";
}
while (i!=0);
return 0;
}
Is this the shortest it can be? If not how could I optimize it further?
Also, even though when I enter 0 and it closes how come this works? != is not equal to. :/
Code:
while (i!=0);
return 0;
9 sections and that's the only thing I don't understand.
Bookmarks