I've been using C++ tutorials for about a week. I wanted to start off with something basic but helpful. So I went on to do some extremely simple programs. While I was doing this I found the odd/even program which determines which is odd and which is even.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Code-Set 2
#include <iostream>
usingnamespace std;
void odd (int a);
void even (int a);
int main ()
{
int i;
do
{
cout << "Type a number: ";
cin >> i;
odd (i);
} while (i != 0);
return 0;
}
Type a number (0 to exit): 9
Number is odd.
Type a number (0 to exit): 6
Number is even.
Type a number (0 to exit): 1030
Number is even.
Type a number (0 to exit): 0
Number is even.
While I do this I get an program with input ability same as this code:
// Code-Set 2
#include <iostream>
usingnamespace 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);
}
Type a number (0 to exit): 9
Number is odd.
Type a number (0 to exit): 6
Number is even.
Type a number (0 to exit): 1030
Number is even.
Type a number (0 to exit): 0
Number is even.
Im not verifying what to write if its odd or even. Yet the first set of codes do the exact same work as the second set. I can't figure out why and how the extra lines come out of code set 1. Why is it so?
I'm not entirely sure what you're asking, but there's no way snippet 1 is producing output 1. In fact, it doesn't even compile; the compiler will complain about undefined symbols.
On an unrelated note, be very careful when writing mutually recursive functions. In this case, there's no problem because the functions and the cases they handle are simple, but more complex functions are easier to screw up.
@Capt I guess you are unknowingly including the definition of the functions in the snippet1.
As helios mentioned,otherwise the problem is bound to give a compilation error.