Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

Similar documents
Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Conditional Statements

Java I/O and Control Structures Algorithms in everyday life

Java I/O and Control Structures

Algorithms and Conditionals

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Data Structures and Algorithms I

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Data Structures and Algorithms I

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Selection and Repetition Revisited

CSC 1051 Data Structures and Algorithms I

Selection and Repetition

Selection and Repetition Revisited

Basics of Java Programming variables, assignment, and input

Selection Statements and operators

Selection and Repetition

Lab 8: IF statement. Conditionals and Loops. Copyright 2012 Pearson Education, Inc.

Chapter 3. Selections

Selection Statements and operators

2: Basics of Java Programming

Lecture 3: Variables and assignment

Conditionals and Loops

Iterators and File Input

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Introduction to Arrays

Conditional Programming

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

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

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

CMPT 125: Lecture 4 Conditionals and Loops

Arrays, Part 3: Multidimensional arrays

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

File I/O and Exceptions

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Using Classes and Objects

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Recap: Assignment as an Operator CS 112 Introduction to Programming

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

CS 112 Introduction to Programming

Operators in java Operator operands.

Control Structures: if and while A C S L E C T U R E 4

Java Flow of Control

Name: Checked: Preparation: Response time experiment accessing the system clock

Introduction to Computer Science Unit 2. Exercises

Oct Decision Structures cont d

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

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

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

Lesson 7 Part 2 Flags

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

More Programming Constructs -- Introduction

Java Coding 3. Over & over again!

Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

COMP 202 Java in one week

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

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

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

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

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

Data Representation Classes, and the Java API

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

download instant at

Name: Checked: Preparation: Response time experiment accessing the system clock

COSC The if Statement. Yves Lespérance. Lecture Notes Week 5 Control Structures

Programming with Java

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

Chapter 4: Conditionals and Loops

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

In this chapter, you will:

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Chapter. Let's explore some other fundamental programming concepts

Data Representation and Applets

Topics. Chapter 5. Equality Operators

Fundamentals of Programming Data Types & Methods

CSC141, Computer Science I, Instructor: Dr. Zhen Jiang, Test 2

Transcription:

Control flow, conditionals, boolean expressions, block statements, nested statements CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Previous Example Java Programè Algorithm variables: qp, credits, gpa Algorithm: è 1. Input qp 2. Input credits 3. Output values entered 4. gpa = qp / credits 5. Print gpa 6. Print goodbye message //******************************************************** // GPA.java Author: Joyce/Papalaskari // Demonstrates the use of Scanner input and simple compu //******************************************************** import java.util.scanner; public class GPA public static void main (String[] args) //----------------------------------------------------- // Inputs the quality points and credits and calculate //----------------------------------------------------- double qp, credits, gpa; Scanner scan = new Scanner(System.in); // get input System.out.print ("Enter Quality Points > "); qp = scan.nextint(); System.out.print ("Enter Credits > "); credits = scan.nextint(); // output values entered System.out.println ("\nquality Points: " + qp); System.out.println ("Credits: " + credits); // calculate & output GPA System.out.println ("\n\tgpa: " + gpa); Some slides in this presentation are adapted from the slides accompanying: Java Software Solutions by Lewis & Loftus Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne What if credits is 0?? // print goodbye message System.out.println ("Thanks for using my program."); variables: qp, credits, gpa Algorithm: 1. Input qp 2. Input credits 3. Output values entered Improved algorithm variables: qp, credits, gpa Algorithm: 1. Input qp 2. Input credits 3. Output values entered //***************************************************** import java.util.scanner; Updated program public class GPA_Updated public static void main (String[] args) //-------------------------------------------------- // Reads the quality points and credits and calcula //-------------------------------------------------- double qp, credits, gpa; Scanner scan = new Scanner(System.in); 4. if credits equals 0 Print No gpa yet gpa = qp / credits Print gpa 5. Print goodbye message Java code if (credits == 0) System.out.println ("No GPA yet"); System.out.println ("GPA: " + gpa); 4. if credits equals 0 Print No gpa yet gpa = qp / credits Print gpa 5. Print goodbye message // get input System.out.print ("Enter Quality Points > "); qp = scan.nextint(); System.out.print ("Enter Credits > "); credits = scan.nextint(); // output values entered System.out.println ("\nquality Points: " + qp); System.out.println ("Credits: " + credits) // calculate and output GPA, if possible if (credits == 0) System.out.println ("No GPA yet"); System.out.println ("GPA: " + gpa); // Print goodbye message System.out.println ("Thanks for using my program. Dr Papalaskari 1

