CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

Slides:



Advertisements
Similar presentations
Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed.
Advertisements

1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Logical Operators and Conditional statements
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 3: Program Statements
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Chapter 3: Program Statements
Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.
Last time We covered: –primitive data types –declaration, initialization, assignment of variables –expressions and operator precedence –data conversions.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops.
1 Chapter 3 Selections. 2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 M.A. Papalaskari, Villanova University Conditional Statements Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University.
5-1 Chapter 5: Conditionals and Loops Topics: –Boolean expressions –Conditional statements –Increment and Decrement Operators (Chapter 2.4) –Repetition.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Control Flow. Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a float and.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 M.A. Papalaskari, Villanova University Algorithms Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Control statements Mostafa Abdallah
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
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.
Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Conditionals and Loops Now we will examine programming statements that allow us to: – make decisions – repeat processing steps in a loop Chapter 5 focuses.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 Conditionals and Loops
CSC 1051 – Data Structures and Algorithms I
Chapter 6 More Conditionals and Loops
Operator Precedence Operators Precedence Parentheses () unary
Boolean Expressions and If
Boolean Expressions & the ‘if’ Statement
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one after another Some programming statements.
Chapter 3: Program Statements
Outline Boolean Expressions The if Statement Comparing Data
Logic of an if statement
CSC 1051 – Data Structures and Algorithms I
Comparing Data & the ‘switch’ Statement
Outline Software Development Activities
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Conditionals and Loops
Boolean Expressions & the ‘if’ Statement
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
3.0 - Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Presentation transcript:

CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: CSC 1051 M.A. Papalaskari, Villanova University Algorithms and Conditionals

Algorithm Example Statement of GPA problem: Write a program that reads the credits and quality points earned and outputs the gpa. Algorithm: variables: qp, credits, gpa 1.Input qp 2.Input credits 3.gpa = qp / credits 4.Print gpa CSC 1051 M.A. Papalaskari, Villanova University

Java Program  //************************************************************* // GPA.java Author: Joyce/Papalaskari // // Demonstrates the use of Scanner input and simple computation. //************************************************************* import java.util.Scanner; public class GPA { public static void main (String[] args) // // Inputs the quality points and credits and calculates GPA. // { 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 information entered System.out.println ("\nQuality Points: " + qp); System.out.println ("Credits: " + credits); // calculate and output GPA gpa = qp / credits; System.out.println ("\n\tGPA: " + gpa); } Algorithm: variables: qp, credits, gpa 1.Input qp 2.Input credits 3.gpa = qp / credits 4.Print gpa CSC 1051 M.A. Papalaskari, Villanova University

Pseudocode: a way to describe what an algorithm does without writing a program. Algorithm: variables: qp, credits, gpa 1.Input qp 2.Input credits 3.gpa = qp / credits 4.Print gpa CSC 1051 M.A. Papalaskari, Villanova University

Writing an algorithm in pseudocode List the variables used. List the steps for solving the problem, in order. Try to be brief and unambiguous; use Java expressions only when it is simpler to specify a step in java than in English. CSC 1051 M.A. Papalaskari, Villanova University Algorithm: variables: qp, credits, gpa 1.Input qp 1.Input credits 1.gpa = qp / credits 4.Print gpa

Writing an algorithm in pseudocode List the variables used. List the steps for solving the problem, in order. Try to be brief and unambiguous; use Java expressions only when it is simpler to specify a step in java than in English. CSC 1051 M.A. Papalaskari, Villanova University Algorithm: variables: qp, credits, gpa (use floating point) 1.Input qp 1.Input credits 1.gpa = qp / credits (Note: use floating point division) 2.Print gpa When the type is not obvious you can add a note.

Another example (from Lab 2): CSC 1051 M.A. Papalaskari, Villanova University PP 2.8 Write an application that reads values representing a time duration in hours, minutes, and seconds and then prints the equivalent total number of seconds. (For example, 1 hour, 28 minutes, and 42 seconds is equivalent to 5322 seconds.)

Can we reverse this calculation? CSC 1051 M.A. Papalaskari, Villanova University PP 2.9 Create a version of the previous project that reverses the computation. That is, read a value representing a number of seconds, then print the equivalent amount of time as a combination of hours, minutes, and seconds. (For example, 9999 seconds is equivalent to 2 hours, 46 minutes, and 39 seconds.) The next 3 slides will help us visualize this problem.

Algorithm for PP 2.9 CSC 1051 M.A. Papalaskari, Villanova University

How many of each can you pack in the black box?

