Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Similar documents
Decision Structures. Lesson 03 MIT 11053, Fundamentals of Programming

Chapter 3: Decision Structures

Chapter 3: Decision Structures

Chapter 3: Decision Structures

Decision Making in C

Lesson 04. Control Structures I : Decision Making. MIT 31043, VISUAL PROGRAMMING By: S. Sabraz Nawaz

Control Structures in Java if-else and switch

Following is the general form of a typical decision making structure found in most of the programming languages:

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Chapter 4: Making Decisions

Chapter 4: Making Decisions

Lecture 5 Tao Wang 1

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Topics. Chapter 5. Equality Operators

Software Design & Programming I

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

LECTURE 04 MAKING DECISIONS

C++ Programming: From Problem Analysis to Program Design, Third Edition

Selections. CSE 114, Computer Science 1 Stony Brook University

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Chapter 3 Selection Statements

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Logical Operators and switch

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Control Structure: Selection

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

In this lab, you will learn more about selection statements. You will get familiar to

1. Wap in JAVA to accept two values and calculate highest value and lowest value.

Introduction to Object-Oriented Programming

Building Java Programs

Lecture 5: Making Decisions

Building Java Programs

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

SELECTION. (Chapter 2)

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

Building Java Programs

Selection Statements. Pseudocode

BRANCHING if-else statements

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

5. Selection: If and Switch Controls

Handout 4 Conditionals. Boolean Expressions.

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Chapter 4: Conditionals and Recursion

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Lesson 7 Part 2 Flags

Topic 4 Expressions and variables

Decisions. Arizona State University 1

Accelerating Information Technology Innovation

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHAPTER 5 FLOW OF CONTROL

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

CIS 110: Introduction to Computer Programming

COMP Primitive and Class Types. Yi Hong May 14, 2015

Lecture 3 Tao Wang 1

Chapter Goals. 3.1 The if Statement. Contents 1/30/2013 DECISIONS

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Programming with Java

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

PROGRAMMING FUNDAMENTALS

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Conditional Programming

Language Reference Manual

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Course Outline. Introduction to java

Chapter 4 - Notes Control Structures I (Selection)

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Lesson 39: Conditionals #3 (W11D4)

Control Structures in Java if-else and switch

if Statement Numeric Rela5onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Fundamental of Programming (C)

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

if Statement Numeric Rela7onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Score score < score < score < 65 Score < 50

Algorithms and Conditionals

Chapter 4: Control Structures I

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Conditionals and Loops

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Practice with variables and types

printf( Please enter another number: ); scanf( %d, &num2);

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Chapter 3. Selections

Boolean Expressions (Conditions)

Transcription:

Decision Structures Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Chapter Topics o Relational Operators o The if Statement o The if-else Statement o Nested if statements o The if-else-if Statement o The switch Statement MIT 12043, By S. Sabraz Nawaz 3-2

Relational Operators Relational operators in Java are used to compare two variables. Java provides six relational operators: Equal == Greater than > Less than < Greater than or equal to >= Less than or equal to <= Unequal!= The result of any relational operator is true or false MIT 12043, By S. Sabraz Nawaz 3

Boolean Expressions int a = 3; b = 4; a == b will evaluate to false a!= b will evaluate to true a > b a < b will evaluate to false will evaluate to true a >= b will evaluate to false a <= b will evaluate to true MIT 12043, By S. Sabraz Nawaz 4

Sequence Structure MIT 12043, By S. Sabraz Nawaz 5

Decision Structure Programs often need more than one path of execution, however. Many algorithms require a program to execute some statements only under certain circumstances. This can be accomplished with a decision structure In a decision structure s simplest form, a specific action is taken only when a condition exists. If the condition does not exist, the action is not performed MIT 12043, By S. Sabraz Nawaz 6

Decision Structure Simple decision structure logic MIT 12043, By S. Sabraz Nawaz 7

Decision Structure Three-action decision structure logic MIT 12043, By S. Sabraz Nawaz 8

Selection Statements The control statement that allows alternative actions based upon conditions that are evaluated at run time are generally called selection statements One way to code a decision structure in Java is with the if statement MIT 12043, By S. Sabraz Nawaz 9

The if Statement The if statement is used to create a decision structure, which allows a program to have more than one path of execution. o The if statement causes one or more statements to execute only when a boolean expression is true. The if statement decides whether a section of executes or not. if (boolean expression is true) execute this statement; MIT 12043, By S. Sabraz Nawaz 3-10

