11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

62 Part I: Introduction to C++ ProgrammingIn C++, the branch statement is implemented using the if statement:if (m > n){// Path 1// ...instructions to be executed if// m is greater than n}else{// Path 2// ...instructions to be executed if not}First, the logical expression m > n is evaluated. If the result of the expressionis true, control passes down the path marked Path 1 in the previous snippet.If the expression is false, control passes to Path 2. The else clause isoptional. If it is not present, C++ acts as if it is present but empty.Actually, the braces are optional (sort of) if there’s only one statement to executeas part of the if. If you lose the braces, however, it’s embarrassinglyeasy to make a mistake that the C++ compiler can’t catch. The braces serveas a guide marker; it’s much safer to include ’em. (If your friends try to enticeyou into not using braces, “Just say No.”)The following program demonstrates the if statement (note all the lovelybraces):// BranchDemo - input two numbers. Go down one path of the// program if the first argument is greater than// the first or the other path if not#include #include #include using namespace std;int main(int nNumberofArgs, char* pszArgs[]){// input the first argument...int arg1;cout > arg1;// ...and the secondint arg2;cout > arg2;// now decide what to do:if (arg1 > arg2)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!