Control flow Sequence of statements that are actually executed in a program Conditional and Repetition statements: enable us to alter control flow Control flow Sequence of statements that are actually executed in a program Example: Example. input qp. statement input. credits 2. condition 1. input qp. credits is zero? statement 2 statement 2 statement input. credits 2. print. no GPA. yet statement 3 statement 4 condition 2 statement 4 statement gpa. = qp / credits 3. statement. print gpa 4. statement gpa. = qp / credits 3. statement. print gpa 4. statement 3 This slide dapted from Wayne&Sedgewick Princeton course: http://www.cs.princeton.edu/courses/archive/spring13/cos126/lectures.php statement print. goodbye 4. message statement print. goodbye 4. message Java Conditional statements alter the linear flow of control. They use boolean expressions to determine what to do next. Example: if (credits == 0) if more than one statement, enclose in braces System.out.println ("No GPA yet"); A boolean expression if, do this if, do these System.out.println ("GPA: " + gpa); Java relational operators relational operators can be used with numeric types and produce boolean results: == equal to!= not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=) Dr Papalaskari 2

Conditional statements if ( condition ) statement; // no clause condition evaluated if ( condition ) statement1; statement2; condition evaluated Example: How do we fix output to use singular/plural as appropriate? For example: Enter the total amount to be given as change: 18 That amount can be given as: 0 quarters get rid of this! 1 dimes 1 nickels 3 pennies statement statement2 Example: Create an application called Vacation that prompts for and inputs an integer representing someone s age and then suggests an appropriate vacation destination. One of two destinations should be suggested depending on whether person is over 30. input age age > 30? sample output How old is the traveler?: 15 Suggestion: Grand Canyon. Nested conditionals ; if (condition 1) statement 2; statement 2 if (condition 2) condition 1 condition 2 statement 4 print Florida statement 4; print Grand Canyon statement 3; statement 3 statement 5; print goodbye statement 5 This slide dapted from Wayne&Sedgewick Princeton course: http://www.cs.princeton.edu/courses/archive/spring13/cos126/lectures.php Dr Papalaskari 3

Another example: Create an application called Vacation that prompts for and inputs an integer representing someone s age and then suggests an appropriate vacation destination. One of three destinations should be suggested depending on whether the answer is less than 20, between 20 and 50, or over 50. sample output How old is the traveler?: 59 Suggestion: Florida. Java Logical Operators Used with boolean operands to express more complex boolean conditions a!a! && The logical NOT operation is also called logical negation or logical complement The logical AND operation is also called conjunction. Expression is when both operands are. The logical OR operation is also called disjunction. Expression is one or both operands are a b a && b a b Vacation example revisited: Create an application called Vacation that prompts for and inputs an integer representing someone s age and then suggests an appropriate vacation destination. One of three destinations should be suggested depending on whether the answer is less than 20, between 20 and 50, or over 50. sample output How old is the traveler?: 59 Suggestion: Florida. Boolean Expressions The reserved words and are the only valid values for a boolean type Example: boolean variables: boolean aboveagelimit = ; boolean useplural = hours > 1; boolean expression using a relational operator Dr Papalaskari 4

Logical Operators Another Example total 103 More Examples if (total < MAX + 5 && (!found)) System.out.println ("Processing "); MAX 100 found if (found!done) System.out.println("Ok"); What gets printed? found done All logical operators have lower precedence than the relational operators The! operator has higher precedence than && and if (total!= stock + warehouse) inventoryerror = ; What changes? total 20 stock 7 warehouse 12 inventoryerror Boolean Expressions using truth tables let s try this one: Boolean Expressions using truth tables another example: found done!done found!done total > MAX found!found total > MAX &&!found Dr Papalaskari 5

How much of a boolean expression do we need to evaluate before determining its value? *** Short-Circuited Operators The processing of && and is short-circuited in cases where the left operand is sufficient to determine the result (the right operand is not evaluated at all) This can be both useful and dangerous! if (count!= 0 && total/count > MAX) System.out.println ("Testing."); Indentation Revisited Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) System.out.println ("Error!!"); errorcount = errorcount + 1; Despite what is implied by the indentation, the increment will occur whether the condition is or not Dr Papalaskari 6