1 / 90

Solving Problems that involve decisions

Solving Problems that involve decisions. Topics. Normal execution order. Conditional statements. Relational operators & Boolean expressions. Enumerations. Objectives. At the completion of this topic, students should be able to:. Describe the normal flow of control through a C# program

oded
Download Presentation

Solving Problems that involve decisions

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 decisions

  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.

  5. Methods that we have written so far begin with the first line in the method, and continue line by line until control reaches the end of the method.

  6. Example of Sequential Flow using System; class Program { static void Main() { const int MINS_PER_HOUR = 60, SPLITTER = 100, PERCENT_BETTER = 1.25;; intstartTime, endTime; intendTime; // Prompt for input and get start time Console.WriteLine("Enter in the start time for this trip in 24 hour clock time"); Console.Write("in the form hhmm: "); startTime = int.Parse(Console.ReadLine()); // Prompt for input and get end time Console.WriteLine("Enter in the end time for this trip in 24 hour clock time"); Console.Write("in the form hhmm: "); endTime = int.Parse(Console.ReadLine()); // calculate the start and end time with minutes as integers intstartMmm = startTime / SPLITTER * MINS_PER_HOUR + startTime % SPLITTER; intendMmm = endTime / SPLITTER * MINS_PER_HOUR + endTime % SPLITTER; …etc } // end of Main } Flow of cont rol

  7. There are many problems that cannot be solved using methods that execute 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.

  8. Examples

  9. A More Accurate GoodGuys Program GoodGuy's Delivery service operates a fleet of delivery vehicles that operate between Provo and Salt Lake City. With the I-15 construction work scheduled for Utah County, Goodguys wants you to create a program for them that will compute the new arrival times for deliveries. Once the work on the interstate begins, GoodGuys estimates that their delivery times will increase based on the following table: midnight to 6:00am no increase 6:01am to 9:30am 30% increase 9:31am to 3:00am 10% increase 3:01pm to 7:00pm 30% increase 7:01pm to 10:00pm 10% increase 10:01pm to midnight no increase

  10. 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;

  11. 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.

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

  13. 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

  14. 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

  15. GoodGuys If the delivery truck Then the delivery leaves between time increases by midnight and 6:00am 0% 6:01am and 9:30am 30% 9:31am and 3:00am 10% 3:01pm and 7:00pm 30% 7:01pm and 10:00pm 10% 10:01pm and midnight 0%

  16. 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.

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

  18. 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

  19. 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

  20. 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.

  21. 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 Use curly braces to clearly define what actions Are taken when the condition is true

  22. 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

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

  24. 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 Notice how this block of code is executed if the condition is true, but the block is skipped if the condition is false.

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

  26. 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.

  27. Warning: Don’t confuse = and == Note that the following expression will not compile in C#… if ( age = myNewAge) { . . . } This is an assignment, not a comparison

  28. 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

  29. 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

  30. 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

  31. 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

  32. 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 …”); } . . .

  33. 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

  34. 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.

  35. 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!

  36. 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

  37. 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

  38. 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();

  39. 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…!");

  40. 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.");

  41. 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.");

  42. 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.

  43. 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.");

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

  45. Will this code do what you expect? const intR_LIMIT = 40; const int O_LIMIT = 20; . . . if (regTime > R_LIMIT) if (overTime > O_LIMIT) Console.WriteLine(“Overtime hours exceed the limit.”); else Console.WriteLine(“no overtime worked.”); If an employee works more than 40 hours a week, then make sure that they don’t work more than 20 hours of overtime

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

  47. The code should be written this way. const intR_LIMIT = 40; Constint O_LIMIT = 20; . . . if (regTime > R_LIMIT) { if (overTime > O_LIMIT) Console.WriteLine(“Overtime hours exceed the limit.”); } else Console.WriteLine(“no overtime worked.”);

  48. 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

  49. Designing programs that use conditional statements

  50. 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.

More Related