Topic Thread 2.1 Character Strings 2.2 Variables, Assignment 2.3 Data Types, in particular int, double 2.4 Expressions (simple) 2.5 Data Conversion 2.6 Interactive Programs 5.1 Boolean Expressions 5.2 The if Statement 5.5 The while Statement CSC 1051 M.A. Papalaskari, Villanova University

Order of statement execution Unless specified otherwise, the flow of control through a method is linear ie, statements are executed in the order they appear We can modify this using conditional and repetition statements CSC 1051 M.A. Papalaskari, Villanova University

Java Program  //************************************************************* // GPA.java Author: Joyce/Papalaskari // // Demonstrates the use of Scanner input and simple computation. //************************************************************* import java.util.Scanner; public class GPA { public static void main (String[] args) // // Inputs the quality points and credits and calculates GPA. // { 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 information entered System.out.println ("\nQuality Points: " + qp); System.out.println ("Credits: " + credits); // calculate and output GPA gpa = qp / credits; System.out.println ("\n\tGPA: " + gpa); } } Algorithm: variables: qp, credits, gpa 1.Input qp 2.Input credits 3.gpa = qp / credits 4.Print gpa CSC 1051 M.A. Papalaskari, Villanova University What if credits = 0 ???? Previous Example

Updated Algorithm Algorithm: variables: qp, credits, gpa 1.Input qp 2.Input credits 3.if credits = 0 Print “No gpa yet” else gpa = qp / credits Print gpa 4.Print goodbye message CSC 1051 M.A. Papalaskari, Villanova University

Solution 6 Algorithm: variables: qp, credits, gpa 1.Input qp 2.Input credits 3.if credits = 0 Print “No gpa yet” else gpa = qp / credits Print gpa 4.Print goodbye message if (credits == 0) System.out.println (“\n\tGPA: None"); else { gpa = qp / credits; System.out.println (“\n\tGPA: " + gpa); } CSC 1051 M.A. Papalaskari, Villanova University

//************************************************************* // GPA_updated.java Author: Joyce/Papalaskari // // Demonstrates the use of conditional statements. //************************************************************* import java.util.Scanner; public class GPA_updated { public static void main (String[] args) // // Reads the quality points and credits and calculates GPA. // { 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 information entered System.out.println ("\nQuality Points: " + qp); System.out.println ("Credits: " + credits); // calculate and output GPA, if possible if (credits == 0) System.out.println ("\n\tGPA: None"); else { gpa = qp / credits; System.out.println ("\n\tGPA: " + gpa); } Algorithm: variables: qp, credits, gpa 1.Input qp 2.Input credits 3.gpa = qp / credits 4.Print gpa CSC 1051 M.A. Papalaskari, Villanova University Updated program 

Conditional statements Conditional statements depart from linear flow of control: Example: if (credits == 0) System.out.println ("GPA: None"); CSC 1051 M.A. Papalaskari, Villanova University A boolean expression

Topic Thread 2.1 Character Strings 2.2 Variables, Assignment 2.3 Data Types, in particular int, double 2.4 Expressions (simple) 2.5 Data Conversion 2.6 Interactive Programs 5.1 Boolean Expressions 5.2 The if Statement 5.5 The while Statement CSC 1051 M.A. Papalaskari, Villanova University

5.1 Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return 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 ( = ) CSC 1051 M.A. Papalaskari, Villanova University

Boolean Expressions The reserved words true and false are the only valid values for a boolean type Example boolean declaration: boolean aboveAgeLimit = false; Another example: boolean usePlural = quarters > 1; A boolean expression using a relational operator CSC 1051 M.A. Papalaskari, Villanova University

Example An if statement with its boolean condition: if (miles > 1) System.out.print("s"); Another way, using a boolean variable: boolean usePlural = miles > 1; if (usePlural) System.out.print("s"); See also Age.javaAge.java CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Age.java Author: Lewis/Loftus // // Demonstrates the use of an if statement. //******************************************************************** import java.util.Scanner; public class Age { // // Reads the user's age and prints comments accordingly. // public static void main (String[] args) { final int MINOR = 21; Scanner scan = new Scanner (System.in); System.out.print ("Enter your age: "); int age = scan.nextInt(); continue

CSC 1051 M.A. Papalaskari, Villanova University continue System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy."); System.out.println ("Age is a state of mind."); }

CSC 1051 M.A. Papalaskari, Villanova University continue System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy."); System.out.println ("Age is a state of mind."); } Sample Run Enter your age: 47 You entered: 47 Age is a state of mind. Another Sample Run Enter your age: 12 You entered: 12 Youth is a wonderful thing. Enjoy. Age is a state of mind.

