Programming, Problem Solving, and Abstraction. Chapter Three. Selection

Similar documents
Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

Operators & Expressions

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Unit 3. Operators. School of Science and Technology INTRODUCTION

Lecture 10: Boolean Expressions

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

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

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

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

Introduction to Programming using C++

Programming Logic and Design Sixth Edition

Chapter 2, Part III Arithmetic Operators and Decision Making

ITT8060: Advanced Programming (in F#)

CT 229 Java Syntax Continued

Boolean Algebra Boolean Algebra

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Programming for Engineers Iteration

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Computer Science & Engineering 150A Problem Solving Using Computers

LECTURE 5 Control Structures Part 2

Flow Control. CSC215 Lecture

CS Programming I: Branches

Data Types and Variables in C language

ENGI Introduction to Computer Programming M A Y 2 8, R E Z A S H A H I D I

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Operators. Java operators are classified into three categories:

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Chapter 4 - Notes Control Structures I (Selection)

A Beginner s Guide to Programming Logic, Introductory. Chapter 6 Arrays

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

Lesson #4. Logical Operators and Selection Statements. 4. Logical Operators and Selection Statements - Copyright Denis Hamelin - Ryerson University

Lecture 3. More About C

TOP-DOWN PROCEDURAL PROGRAMMING

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

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

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Structured programming. Exercises 3

Introduction to C Programming

Numbers In, Numbers Out

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More Programming Constructs -- Introduction

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CHAPTER 5 FLOW OF CONTROL

Variables and literals

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 1 IDL Operators

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

Chapter 2: Using Data

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

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

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

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

Software Testing. 1. Testing is the process of demonstrating that errors are not present.

CSCI 1061U Programming Workshop 2. C++ Basics

ECE 122 Engineering Problem Solving with Java

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

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Difference Between Dates Case Study 2002 M. J. Clancy and M. C. Linn

5. Control Statements

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

Test 1. CSC 121 Lecture Lecturer: Howard Rosenthal. March 4, 2014

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lexical Considerations

Selection Statements. Pseudocode

UEE1302(1102) F10: Introduction to Computers and Programming

Arithmetic Operators. Portability: Printing Numbers

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Object-Oriented Programming

CONDITIONAL EXECUTION: PART 2

Chapter 4: Control Structures I (Selection)

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

H192 Midterm 1 Review. Tom Zajdel

Relational Expressions. Boolean Expressions. Boolean Expressions. ICOM 4036 Programming Languages. Boolean Expressions

At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details.

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

SFPL Reference Manual

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Operators and Expressions:

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

PROGRAMMING FUNDAMENTALS

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Flow Control. So Far: Writing simple statements that get executed one after another.

Transcription:

Programming, Problem Solving, and Abstraction Chapter Three Selection c The University of Melbourne, 2018 Lecture slides prepared by Alistair Moffat

Chapter 3 to watch for 3.5 The switch statement

Chapter 3 Logical and precedence again. Selection via the if statement, with or without else Selection via the switch statement (discouraged)

Relational operators test for equality and ordering. In C: <, <=, >, >=, ==, and!=. Note that the equality test uses == and not =. All of these operators yield int as the result type.

In C, that evaluate to true generate integer 1. Expressions that evaluate to false generate integer 0. Logical may appear anywhere: num neg+=(n<0) is valid. In general, where true/false values are required, any non-zero value is interpreted as being true; only zero is taken as false.

operators Logical operators combine int true/false values to obtain int true/false values: Operands Operation e1 e2 e1 && e2 e1 e2! e1 0 0 0 0 1 0 NZ 0 1 1 NZ 0 0 1 0 NZ NZ 1 1 0

3.1 Exercise 1 When is each of these true? 5<x 5<x && x<=10 5<x && x<=10 15<x && x<=20 month==4 month==6 month==9 month==11 year%4==0 && (year%100!=0 year%400==0)

and precedence The precedence rules specify default evaluation order. Operators Operation class Precedence ++, -- postinc, postdec Highest!, -, (type) not, negation, casting *, /, % multiplication +, - addition <, >, <=, >= comparison ==,!= equality && and or =, +=, *=, etc assignment Lowest

and precedence Unlike the other operators, the various assignment operators are evaluated from right to left. For example, the statements: x = y = 0; s = n += 1; have the operation ordering x = (y = 0); s = (n += 1); Including redundant parentheses costs nothing.

and precedence Within the overall ordering imposed by precedence, the C system may choose how to evaluate. In a*b+c*d either of a*b or c*d might get evaluated first. This means that you must be careful to avoid that have side effects, including the ++ and -- operators. Use such operators cautiously and sparingly.

and precedence Left-to-right evaluation order is guaranteed for the and (&&) and or ( ) operators. In addition, for and and or, evaluation is terminated as soon as the outcome is known. Expressions like x!=0 && y/x>5 are safe.

The if statement has two forms: and if ( guard ) statement1 else statement2 if ( guard ) statement1 Either or both of statement1 and statement2 can be empty statements, or compound statements bracketed by { and } pairs.

The flow of control through the two-branch if statement is: Non zero guard Zero statement1 statement2

Example 1: if (n < 0) num_neg += 1; Example 2: if (scanf("%d%d%d", &n, &m, &r)!= 3) { printf("scanf failed to read three items\n"); exit(exit_failure); }

The function exit can be used at any point to terminate program execution. Return of a non-zero exit value signals an abnormal termination. The constants EXIT SUCCESS and EXIT FAILURE are defined in the header file stdlib.h, and are accessed using #include <stdlib.h>

Example 3: if (year%4==0 && (year%100!=0 year%400==0)) { /* need to allow for leap years */ length_of_year = 366; length_of_feb = 29; } else { /* not a leap year */ length_of_year = 365; length_of_feb = 28; }

Example 4: if (month==2) { length_of_month = length_of_feb; } else if (month==4 month==6 month==9 month==11) { /* thirty days hath september, april, june, and november */ length_of_month = 30; } else { /* all the rest have 31, except february... */ length_of_month = 31; }

Exercise 3.4 Write a program that reads a date in dd/mm/yyyy format and prints, in the same format, the date that it will be tomorrow. Remember, start with a very simple program, and then expand it incrementally.

to watch for equalinif.c What is output by this program when 0 is entered? Why? Using = where == is intended is a very common mistake.

to watch for danglingelse.c What is the final value of variable z? Why? The compiler provides optional warning messages; ask for them with -Wall and read them all carefully.

to watch for threetest.c Is the final value of z going to be 9? Why not? This one may not result in a warning message being generated. A silent compiler does not guarantee that your program is correct. Programs should always be carefully tested.

The 2012/13 Australian tax rates stipulate that annual income between $18,200 and $37,000 is taxed at 19.0 cents in the dollar; income between $37,000 and $80,000 at 32.5 cents in the dollar; and income between $80,000 and $180,000 at 37.0 cents in the dollar. Any further income is taxed at 45.0 cents in the dollar. In addition, a Medicare levy of 1.5 cents in the dollar is applied to all income. For a given gross income, what net income is received? taxation.c

3.5 The switch statement switch ( integer expression ) { case ( integer1 ): statement1 break; case ( integer2 ): statement2 break;... case ( integern ): statementn break; default: statement }

3.5 The switch statement A sensible switch: switch1.c To manage the logic flow, each case should have a break.

3.5 The switch statement A dangerous switch: switch2.c Trace the final value for each input value of x. Was it easy?

Chapter 3 Logical and relational are integer valued. Be careful with precedence, be especially wary of side-effects. The if statement allows conditional execution based on an integer-valued guard. Switch statements should be avoided, they encourage poorly structured code. If for some reason you must use them, be disciplined, and use a break for every case.