The if Statement A block if statement may be modeled as: if (coldoutside) { wearcoat; wearhat; weargloves; } Note the use of curly braces to block several statements together. MIT 12043, By S. Sabraz Nawaz 3-11

if Statements and Boolean Expressions if (x > y) System.out.println("X is greater than Y"); if(x == y) System.out.println("X is equal to Y"); if(x!= y) { System.out.println("X is not equal to Y"); x = y; System.out.println("However, now it is."); } MIT 12043, By S. Sabraz Nawaz 3-12

Programming Style and if Statements An if statement can span more than one line; however, it is still one statement. if (average > 95) grade = A ; is functionally equivalent to if(average > 95) grade = A ; MIT 12043, By S. Sabraz Nawaz 3-13

Block if Statements Conditionally executed statements can be grouped into a block by using curly braces {} to enclose them. If curly braces are used to group conditionally executed statements, the if statement is ended by the closing curly brace. if (expression) { statement1; statement2; } Curly brace ends the statement. MIT 12043, By S. Sabraz Nawaz 3-14

Block if Statements Remember that when the curly braces are not used, then only the next statement after the if condition will be executed conditionally if (expression) statement1; statement2; statement3; Only this statement is conditionally executed. MIT 12043, By S. Sabraz Nawaz 3-15

Example 01 Write a Java program that takes a person s age as input and decides whether that person is eligible to vote If the person s age is above 18, he or she is eligible to vote The program should display a message whether he or she is eligible to vote MIT 12043, By S. Sabraz Nawaz 16

Example 01 MIT 12043, By S. Sabraz Nawaz 17

Example 02 Write a Java program that takes a person s age and his or her name as inputs and decides whether that person is eligible to vote If the person s age is above 18, he or she is eligible to vote The program should display a message with the Name of the person and his or eligibility to vote MIT 12043, By S. Sabraz Nawaz 18

Example 02 MIT 12043, By S. Sabraz Nawaz 19

if-else Statements The if-else statement adds the ability to conditionally execute code when the if condition is false. if (expression) statementorblockiftrue; else statementorblockiffalse; It works the same way as the if statement except that, when the condition is false, the statement within the else clause executes MIT 12043, By S. Sabraz Nawaz 3-20

if-else Statement Flowcharts No Wear shorts. Is it cold outside? Yes Wear a coat. MIT 12043, By S. Sabraz Nawaz 3-21

Example 03 Write a Java program that takes a person s age and his or her name as inputs and decides whether that person is eligible to vote or not If the person s age is above 18, he or she is eligible to vote The program should display a message with the Name of the person and his or eligibility to vote MIT 12043, By S. Sabraz Nawaz 22

Example 03 MIT 12043, By S. Sabraz Nawaz 23

Exercise A company s payment structure to its employees is as follows o o o If the Basic salary exceeds 30,000/=, the Dearness Allowance 40% the BS, otherwise 50% of the BS If the BS exceeds 25,000/=, the House Rent Allowance is 20% of the BS, otherwise 3,000 of the BS Income Tax is calculated at the rate of 12% if the Total Salary exceeds 50,000/= Write a Java program that takes BS as input, calculate DA, HRA, IT, Total Salary, Net Salary, and display them all on screen MIT 12043, By S. Sabraz Nawaz 24

Solution MIT 12043, By S. Sabraz Nawaz 25

Solution MIT 12043, By S. Sabraz Nawaz 26

Nested if Statements To test more than one condition, an if statement can be nested inside another if statement If an if statement appears inside another if statement (single or block) it is called a nested if statement The nested if is executed only if the outer if statement results in a true condition MIT 12043, By S. Sabraz Nawaz 3-27

Alignment and Nested if Statements This if and else go together. This if and else go together. if (expression) { if (expression) { statement; } else { statement; } } else { statement; } MIT 12043, By S. Sabraz Nawaz 3-28

Example 04 For example, consider a banking program that determines whether a bank customer qualifies for a special, low interest rate on a loan To qualify, two conditions must exist: 1. The customer s salary must be at least Rs.30,000 2. The customer must have held his or her current job for at least 02 years MIT 12043, By S. Sabraz Nawaz 29

Example 04 MIT 12043, By S. Sabraz Nawaz 30

