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

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

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

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

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

Chapter 3. Selections

Selection Statements and operators

Selection and Repetition

Selection Statements and operators

Conditionals and Loops

2: Basics of Java Programming

Lecture 3: Variables and assignment

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

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:

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

Chapter 3: Program Statements

File I/O and Exceptions

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

Java Flow of Control

Using Classes and Objects

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

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 February 24, Name: KEY 1

Recap: Assignment as an Operator CS 112 Introduction to Programming

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

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

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

More Programming Constructs -- Introduction

Introduction to Computer Science Unit 2. Exercises

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

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

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

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

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

Lesson 7 Part 2 Flags

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

BRANCHING if-else statements

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

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

Java Coding 3. Over & over again!

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

COMP 202 Java in one week

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

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

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

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

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

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

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

download instant at

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

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

Programming with Java

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

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

Transcription:

, 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 è 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."); 4. if credits equals 0 Print No gpa yet gpa = qp / credits Print gpa Improved algorithm 4. if credits equals 0 Print No gpa yet gpa = qp / credits Print gpa Java code 5. Print goodbye message 5. Print goodbye message if (credits == 0) System.out.println ("No GPA yet"); System.out.println ("GPA: " + gpa); Dr Papalaskari 1

//***************************************************** 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 // 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) 5. Print goodbye message // 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. Conditional and Repetition statements: enable us to alter control flow Example: condition 1. input qp. statement input. credits 2. condition 2 statement gpa. = qp / credits 3. statement. print gpa 4. This slide dapted from Wayne&Sedgewick Princeton course: http://www.cs.princeton.edu/courses/archive/spring13/cos126/lectures.php statement print. goodbye 4. message Dr Papalaskari 2

Example:. input qp. statement input. credits 2. statement gpa. = qp / credits 3. statement. print gpa 4. statement print. goodbye 4. message Example print. no GPA. yet. input qp. statement input. credits 2. credits is zero? statement gpa. = qp / credits 3. statement. print gpa 4. 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: Conditional statements if ( condition ) statement; // no clause if ( condition ) statement1; statement2; == equal to!= not equal to < less than > greater than <= less than or equal to >= greater than or equal to condition evaluated condition evaluated Note the difference between the equality operator (==) and the assignment operator (=) statement statement2 Dr Papalaskari 3

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 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. print Florida print Grand Canyon print goodbye Nested conditionals ; if (condition 1) condition 1 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. ; if (condition 2) condition 2 sample output How old is the traveler?: 59 Suggestion: Florida. ; ; statement 5; statement 5 This slide dapted from Wayne&Sedgewick Princeton course: http://www.cs.princeton.edu/courses/archive/spring13/cos126/lectures.php Dr Papalaskari 4

Java Logical Operators logical operators can be used with boolean operands to express more complex boolean conditions:! Logical NOT && Logical AND Logical OR 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 Logical Operators Another Example if (total < MAX + 5 && (!found)) System.out.println ("Processing "); All logical operators have lower precedence than the relational operators The! operator has higher precedence than && and total 103 MAX 100 found Dr Papalaskari 5

Logical NOT The logical NOT operation is also called logical negation or logical complement If some boolean condition a is, then!a is ; if a is, then!a is Logical expressions can be shown using a truth table: a!a Logical AND and Logical OR The logical AND expression a && b is if both a and b are, and otherwise The logical OR expression a b is if a or b or both are, and otherwise a b a && b a b Quick Check 1 Quick Check 2 What does this statement do? What does this statement do? total 20 if (found!done) System.out.println("Ok"); found done if (total!= stock + warehouse) inventoryerror = ; stock 7 warehouse 12 inventoryerror Dr Papalaskari 6

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 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 7