1 / 84

Solving Problems that involve decisions Version 1.0

Solving Problems that involve decisions Version 1.0. Topics. Normal execution order. Conditional statements. Relational operators & Boolean expressions. Enumerations. Objectives. At the completion of this topic, students should be able to:.

Download Presentation

Solving Problems that involve decisions Version 1.0

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Solving Problems thatinvolve decisionsVersion 1.0

  2. Topics Normal execution order Conditional statements Relational operators & Boolean expressions Enumerations

  3. Objectives At the completion of this topic, students should be able to: Describe the normal flow of control through a C# program Correctly use if statements in a C# program Explain how to use relational operators to write a Boolean expression and use them correctly in a C# program Correctly use if/else statements in a C# program Correctly use blocks in if/else statements Correctly use a switch statement in a C# program Describe enumerations and use them in a C# program Correctly use the logical operators to make complex Boolean expressions

  4. The order in which statements in a program are executed is called the flow of control. Programs that we have written so far begin with the first line in the Main( ) method, and continues line by line until control reaches the end of Main( ).

  5. There are many problems that cannot be solved with a program that executes in this line-by-line fashion from beginning to end. Some problems require the program to take different actions, depending upon conditions that exist in the program at the time.

  6. For example, the U.S. Widget company runs its payroll program at the end of every two week period. If an employee gets paid by the hour, that employee’s gross pay is equal to hoursWorked * hourlyWage; However, if an employee gets paid a salary, that employee’s gross pay is calculated differently yearlySalary / 26.0;

  7. In a computer chess game, the computer might calculate its move in a number of different ways, depending upon where all of the various pieces on the chessboard.

  8. How can you tell if a problem requires a program that includes this kind of logic?

  9. When the problem statement includes the word “if” If this employee gets an hourly wage If the King is in check If today is a weekday If the balance in the account is less than $1,000

  10. Sometimes the problem statement will use the word “when” When an employee gets an hourly wage When the King is in check When theday is a weekday When the balance in the account is less than $1,000

  11. These are all examples of Conditional Statements, i.e. do something if a condition is true. In programming we often take a different action based on whether or not a condition is true.

  12. Conditional statements are shown in an activity diagram by using a diamond. balance < LIMIT ? ( balance < LIMIT )

  13. Conditional statements are shown in an activity diagram by using a diamond. Arrows show the execution path that the program takes when the statement is true and when it is false. balance < LIMIT ? true if ( balance < LIMIT ) false

  14. Conditional statements are shown in an activity diagram by using a diamond. Arrows show the execution path that the program takes when the statement is true and when it is false. balance < LIMIT ? true if ( balance < LIMIT ) The “if” statement tests the condition. false

  15. The if Statement The if statement allows us to execute a statement only when the condition is true. balance < LIMIT ? balance = balance – CHARGE; true if ( balance < LIMIT ) balance = balance – CHARGE; false note how we have indented the statement to be executed when the condition is true. Although the compiler doesn’t care about indentation, it makes it easier to read the code.

  16. Problem Statement Write a program that prompts the user to enter in his or her age. the person is under 21, print a message that says “Youth is a wonderful thing … enjoy it.” If

  17. Prompt user to Enter in their age Store input in the variable age true age < 21 ? Print “Youth is a …” false end

  18. using System; class Program { const int MINOR = 21; static void Main() { intage = 0; Console.Write("How old are you? "); age = int.Parse(Console.ReadLine()); if (age < MINOR) Console.WriteLine("Youth is a wonderful thing ... enjoy it."); Console.WriteLine(“Goodbye!”); Console.ReadLine(); }//End Main() }//End class Program

  19. The expression inside the if( … ) statement is called a Boolean expression, because its value must be either true or false.

  20. Relational Operators relational operators are used to write Boolean expressions Operator Meaning == equal != not equal < less than <= less than or equal > greater than >= greater than or equal (not greater than) (not less than) Note: The precedence of relational operators is lower than arithmetic operators, so arithmetic operations are done first.

  21. Note that the following expression will not compile in C#… if ( age = myNewAge) { . . . } This is an assignment, not a comparison

  22. The if/else statement This construct allows us to do one thing if a condition is true, and something else if the condition is false. height > MAX ? adjustment = MAX - height true if (height > MAX) adjustment = MAX – height; else adjustment = 0; Console.WriteLine(adjustment); false adjustment = 0

  23. Problem Statement Write a program that prompts the user to enter in his or her age. the person is under 21, print a message that says “Youth is a wonderful thing … enjoy it.” Otherwise, print a message that says “Old age is a state of mind.” If

  24. Prompt user to Enter in their age Store input in the variable age age < 21 ? true Print “Youth is a …” false Print Old age is a…” end

  25. using System; class Program { const int MINOR = 21; static void Main() { int age; Console.Write("How old are you? "); age = int.Parse(Console.ReadLine()); if (age < MINOR) Console.WriteLine("Youth is a wonderful thing ... enjoy it."); else Console.WriteLine("Old age is a state of mind...!"); Console.ReadLine(); }//End Main() }//End class Program

  26. Executing a Block of Statements Sometimes we want to execute more than one statement when a condition is true ( or false ). In C#, we can use a block of statements, delimited by { and } anyplace where we would normally use a single statement. if ( a < b ) { a = 0; b = 0; Console.WriteLine(“Sorry …”); } . . .

  27. using System; class Program { const int MINOR = 21; static void Main() { int age; Console.Write("How old are you? "); age = int.Parse(Console.ReadLine()); if (age < MINOR) { Console.WriteLine("**********************************"); Console.WriteLine("* Youth is a wonderful thing *"); Console.WriteLine("* Enjoy it! *"); Console.WriteLine("**********************************"); } else { Console.WriteLine("***********************************"); Console.WriteLine("* Old age is a *"); Console.WriteLine("* state of mind...! *"); Console.WriteLine("***********************************"); } Console.ReadLine(); }//End Main() }//End class Program

  28. Nested if/else Statements In C#, the statement to be executed as the result of an if statement could be anotherif statement. In a nested if statement, an else clause is always matched to the closest unmatched if.

  29. using System; class Program { static void Main() { int a, b, c, min = 0; Console.WriteLine("Enter three integer values - each on a separate line."); a = int.Parse(Console.ReadLine()); b = int.Parse(Console.ReadLine()); c = int.Parse(Console.ReadLine()); if (a < b) if (a < c) min = a; else min = c; else if (b < c) min = b; else min = c; Console.WriteLine("The smallest value entered was {0}", min); Console.ReadLine(); }//End Main() }//End class Program keep track of which ifan else goes with!

  30. using System; class Program { static void Main() { int a, b, c, min = 0; Console.WriteLine("Enter three integer values - each on a separate line."); a = int.Parse(Console.ReadLine()); b = int.Parse(Console.ReadLine()); c = int.Parse(Console.ReadLine()); if (a < b) if (a < c) min = a; else min = c; else if (b < c) min = b; else min = c; Console.WriteLine("The smallest value entered was {0}", min); Console.ReadLine(); }//End Main() }//End class Program Hmmm … it’s hard without indenting code

  31. using System; class Program { static void Main() { int a, b, c, min = 0; Console.WriteLine("Enter three integer values - each on a separate line."); a = int.Parse(Console.ReadLine()); b = int.Parse(Console.ReadLine()); c = int.Parse(Console.ReadLine()); if (a < b) if (a < c) min = a; else min = c; else if (b < c) min = b; else min = c; Console.WriteLine("The smallest value entered was {0}", min); Console.ReadLine(); }//End Main() }//End class Program Hmmm … it’s worse if you indent wrong

  32. Another Example char direction = ‘n’; Console.WriteLine("Press a direction key(n, s, e, or w) and Enter"); direction = char.Parse(Console.ReadLine()); if (direction == 'n') Console.WriteLine("You are now going North."); else if (direction == 's') Console.WriteLine("You are now going South."); else if (direction == 'e') Console.WriteLine("You are now going East."); else if (direction == 'w') Console.WriteLine("You are now going West."); else Console.WriteLine("You don't know where you are going!"); Console.ReadLine();

  33. if (direction == 'n') Console.WriteLine(“…going North."); else if (direction == 's') Console.WriteLine(“…going South."); else if (direction == 'e') Console.WriteLine(“…going East."); else if (direction == 'w') Console.WriteLine(“…going West."); else Console.WriteLine("You don't know…!"); These are exactly the same. The only difference is how the code is indented. if (direction == 'n') Console.WriteLine(“…going North."); else if (direction == 's') Console.WriteLine(“…going South."); else if (direction == 'e') Console.WriteLine(“…going East."); else if (direction == 'w') Console.WriteLine(“…going West."); else Console.WriteLine("You don't know…!");

  34. if (direction == 'n') Console.WriteLine(“…going North."); else if (direction == 's') Console.WriteLine(“…going South."); else if (direction == 'e') Console.WriteLine(“…going East."); else if (direction == 'w') Console.WriteLine(“…going West."); What’s the difference? if (direction == 'n') Console.WriteLine(“…going North."); if (direction == 's') Console.WriteLine(“…going South."); if (direction == 'e') Console.WriteLine(“…going East."); if (direction == 'w') Console.WriteLine(“…going West.");

  35. if (direction == 'n') Console.WriteLine(“…going North."); else if (direction == 's') Console.WriteLine(“…going South."); else if (direction == 'e') Console.WriteLine(“…going East."); else if (direction == 'w') Console.WriteLine(“…going West."); Suppose that ‘n’ was entered. if (direction == 'n') Console.WriteLine(“…going North."); if (direction == 's') Console.WriteLine(“…going South."); if (direction == 'e') Console.WriteLine(“…going East."); if (direction == 'w') Console.WriteLine(“…going West.");

  36. if (direction == 'n') Console.WriteLine(“…going North."); else if (direction == 's') Console.WriteLine(“…going South."); else if (direction == 'e') Console.WriteLine(“…going East."); else if (direction == 'w') Console.WriteLine(“…going West."); Suppose that ‘n’ was entered. This statement is executed and all of the others are skipped.

  37. Suppose that ‘n’ was entered. The first output statement is executed, then each of the other if statements is executed in turn. There is no else clause to cause control to skip these. if (direction == 'n') Console.WriteLine(“…going North."); if (direction == 's') Console.WriteLine(“…going South."); if (direction == 'e') Console.WriteLine(“…going East."); if (direction == 'w') Console.WriteLine(“…going West.");

  38. Dangling else clauses An else is always matched to the closest unmatched if

  39. Will this code do what you expect? const intLIMIT = 40; . . . if (regTime > LIMIT) if (overTime > LIMIT) Console.WriteLine(“Overtime hours exceed the limit.”); else Console.WriteLine(“no overtime worked.”);

  40. Will this code do what you expect? const intLIMIT = 40; . . . if (regTime > LIMIT) if (overTime > LIMIT) Console.WriteLine(“Overtime hours exceed the limit.”); else Console.WriteLine(“no overtime worked.”); This else goes with The second if statement If regTime were 50 and overTime were 30, the message “no overtime worked” would be displayed. . . .

  41. The code should be written this way. const intLIMIT = 40; . . . if (regTime > LIMIT) { if (overTime > LIMIT) Console.WriteLine(“Overtime hours exceed the limit.”); } else Console.WriteLine(“no overtime worked.”);

  42. Practice: Write a program that takes a temperature in degrees Celsius. Then output whether or not water is a solid, liquid, or vapor at that temperature at sea level. Example: Input: -5 Output: Water is solid

  43. Designing programs that use conditional statements

  44. Carefully inspect the problem statement. If • word “if” is used or the word “when” is used • to describe different situations that might • exist, then the program probably will need • to use conditional statements.

  45. After determining that several different situations • might exist, try to identify each unique situation. • Write down the condition that makes this situation • unique. • Carefully check that each condition is unique - there • should be no overlaps. Be sure that the boundary • conditions are correctly stated.

  46. Write down exactly what the program should do • differently in each of the unique situations • that you have identified.

  47. Formulate the if/else statements that reflect • this set of conditions. Make them as simple • as possible. Watch for dangling else’s.

  48. Example Slick Guys Used Car Sales gives their sales people a commission, based on the value of the sale. If the sale was made at or above the sticker price, the sales person gets a 20% commission. If the sale was less than the full sticker price, but greater than the blue book price, the sales commission is 10%. If the sale price is equal to the blue book price, the sales person gets a 5% commission. Slick Guys never sells a car for less than the blue book price.

  49. How many conditions are there? What are the conditions?

  50. 4 Conditions 1. The sales price is GREATER than or EQUAL to the sticker price. 2. The sales price is LESS than the sticker price but GREATER than the blue book price. 3. The sales price EQUALS the blue book price. 4. The sales price cannot be less than blue book.

More Related