Branching Mechanisms ◆if-else statements Choice of two alternate statements based on condition expression ◆Example: if (hrs 40) grossPay rate*40 1.5*rate*(hrs-40); else grossPay rate*hrs; Copyright006 Pearson Addison-Wesley.All rights reserved. 2-11
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-11 Branching Mechanisms ¨ if-else statements ¨Choice of two alternate statements based on condition expression ¨Example: if (hrs > 40) grossPay = rate*40 + 1.5*rate*(hrs-40); else grossPay = rate*hrs;
if-else Statement Syntax ◆Formal syntax: if(<boolean expression>) <yes statement> else <no statement> Note each alternative is only ONE statement! To have multiple statements execute in either branch>use compound statement Copyright 2006 Pearson Addison-Wesley.All rights reserved. 2-12
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-12 if-else Statement Syntax ¨ Formal syntax: if (<boolean_expression>) <yes_statement> else <no_statement> ¨ Note each alternative is only ONE statement! ¨ To have multiple statements execute in either branch use compound statement
Compound/Block Statement Only "get"one statement per branch Must use compound statement for multiples Also called a "block"stmt Each block should have block statement Even if just one statement Enhances readability Copyright006 Pearson Addison-Wesley.All rights reserved. 2-13
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-13 Compound/Block Statement ¨ Only "get" one statement per branch ¨ Must use compound statement { } for multiples ¨Also called a "block" stmt ¨ Each block should have block statement ¨Even if just one statement ¨Enhances readability
Compound Statement in Action Note indenting in this example: if(myScore yourScore) cout <"I win!\n"; wagerwager 100; } else { cout <"I wish these were golf scores.\n"; wager 0; Copyright 2006 Pearson Addison-Wesley.All rights reserved. 2-14
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-14 Compound Statement in Action ¨ Note indenting in this example: if (myScore > yourScore) { cout << "I win!\n"; wager = wager + 100; } else { cout << "I wish these were golf scores.\n"; wager = 0; }