The if Statement Let's now look at the if statement in more detail The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped. CSC 1051 M.A. Papalaskari, Villanova University

Logic of an if statement condition evaluated statement true false CSC 1051 M.A. Papalaskari, Villanova University

Indentation The statement controlled by the if statement is indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand The compiler ignores indentation CSC 1051 M.A. Papalaskari, Villanova University

The if-else Statement An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both See Wages.java Wages.java CSC 1051 M.A. Papalaskari, Villanova University

Example: Calculating wages with overtime Variables: hours, pay Algorithm: CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Wages.java Author: Lewis/Loftus // // Demonstrates the use of an if-else statement. //******************************************************************** import java.text.NumberFormat; import java.util.Scanner; public class Wages { // // Reads the number of hours worked and calculates wages. // public static void main (String[] args) { final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours in a work week Scanner scan = new Scanner (System.in); double pay = 0.0; continue

CSC 1051 M.A. Papalaskari, Villanova University continue System.out.print ("Enter the number of hours worked: "); int hours = scan.nextInt(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println ("Gross earnings: " + fmt.format(pay)); }

CSC 1051 M.A. Papalaskari, Villanova University continue System.out.print ("Enter the number of hours worked: "); int hours = scan.nextInt(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println ("Gross earnings: " + fmt.format(pay)); } Sample Run Enter the number of hours worked: 46 Gross earnings: $404.25

Logic of an if-else statement condition evaluated statement1 true false statement2 CSC 1051 M.A. Papalaskari, Villanova University

Block Statements Several statements can be grouped together into a block statement delimited by braces A block statement can be used wherever a statement is called for in the Java syntax rules if (total > MAX) { System.out.println ("Error!!"); errorCount++; } CSC 1051 M.A. Papalaskari, Villanova University

Block Statements The if clause, or the else clause, or both, could govern block statements if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; } CSC 1051 M.A. Papalaskari, Villanova University

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 true or not CSC 1051 M.A. Papalaskari, Villanova University

Logical Operators Boolean expressions can also use the following logical operators: ! Logical NOT && Logical AND || Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) CSC 1051 M.A. Papalaskari, Villanova University

Logical NOT The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table: CSC 1051 M.A. Papalaskari, Villanova University a!a truefalse true

Logical AND and Logical OR The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a || b is true if a or b or both are true, and false otherwise CSC 1051 M.A. Papalaskari, Villanova University

Logical AND and Logical OR A truth table shows all possible true-false combinations of the terms Since && and || each have two operands, there are four possible combinations of conditions a and b CSC 1051 M.A. Papalaskari, Villanova University aba && ba || b true false true falsetruefalsetrue false

Logical Operators Expressions that use logical operators can form complex conditions 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 || CSC 1051 M.A. Papalaskari, Villanova University

Boolean Expressions Specific expressions can be evaluated using truth tables – let’s try this one: CSC 1051 M.A. Papalaskari, Villanova University total < MAXfound!foundtotal < MAX && !found false true false true

Quick Check CSC 1051 M.A. Papalaskari, Villanova University What do the following statements do? if (total != stock + warehouse) inventoryError = true; if (found || !done) System.out.println("Ok");

Boolean Expressions using truth tables – let’s try this one: CSC 1051 M.A. Papalaskari, Villanova University founddone!donefound || !done false true false true

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."); CSC 1051 M.A. Papalaskari, Villanova University

Nested if Statements The statement executed as a result of an if or else clause could be another if statement These are called nested if statements An else clause is matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs See MinOfThree.java CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // MinOfThree.java Author: Lewis/Loftus // // Demonstrates the use of nested if statements. //******************************************************************** import java.util.Scanner; public class MinOfThree { // // Reads three integers from the user and determines the smallest // value. // public static void main (String[] args) { int num1, num2, num3, min = 0; Scanner scan = new Scanner (System.in); System.out.println ("Enter three integers: "); num1 = scan.nextInt(); num2 = scan.nextInt(); num3 = scan.nextInt(); continue

CSC 1051 M.A. Papalaskari, Villanova University continue if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; System.out.println ("Minimum value: " + min); }

CSC 1051 M.A. Papalaskari, Villanova University continue if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; System.out.println ("Minimum value: " + min); } Sample Run Enter three integers: Minimum value: 69

Homework Read Sections 5.1, 5.2 –pages and (skip coin example in listings 5.3, 5.4) –Always do all self-review exercises when you review material Do Exercises EX 5.1 – 5.5 CSC 1051 M.A. Papalaskari, Villanova University