2. Condition logic / Decisions and Branching Recall the problems we solved in week #1 & 2: we used “if (n1 > n2) { … }” to check condition and branch This chapter will cover condition logic in detail
3. General view if (condition) { // condition is true // processing1 } else { // condition is false // processing2 } is condition true? false true Processing1 Processing2
4.
5. Eg: For the condition (n1 > n2) => Is n1 greater than n2? The result is a ‘true’ or ‘false’
6. Condition if (condition) { // processing1 } else { // processing2 } How to set condition? Use operand to compare Eg (n1 == n2) (n1 != n2)
7. Condition if (condition) { // processing1 } else { // processing2 } With more than 1 condition Use && for “and”: (condition1) && (condition2) Use || for “or”: (condition1) || (condition2) Eg (n1 >= 0) && (n2 >=0) => both n1 and n2 must be positive Eg (n1 >= 0) || (n2 >=0) => either n1 or n2 is positive
8. condition Comparing Boolean type: boolbuttonClicked = false; if (buttonClicked == true) { … } if ( !buttonClicked) { … } // not buttonClicked
12. Other branching – if only if (condition) { // condition is true // processing1 } // No else branch is condition true? false true Processing1
13. Other branching – if .. Else if .. else is condition1 true? if (condition1) { // condition is true // processing1 } else if (condition2) { // condition1 is false and // condition2 is true // processing2 } else {// condition1 is false and //condition2 is false // processing3 } false true is condition2 true? Processing1 false true Processing2 Processing3
14. Other branching - switch switch (n1) { case 1: // processing1 break; case 2: // processing2 break; default: // processing3 break; } n1 1 2 3 Processing2 Processing3 Processing1
15. Other branching - switch switch (n1) { case 1: case 2: // processing2 break; default: // processing3 break; } n1 1, 2 3 Processing2 Processing3
16. Other branching - switch switch (n1) { case 1: // processing1 goto case 2; case 2: // processing2 break; default: // processing3 break; } n1 1 2 3 Processing1 Processing2 Processing3
17. Exercise 5.1 Textbook from page 93 – 98: Part 1 if Statements Part 2 else ... if in C# .NET
18. Exercise 5.2 Textbook from page 98 – 106: Part 3 switch Statements in C# .NET Part 4 C# Operators
19. Exercise 5.3(a) For the GUI created in Exercise 3.2: Rename all the controls to follow proper naming convention: egtextboxOutput, buttonZero, etc Use winword to draft the pseudo codes for all the button click methods (you may need some variables outside the methods to be accessible by all methods)
20. Exercise 5.3(b) For the GUI created in Exercise 3.2: Create a new project: Exercise53B Select all the controls in Exercise32 and paste into this new project Code and debug manually by viewing the codes No worry: we shall use debugging tool to debug this project in chapter 6: Debugging