Control structure: Selections Computer and Programming Department of Computer Engineering Kasetsart University Cliparts are taken from

Slides:



Advertisements
Similar presentations
Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
Advertisements

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
If Statements & Relational Operators Programming.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 CS 105 Lecture 4 Selection Statements Wed, Jan 26, 2011, 6:05 pm.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
ECIV 301 Programming & Graphics Numerical Methods for Engineers Lecture 3 Programming and Software.
C++ for Engineers and Scientists Third Edition
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
1 Conditional statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Flow of Control Part 1: Selection
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
CPS120: Introduction to Computer Science Decision Making in Programs.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Introduction to branching.
1 Interactive Applications (CLI) and Math Interactive Applications Command Line Interfaces The Math Class Flow of Control / Conditional Statements The.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Branching statements.
Control structure: Selections
Program design Program Design Process has 2 phases:
Chapter 4: Control Structures I (Selection)
Chapter 3 Control Statements
REPETITION CONTROL STRUCTURE
Repetition (While-Loop) version]
Chapter 4: Making Decisions.
Algorithms and Flowcharts
Operator Precedence Operators Precedence Parentheses () unary
The Selection Structure
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 4: Making Decisions.
Programming Fundamentals
User-Defined Functions
SELECTION STATEMENTS (1)
CS1100 Computational Engineering
Structured Program
Programming Funamental slides
Selection Statements.
Summary Two basic concepts: variables and assignments Basic types:
Computer Science Core Concepts
Chapter 4: Control Structures I (Selection)
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
EECE.2160 ECE Application Programming
CSC 1051 – Data Structures and Algorithms I
Conditionals and Loops
Control Structures.
Presentation transcript:

Control structure: Selections Computer and Programming Department of Computer Engineering Kasetsart University Cliparts are taken from Please comment or report errors to

2 Outline Boolean Data Type and Expressions Fundamental Control Structures Flowcharts: Graphical Representation of Controls Basic Selections: if statements Basic Selections: if-else statements Programming Examples

3 bool isOdd; bool isMammal = true; bool isVaranus = false; const bool AllHumansAreMortal = true; Type bool in C# Has two possible values: true, false Declaration Examples of bool variables: Boolean Data Type: bool // see how similarly numeric variables are declared int i = 10; const double PlanckConstant = e-34;

4 Evaluated to a bool value (either true or false) Have two kinds of operators: relational and logical operators Boolean Expressions Relational Operators == (equal) !=(not equal) >(greater than) <(less than) >=(greater than or equal) <=(less than or equal) Relational Operators == (equal) !=(not equal) >(greater than) <(less than) >=(greater than or equal) <=(less than or equal) Logical Operators &&(AND) ||(OR) !(NOT) Logical Operators &&(AND) ||(OR) !(NOT)

5 Boolean Expressions: Examples int i = 10, j = 15; bool b, isEven; b = i = 5); Console.WriteLine((i%2)!=0); Console.WriteLine(!((i%2)==0)); Console.WriteLine(i+j >= 5 && i+j <= 10); Console.WriteLine(i < 20 || isEven); False True output

6 C# Operator Precedence From the highest precedence to the lowest down the table. Operators on the same row have the same precedence.

7 Operator Precedence: Examples int i = 10, j = 15; bool passed; passed = i+j*5-2 =20; The result is the value assigned to the variable passed

8 Outline Boolean Data Type and Expressions Fundamental Control Structures Flowcharts: Graphical Representation of Controls Basic Selections: if statements Basic Selections: if-else statements Programming Examples

9 Fundamental Control Structures Sequence Subroutine Selection (or Branching) Repetition (or Iteration or Loop) You have already learned and used these two control structures. You have already learned and used these two control structures.

10 Fundamental Control Structures SequenceSelection Repetition Subroutine

11 Outline Boolean Data Type and Expressions Fundamental Control Structures Flowcharts: Graphical Representation of Controls Basic Selections: if statements Basic Selections: if-else statements Programming Examples

12 Flowcharts: Graphical Representation of Controls Basic flowchart symbols: Terminator Process Input/outputCondition Connector Flow line

13 start nOdd = 0 nEven = 0 End of input ? read k false k%2 == 0 nEven = nEven+1nOdd = nOdd+1 falsetrue write nOdd, nEven end Example: Can you find out what algorithm this flowchart represents?

