4 6_controlling_the_flow_of_execution
Jason Zhu edited this page 2021-02-23 13:57:37 +11:00

Module 6. Controlling the Flow of Execution

Branching with if Statements

Reference:

Keywords:

  • if/else condition, switch statement
  • Equality Comparison: ==, >=, <=, !=, etc.
  • AND &&, OR ||

Looping with for, foreach, do, and while

Reference:

keywords:

  • do-while
  • while
  • for
  • foreach for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface

foreach is most clear, concise, highly recommended. for statement is for low level control

Jumping with break and continue

Reference:

  • break (C# Reference)
    • The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.
  • continue (C# Reference)
    • The continue statement passes control to the next iteration of the enclosing while, do, for, or foreach statement in which it appears.
  • goto (C# Reference)
    • Very rare to use. Nobody use it.
    • The goto statement transfers the program control directly to a labeled statement. A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.

Switching with the switch Statement

Reference:

General syntax:

      switch (caseSwitch)
      {
          case 1:
              Console.WriteLine("Case 1");
              break;
          case 2:
              Console.WriteLine("Case 2");
              break;
          default:
              Console.WriteLine("Default case");
              break;
      }

Pattern Matching with switch:

Reference:

Starting with C# 7.0, because case statements need not be mutually exclusive, you can add a when clause to specify an additional condition that must be satisfied for the case statement to evaluate to true. The when clause can be any expression that returns a Boolean value. The case statement and the when clause

Challenge: Taking User Input from Console

Objective:

  • Program take grade from console asking grade in loop
  • Program stop taking grade after receiving "Q"
  • Program calculate statistics at the end

Thowing Exceptions

Reference:

How to throw exceptions:

            {
                throw new ArgumentException($"Invalid {nameof(grade)}");
            }

Catching Exceptions

Reference:

How to catch exceptions (for all standard or customized exceptions):

  • After defining the code to throw exceptions. Need create a try-catach logic to catch exceptions
  • All exception classes (e.g. ArgumentException, FormatException) inherit from Exception, so it can be used to catch all exceptions.
  • finally block will be executed after every exception block, good for I/O closing, etc.