The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Conditionals and recursion Alternative Execution | ||
See also: Conditional Execution | ||
Alternative Execution
A second form of conditional execution is alternative execution, in which there are two possibilities, and the condition determines which one gets executed. The syntax looks like: if (x%2 == 0) {cout << "x is even" << endl; } else { cout << "x is odd" << endl; }
As an aside, if you think you might want to check the parity (evenness or oddness) of numbers often, you might want to "wrap" this code up in a function, as follows: void printParity (int x) {if (x%2 == 0) { cout << "x is even" << endl; } else { cout << "x is odd" << endl; } } Now you have a function named printParity that will display an appropriate message for any integer you care to provide. In main you would call this function as follows: printParity (17);Always remember that when you call a function, you do not have to declare the types of the arguments you provide. C++ can figure out what type they are. You should resist the temptation to write things like: int number = 17;printParity (int number); // WRONG!!!
|
||
Home Conditionals and recursion Alternative Execution |