14 Outline Boolean Data Type and Expressions Fundamental Control Structures Flowcharts: Graphical Representation of Controls Basic Selections: if statements Basic Selections: if-else statements Programming Examples

15 Basic Selection: if statement Condition must be a boolean expression condition False True stateme nt C# SyntaxSemantics if (condition) statement; if (condition) statement;

16 F T b > max max = a max = b return max Example: Find the larger of two integers static int MaxOfTwo(int a, int b) { int max = a; if (b > max) max = b; return max; } C# Code Flow of execution The method MaxOfTwo() receives two int parameters a and b. returns the larger of them. The method MaxOfTwo() receives two int parameters a and b. returns the larger of them.

17 A Block of Statements A block is one or more C# statements that are enclosed within a pair of braces {}. A block is equivalent to a single C# statement, so it can be placed wherever a C# statement can be. { x = 20; y = x+5; Console.WriteLine(y); } if (k > 5) { x = 20; y = x+5; Console.WriteLine(y); } A block A block can be placed within an if statement. because a block is equivalent to a single statement because a block is equivalent to a single statement

18 Example if (k > 5) { x = 20; y = x+5; Console.WriteLine(y); } z = x*y; C# Code Flow of execution F T k > 5 x = 20 y = x+5 z = x*y write y

19 Task: The largest of three integers Read three integers Find out which of the three is the largest. If there are more than one largest numbers, the earlier one wins. Sample Run Enter 1st integer: 20 Enter 2nd integer: 30 Enter 3rd integer: 30 The second is the largest.

20 The largest of three integers – Topmost Level static void Main() { int a = ReadInt("Enter 1st integer: "); int b = ReadInt("Enter 2nd integer: "); int c = ReadInt("Enter 3rd integer: "); Console.WriteLine("The {0} is the largest.", WhichIsLargest(a, b, c)); } static int ReadInt(string prompt) { Console.Write(prompt); return int.Parse(Console.ReadLine()); } To be implemented next

21 The Method WhichIsLargest() - Steps  Let i1, i2, and i3 be the three integers and max be the largest so far. 1.Let max be i1, so the largest so far is the first. 2.If i2 > max, then let max be i2 so the largest so far is the second. 3.If i3 > max, then the largest is the third.  Let i1, i2, and i3 be the three integers and max be the largest so far. 1.Let max be i1, so the largest so far is the first. 2.If i2 > max, then let max be i2 so the largest so far is the second. 3.If i3 > max, then the largest is the third. Algorithm

22 The Method WhichIsLargest() – C# code static string WhichIsLargest( int i1, int i2, int i3) { int max = i1; string which = "first"; if (i2 > max) { max = i2; which = "second"; } if (i3 > max) which = "third"; return which; }

23 Outline Boolean Data Type and Expressions Fundamental Control Structures Flowcharts: Graphical Representation of Controls Basic Selections: if statements Basic Selections: if-else statements Programming Examples

24 Basic Selection: if –else statement if (condition) statement 1 ; else statement 2 ; if (condition) statement 1 ; else statement 2 ; C# SyntaxSemantics statement 1 and statement 2 can be a block

25 F T b > max max = a max = b return max Example: The method MaxOfTwo() revisit ed static int MaxOfTwo(int a, int b) { int max = a; if (b > max) max = b; return max; } C# Code Flow of execution This version: uses if (without else) statement performs one comparison executes one or two assignments

26 Example: another way to write MaxOfTwo() static int MaxOfTwo(int a, int b) { int max; if (a > b) max = a; else max = b; return max; } C# CodeFlow of execution This version: uses if-else statement performs one comparison always executes only one assignment

27 Many styles of placing braces if (condition) { Statement_1; Statement_2; } else { Statement_3; Statement_4; } Statement_5; if (condition) { Statement_1; Statement_2; } else { Statement_3; Statement_4; } Statement_5; if (condition) { Statement_1; Statement_2; } else { Statement_3; Statement_4; } Statement_5; To the compiler all are the same, so choose any one you like best. Use the same style in the same program. To the compiler all are the same, so choose any one you like best. Use the same style in the same program.