if-else-if Statements The if-else-if statement tests a series of conditions It is often simpler to test a series of conditions with the if-else-if statement than with a set of nested ifelse statements MIT 12043, By S. Sabraz Nawaz 31

if-else-if Syntax if (expression_1) { statement; statement; etc. } else if (expression_2) { } statement; statement; etc. Insert as many else if clauses as necessary If expression_1 is true these statements are executed, and the rest of the structure is ignored. Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. else { statement; statement; etc. } These statements are executed if none of the expressions above are true. MIT 12043, By S. Sabraz Nawaz 3-32

Example 05 Your lecturer has asked you to write a program that will allow a student to enter a test score and then display the grade for that score MIT 12043, By S. Sabraz Nawaz 33

34

Logical Operators MIT 12043, By S. Sabraz Nawaz 35

Logical Operators Logical operators connect two or more relational expressions into one or reverse the logic of an expression. Java provides two binary logical operators, && and used to combine two boolean expressions into a single expression It also provides the unary! Operator o reverses the truth of a boolean expression MIT 12043, By S. Sabraz Nawaz 36

Logical Operators Operator Meaning Effect && AND Connects two boolean expressions into one. Both expression must be true for the overall expression to be true OR Connects two boolean expressions into one. One or both expressions must be true for the overall expression to be true. It is only necessary for one to be true, and it does not matter which one.! NOT Reverses the truth of a boolean expression. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator returns true MIT 12043, By S. Sabraz Nawaz 37

Logical Operators Expression Meaning x > y && a < b Is x greater than y AND is a less than b? x == y x == z Is x equal to y OR is x equal to z?!(x > y) Is the expression x > y NOT true? MIT 12043, By S. Sabraz Nawaz 38

Truth table for the && operator Expression true && false false && true false && false true && true Value of the Expression false false false true MIT 12043, By S. Sabraz Nawaz 39

Truth table for the operator Expression true false false true false false true true Value of the Expression true true false true MIT 12043, By S. Sabraz Nawaz 40

Truth table for the! operator Expression!true!false Value of the Expression false true MIT 12043, By S. Sabraz Nawaz 41

Example 06 Improved Ex 05 42

43

The % Operator The above modulus operator returns the remainder Eg. o 3 % 2 1 (remainder is one) o 15 % 4 3 (remainder is three) Odd or Even number finder MIT 12043, By S. Sabraz Nawaz 44

Comparing String Objects You cannot use relational operators to compare String objects To compare, you should use the String class s equals method. The general form of the method is as follows: StringReference1.equals(StringReference2) o StringReference1 is a variable that references a String object, and StringReference2 is another variable that references a String object The method returns true if the two strings are equal, or false if they are not equal. Here is an example: if (name1.equals(name2)) The expression in the if statement will return true if they are the same, or false if they are not the same MIT 12043, By S. Sabraz Nawaz 45

Example 07 Note: the equal method is case sensitive; if you want to ignore the case case, use string. equalsignorecase() method MIT 12043, By S. Sabraz Nawaz 46

Classroom Exercise A car rental company has three types of cars; Premio, Alien, and Civic. The rental scheme is as follows. Type Premio Alien Civic Fixed Rent per day 1,500/- 2,000/- 2,500/- Rate per KM 20/- 30/- 40/- Free Allowance per day 80/- 60/- 50/- Write a Java program to input Vehicle Type, Number of Days Rented, and Kilometers run to calculate the Total Rent Payable and display on the screen. MIT 12043, By S. Sabraz Nawaz 47

The switch Statement For decisions involving many possible paths and values we use the switch statement The switch statement can have a number of possible execution paths At the end of each sequence we insert a break statement that means go to the end of the switch A switch works with the byte, short, char, and int primitive data types. It works with the String class as well. 48

The switch Statement switch case default break Reserved words 49 switch (variable) { case value1: statement; statement; break; } case value2: statement; statement; break;...... default: statement; break; Don t forget breaks!

switch - Example The same case can have two or more labels. For example: switch (num) { case 1: case 2:System.out.println ( Stand up and sing a song"); break; case 3:... } 50

Month Finder 51

Switch with Multiple case labels 52

Rules apply to a switch statement You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon The value for a case must be the same data type as the variable in the switch, and it must be a constant or a literal (character) When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached 53

Rules apply to a switch statement When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case 54

Looping in the next lectures MIT 12043, By S. Sabraz Nawaz 55