28 The Method WhichIsLargest() revisited static string WhichIsLargest( int i1, int i2, int i3) { int max = i1; string which = "first"; if (i2 > max) { max = i2; which = "second"; } if (i3 > max) which = "third"; return which; } This version: uses if (without else) statement at most 5 assignments are executed

29 Example: another way to write WhichIsLargest () // find out which of the three ints is the largest static string WhichIsLargest(int i1, int i2, int i3) { int max; string which; if (i1 >= i2) { max = i1; which = "first"; } else { max = i2; which = "second"; } if (i3 > max) which = "third"; return which; } This version: uses if-else statement at most 3 assignments are executed

30 Outline Boolean Data Type and Expressions Fundamental Control Structures Flowcharts: Graphical Representation of Controls Basic Selections: if statements Basic Selections: if-else statements Programming Examples

31 Task: Solving quadratic equations  Given the three coefficients a, b, and c of a quadratic equation ax 2 + bx + c = 0 where a  0, find the roots of the equation. A root is a value of x that satisfies the equation

32 Solving quadratic equations - I/O Specification Sample Run Enter 1st coefficient: 2 Enter 2nd coefficient: -1 Enter 3rd coefficient: -1 Two real roots: 1 and -0.5 Sample Run Enter 1st coefficient: 1 Enter 2nd coefficient: 8 Enter 3rd coefficient: 16 Only one real root: -4 Enter 1st coefficient: 5 Enter 2nd coefficient: 2 Enter 3rd coefficient: 1 Two complex roots: i and i Sample Run Enter 1st coefficient: 0 1st coefficient can’t be zero. Program exits.

33 Solving quadratic equations - Ideas  The roots of a quadratic equation ax 2 + bx + c = 0 can be calculated by the formula:  The term b 2 − 4ac in the formula is called the discriminant (D) of the equation because it can discriminate between the possible types of roots.

34 Solving quadratic equations - Ideas The discriminant D = b 2 − 4ac of the equation determines the type of roots as follows:  If D > 0, there are two real roots: and  If D = 0, there is only one real root:  If D < 0, there are two complex roots: and Now we have got enough information to write the program.

35 Solving a quadratic equation – Topmost Steps  The Main() method: 1.reads the three coefficients a, b, and c 2.uses a, b, and c to solve and output the roots. public static void Main() { double a, b, c; ReadCoefficients(out a, out b, out c); SolveAndOutput(a, b, c); Console.ReadKey(true); } The supreme commander usually doesn’t do things himself. He only gives orders. The supreme commander usually doesn’t do things himself. He only gives orders.

36 Solving a quadratic equation – Call Tree Main ReadCoefficients SolveAndOutput Done!

37 Solving a quadratic equation – Read the inputs  The method ReadCoefficients() 1.reads the coefficients a, b, and c by calling ReadDouble() for each. 2.If a is zero, it prints an error message and then terminates the program immediately. What command could we use to terminate a running program immediately? For Console applications, we could use the System method Environment.Exit() with an exit code.

38 A System method: Environment.Exit() Namespace: System Class: Environment Method: public static void Exit(int exitCode) Description: Exit() terminates this running program and returns an exit code of type int to the operating system. Parameter:  exitCode is an integer of type int to return to the operating system.  Traditionally, zero is used to indicate a successful exit and a nonzero number is used to indicate an error.  You can define your own error codes by various nonzero numbers. Namespace: System Class: Environment Method: public static void Exit(int exitCode) Description: Exit() terminates this running program and returns an exit code of type int to the operating system. Parameter:  exitCode is an integer of type int to return to the operating system.  Traditionally, zero is used to indicate a successful exit and a nonzero number is used to indicate an error.  You can define your own error codes by various nonzero numbers.

39 Solving a quadratic equation – Read the inputs  The method ReadCoefficients() 1.reads the coefficients a, b, and c by calling ReadDouble(). 2.If a is zero, it prints an error message and then terminates the program immediately. static void ReadCoefficients(out double a, out double b, out double c) { a = ReadDouble("Enter 1st coefficient: "); if (a == 0) { Console.WriteLine("1st coefficient can't be zero. Program exits."); Console.ReadKey(true); Environment.Exit(1); // nonzero exit code to indicate error } b = ReadDouble("Enter 2nd coefficient: "); c = ReadDouble("Enter 3rd coefficient: "); }

40 Solving a quadratic equation – Call Tree Main ReadCoefficients SolveAndOutput Done! ReadDouble Done!

41 Solving a quadratic equation - Program  Our good old method ReadDouble() static double ReadDouble(string prompt) { Console.Write(prompt); return double.Parse(Console.ReadLine()); }

42 Solving a quadratic equation – Call Tree Main ReadCoefficients SolveAndOutput Done! ReadDouble Done!

43 Solving a quadratic equation - Program  The method SolveAndOutput() 1.computes the discriminant. 2.uses the discriminant to select either the method to find real roots or the one to find complex roots. static void SolveAndOutput(double a, double b, double c) { double discriminant = b*b - 4*a*c; if (discriminant >= 0) // has real roots ComputeAndPrintRealRoots(a, b, c); else// has complex roots ComputeAndPrintComplexRoots(a, b, c); }

44 Solving a quadratic equation – Call Tree Main ReadCoefficients SolveAndOutput Done! ReadDouble Done! ComputeAndPrintRealRoots ComputeAndPrintComplexRoots Done!

45 Solving quadratic equations - Ideas The discriminant D = b 2 − 4ac of the equation determines the type of roots as follows:  If D > 0, there are two real roots: and  If D = 0, there is only one real root:  If D < 0, there are two complex roots: and Before we go further, let’s recall the formula

46 Solving a quadratic equation - Program  The method ComputeAndPrintRealRoots() 1.uses the discriminant to select either the formula for one real root or two real roots. 2.computes and outputs the root(s). static void ComputeAndPrintRealRoots(double a, double b, double c) { double r1, r2; double discrim = b*b - 4*a*c; if (discrim == 0) { r1 = -b / (2*a); Console.WriteLine("Only one real root: {0}", r1); } else { r1 = (-b + Math.Sqrt(discrim)) / (2*a); r2 = (-b - Math.Sqrt(discrim)) / (2*a); Console.WriteLine("Two real roots: {0} and {1}", r1, r2) } } static void ComputeAndPrintRealRoots(double a, double b, double c) { double r1, r2; double discrim = b*b - 4*a*c; if (discrim == 0) { r1 = -b / (2*a); Console.WriteLine("Only one real root: {0}", r1); } else { r1 = (-b + Math.Sqrt(discrim)) / (2*a); r2 = (-b - Math.Sqrt(discrim)) / (2*a); Console.WriteLine("Two real roots: {0} and {1}", r1, r2) } }

47 Solving a quadratic equation – Call Tree Main ReadCoefficients SolveAndOutput Done! ReadDouble Done! ComputeAndPrintRealRoots ComputeAndPrintComplexRoots Done!

48 Solving a quadratic equation - Program  The method ComputeAndPrintComplexRoots() static void ComputeAndPrintComplexRoots(double a, double b, double c) { } static void ComputeAndPrintComplexRoots(double a, double b, double c) { } Now it’s time for all good students to write it yourself! Now it’s time for all good students to write it yourself!

49 Conclusion Control structures allow you to control the flow of your program’s execution There are four fundamental control structures: Sequence, Subroutine, Selection, and Repetition. The previous chapters have already used the first two. The control structure Selection is used to select one of many possible paths of execution in a program depending on the given conditions. Each condition is expressed in C# by a bool expression. In C#, Selection can be expressed by the if statements or if-else statements. The if statement decides whether or not a statement (or a block) is to be executed. The if-else statement selects between two possible statements (or blocks) to be executed.

50 References Data type bool and bool expressions: C# operators (from the highest precedence to the lowest) if and if-else statements: A block of statements: Environment.Exit() method:

51 Syntax Summary I if (condition) statement; if (condition) statement; if (condition) statement 1 ; else statement 2 ; if (condition) statement 1 ; else statement 2 ; { statement 1 ; statement 2 ;... statement k ; } { statement 1 ; statement 2 ;... statement k ; } if statement if-else statement A Block Condition must be a bool expression. A block can be anywhere a single statement can be. Environment.Exit(exitCode); terminates the program immediately and returns exitCode to the OS. A System Method

52 Syntax Summary II: C# Operator Precedence From the highest precedence to the lowest down the table. Operators on the same row have the same precedence.