Professor: Dr. Baba Kofi Weusijana Pronounced Bah-bah Co-fee Way-ou-see-jah-nah Call him “Baba” or “Dr. Weusijana” https://cascadia.instructure.com/courses/1175442.

Slides:



Advertisements
Similar presentations
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Advertisements

Introduction to Computers and Programming Lecture 5 New York University.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
Lecture 9a Instructor: Craig Duckett CALL ME. Assignment 2 Revision DUE THIS Wednesday, August 5 th Assignment 3 DUE Monday, August 10 th Assignment 3.
The switch Statement, DecimalFormat, and Introduction to Looping
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
DAT602 Database Application Development Lecture 5 JAVA Review.
Instructor: Craig Duckett Assignment 1 Due Lecture 5 by MIDNIGHT – NEXT – NEXT Tuesday, October 13 th I will double dog try to.
Lecture 6 Instructor: Craig Duckett. Assignment 1, 2, and A1 Revision Assignment 1 I have finished correcting and have already returned the Assignment.
CPS120: Introduction to Computer Science Decision Making in Programs.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
ICT Introduction to Programming Chapter 4 – Control Structures I.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
BOOLEAN OPERATIONS AND CONDITIONALS CHAPTER 20 1.
Lecture 13 Instructor: Craig Duckett CALL ME. Assignment 3 DUE TONIGHT! Uploaded to StudentTracker by midnight If you are submitting as part of a team.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Lecture 14/15 Instructor: Craig Duckett. 2 ANNOUNCEMENTS For various reasons, the Cascadia Faculty web server occasionally goes down, making it impossible.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Lecture 11 Instructor: Craig Duckett Instance Variables.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana Pronounced Bah-bah Co-fee Way-ou-see-jah-nah Call him “Baba” or “Dr. Weusijana”
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
BIT 115: Introduction To Programming
BIT 115: Introduction To Programming
Java Language Basics.
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
REPETITION CONTROL STRUCTURE
BIT 115: Introduction To Programming
The switch Statement, and Introduction to Looping
Lecture 5: Some more Java!
BIT115: Introduction to Programming
EGR 2261 Unit 4 Control Structures I: Selection
Lecture 4: Program Control Flow
Primitive Data, Variables, Loops (Maybe)
Boolean Expressions and If
Variables ICS2O.
Java Language Basics.
Building Java Programs
Building Java Programs Chapter 2
BIT115: Introduction to Programming
Chapter 2 Programming Basics.
Chapter8: Statement-Level Control Structures April 9, 2019
Building Java Programs
February , 2009 CSE 113 B.
Introduction to Primitives
Introduction to Primitives
Unit 3: Variables in Java
Building Java Programs Chapter 2
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Chap 7. Advanced Control Statements in Java
Review of Previous Lesson
Conditionals and Loops
Presentation transcript:

Professor: Dr. Baba Kofi Weusijana Pronounced Bah-bah Co-fee Way-ou-see-jah-nah Call him “Baba” or “Dr. Weusijana”

Lecture 15 Log into Canvas Put your name sticker on your computer Announcements No Quiz Lecture Boolean expressions && Logical Operators Nested if & while statements The return statement & returned values For loops & do-while loops ICE15 George Boole

Announcements Office hour will be cut short today Lots of topics today Moved some Chapter 5 reading sections earlier Getting ready for Assignment 4

Boolean Expressions and Logical Operators A Boolean Expression is an expression that results in a Boolean value, that is, in a value that is either true or false. More complex Boolean expressions can be built out of simpler expressions, using the Boolean Logical Operators. George Boole

Primitive Data Types byte -128 to 127 short -32,768 to 32,767 int -2,147,483,648 to 2,147,483,647 (billion) long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (quintillion) float 127 digits after the decimal point double 1023 digits after the decimal point boolean true or false char Alphabetical characters stored as an ASCII numerical value (e.g., ‘A’ is 65, ‘B’ is 66) Primitive data types are built into the Java language and are not derived from classes. There are 8 Java primitive data types: George Boole

Testing Integer Queries BIT 115: Introduction To Programming6 The if and while statements always ask True or False questions. “Should I execute the code, true or false?” This approach works well for queries that return a boolean value, but how can we use queries that return integers? We do it with comparison operators

Two-Sided Queries BIT 115: Introduction To Programming7 The examples in the comparison operator table show an integer on only one side, but Java is more flexible than this: it can have a query on both sides of the operator, as in the following statements -- The following code tests whether the robot’s Avenue is five more than the Street. Locations where this tests true include (0,5) and (1,6). This test determines whether karel is on the diagonal line of intersections (0,0), (1,1), (2,2), and so on. It also includes intersections with negative numbers such as (-3, -3).

Boolean Expressions and Comparison Operators Using Comparison Operators, the test in if and while statements are Boolean expressions that give a true or false answer to a question. So far, our questions have been simple. As our programming skills grow, however, we will want to ask more complex questions, which will need more complex Boolean expressions to answer. OperatorOperation < Less than <= Less than or equal > Greater than >= Greater than or equal == Equal != Not equal Just like the mathematic operators ( + - / * ) can be combined to form more complex expressions like s = (( x + y) * (w – z)) / 2 so too can Boolean expressions be combined to create more complex and utility expressions using and (represented by &&) and or (represented by ||).

Logical Operators: && (“And”) and II (“Or”) In many programming languages — like Java, JavaScript, C++, and C# — the logical operators ‘and’ and ‘or’ are represented in the code by a double ampersand && and double pipe || “And” && Double Ampersand “Or” || Double Pipe There is also the ‘not’ operator represented by a single exclamation point ! which I’ll talk about in a moment. “Not” ! Single Exclamation Point Java also has a single & and single | characters, called bitwise operators, but for the purposes of this course we won’t be discussing them. These will come a bit later (pun intended) along your journey in learning programming languages.

Where is the pipe character | located on the keyboard? Before We Continue: What Pipe Character ? AN INTERESTING NOTE : The “pipe” character goes by several different names, depending on the particular group using it: besides being called the pipe, it can also be called the pipeline, vertical bar, Sheffer stroke, polon, verti-bar, vbar, stick, vertical line, vertical slash, bar, or glidus.

Logical Operators AND A && B are true only if both A and B are true && OR A || B are true if A is true or B is true or they're both true || NOT !A is the opposite of A. If A is true, then !A is false. If A is false, !A is true. ! && || TRUE TRUE TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE AND Operator OR Operator The double ampersand && and double pipe || are called “ short circuit ” logical operators

Logical Operator: Examples int a = 7; int b = 10; if( a > 4 && b < 20 ) { // This will be true since both operands to the && operator will evaluate to true } int c = 10; int d = 40; if( c == 7 || d > c ) { // This will be true. Even though the first operand evaluates to false, // the second will evaluate to true. } int e = 7; int f = 10; if( !(e == f) ) { // This will evaluate to true since e == f will be false, // and the NOT operator will reverse it }

Logical Operator: Gotchas int x = 5; if( 0 < x < 11) // Testing to see if x is in range of 1 to 10 { System.out.println("X is in range"); } int x = 5; if( x > 0 && < 11) // Testing to see if x is in range of 1 to 10 { System.out.println("X is in range"); }

Logical Operator: Gotchas int x = 5; if( x > 0 && x < 11) // Testing to see if x is in range of 1 to 10 { System.out.println("X is in range"); } So, remember: you need whatever you are comparing—whether variables or methods— listed on both sides of the logical operators. if( getStreet() > 0 && getStreet() < 11)

Logical Operator: Robotic Examples if(this.countThingsInBackpack() > 0 && this.frontIsClear()) { this.putThing(); this.move(); } if((this.isFacingEast() || this.isFacingWest()) && this.frontIsClear()) { this.move(); } if( !(this.frontIsClear()) ) { this.turnLeft(); } Example: LogicalOperatorRobot.java

The Return Statement and Return Values

Return Values An Illustrated Introduction to Return Values First, a look at non-return… Up to now we’ve seen how to use void methods… public void moveMultiple(int numberOfIntersections) { int counter = 0; while( counter < numberOfIntersections) { this.move(); counter = counter + 1; } rob.moveMultiple(5); You can pass an argument to a void method and it will do whatever it is meant to do, but nothing is returned as a separate value that the program might use later on.

Void: Means “Nothing is Returned” Up to now we’ve seen how to use void methods. public void moveMultiple(int numberOfIntersections) { int counter = 0; while( counter < numberOfIntersections) { this.move(); counter = counter + 1; } void means that nothing is returned back to the program; the method does something, it just doesn’t return something back into the program once it’s finished doing whatever it is it’s been doing. moveMultiple 5 …and down in main: rob.moveMultiple(5); The meaning of “void”

Two Types of “void” Nothing goes in, nothing comes out Something goes in, nothing comes out move(); moveMultiple(5); 5 Method 1 Method 2

Cooking Eggs Analogy Return: By Way of A Cooking Eggs Analogy customer.overEasy() Alas, nothing is returned. Hungry customer not happy. The overEasy() method does exactly what it is supposed to do—it cooks the egg over easy, but that’s as far as it goes… kitchen class diningRoom class

WTF? * * Where’s the food? A Sad Scenario

Cooking Eggs Analogy plate = customer.overEasy() Hooray, overEasy() returns the cooked egg and puts it in the plate! Plate is now used to transport egg to happy customer! egg.sunnySideUp() egg.overEasy() egg.overMedium() egg.overHard() egg.scrambled() egg.poached() egg.hardboiled() egg.softBoiled()

A Happy Scenario Breakfast is served!

Return: The Return Type Must Be Specified The Return Value is a way to send the information back into the program so the program can use it in another way. public int addSum(int num) public int countMoves( ) return counter; return sum; public boolean isNorth(int num) return true; int true int will be returned true or false will be returned chugga-chugga

Nothing goes in, something comes out Something goes in, something comes out FileName.java FileName2.java 3 Method 1 Method 2 Two Types of “Return”

class PrintHelper extends Object { public int printNum() { System.out.println("Going to print, some number of times!"); int howManyPrints = 0; while(howManyPrints < 2) { System.out.println("Printing!"); howManyPrints++; // This is a basic counter } return howManyPrints; } } public class FileName extends Object { public static void main(String[] args) { PrintHelper Gutenberg = new PrintHelper(); int num; num = Gutenberg.printNum(); // This method is called by an object System.out.println( "The method printed " + num + " times!"); } } Walkthrough: FileName.java

class PrintHelper extends Object { public int printNum() { System.out.println("Going to print, some number of times!"); int howManyPrints = 0; while(howManyPrints < 2) { System.out.println("Printing!"); howManyPrints++; // This is a basic counter } return howManyPrints; } } public class FileName extends Object { public static void main(String[] args) { PrintHelper Gutenberg = new PrintHelper(); int num; num = Gutenberg.printNum(); System.out.println( "The method printed " + num + " times!"); } } Class “Idea / Attributes” Object (Instance of Class) Class

class PrintHelper extends Object { public int printNum() { System.out.println("Going to print, some number of times!"); int howManyPrints = 0; while(howManyPrints < 2) { System.out.println("Printing!"); howManyPrints++; // This is a basic counter } return howManyPrints; } } public class FileName extends Object { public static void main(String[] args) { PrintHelper Gutenberg = new PrintHelper(); int num = 0; num = Gutenberg.printNum(); System.out.println( "The method printed " + num + " times!"); } } howManyPrints num

class PrintHelper extends Object { public int printNum () { System.out.println("Going to print, some number of times!"); int howManyPrints = 0; while(howManyPrints < 2) { System.out.println("Printing!"); howManyPrints++; // This is a basic counter } return howManyPrints; } } public class FileName extends Object { public static void main(String[] args) { PrintHelper Gutenberg = new PrintHelper(); int num; num = Gutenberg.printNum(); System.out.println( "The method printed " + num + " times!"); } } howManyPrints num howManyPrints 2

Example Code: Return Let’s look at some more examples using return… NumberTest.java ReturnValues_Demo.java

The for statement (loop) “For as long as this condition is true... do something.”... do something.”

The for statement (loop) The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for (initiating statement; conditional statement; next statement) // usually incremental { body statement(s); } “For as long as this condition is true... do something.”... do something.”

The for statement (loop) for (initial statement; conditional; next statement // usually incremental { statement(s); } class ForLoopDemo { public static void main(String[] args) { for(int count = 1; count < 11; count++) { System.out.println("Count is: " + count); } The output of this program is: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 “For as long as this is true... do something.”

The for statement (loop) There are three clauses in the for statement. The init-stmt statement is done before the loop is started, usually to initialize an iteration variable (“counter”). After initialization this part of the loop is no longer touched. The condition expression is tested before each time the loop is done. The loop isn't executed if the Boolean expression is false (the same as the while loop). The next-stmt statement is done after the body is executed. It typically increments an iteration variable (“adds 1 to the counter”). for(int count = 1; count < 11; count++) { System.out.println("Count is: " + count); }

initialization; while(condition) { statement; } for(initialization; condition; increment) { statement; } The for loop is shorter, and combining the intialization, test, and increment in one statement makes it easier to read and verify that it's doing what you expect. The for loop is better when you are counting something. If you are doing something an indefinite number of times, the while loop may be the better choice.

while loop class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } for loop class ForLoopDemo { public static void main(String[] args) { for(int count = 1; count < 11; count++) { System.out.println("Count is: " + count); }

while loop class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } for loop class ForLoopDemo { public static void main(String[] args) { for(int count = 1; count < 11; count++) { System.out.println("Count is: " + count); } SEE: for_while_test.java

The Do-While Loop

do-while loops The Java programming language also provides a do-while statement, which can be expressed as follows: do { statement(s) } while (expression); The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program: class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); }

while loop EVALUATES AT THE TOP class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } for do-while loop EVALUATES AT THE BOTTOM class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } SEE: for_while_do_while _test.java

REFRESHER: The if-else Statement if(Boolean_expression){ statement 1 //Executes when true }else{ //<-- No Conditional statement 2 //Executes when false } public class IfElseTest { public static void main(String args[]) { int x = 30; if( x < 20 ){ System.out.print(“The number is less than 20."); }else{ System.out.print(“The number is NOT less than 20!"); }

The if-else Statement if(Boolean_expression){ statement 1 //Executes when true }else{ // <--No Conditional statement 2 //Executes when false } Now, this works great if you’re only testing two conditions, but what do you do if you have more than two conditions? What if you have three conditions, or four, or five?

Several if Statements if(Boolean_expression_01) { statement//Executes when true } if(Boolean_expression_02) { statement//Executes when true } if(Boolean_expression_03) { statement//Executes when true } if(Boolean_expression_04) { statement//Executes when true } if(Boolean_expression_05) { statement//Executes when true } You could create a whole bunch of if statements to look for and test a particular condition, and this is perfectly acceptable, although this might get unwieldy if you have several conditions, say ten or more to look through.

Several if Statements int grade = 98; if(grade >=0 && grade < 60) { System.out.println(”Sorry. You did not pass.”); } if(grade >= 60 && grade < 70) { System.out.println(”You just squeaked by.”); } if(grade >= 70 && grade < 80) { System.out.println(”You are doing better.”); } if(grade >= 80 && grade < 90) { System.out.println(”Not too bad a job!”); } if(grade >= 90 && grade <= 100) { System.out.println(”You are at the top of your class!”); }

“Nested if-elses" It is common to make a series of tests on a value, where the else part contains only another nested if statement. If you use indentation for the else part, it isn't easy to see that these are really a series of tests which are similar. This is traditional syntax, but there’s actually a cleaner way to do this in Java. int grade = 68; if(grade >=0 && grade = 60 && grade = 70 && grade = 80 && grade = 90 && grade <= 100) { System.out.println("You are at the top of your class!"); } } } } And how about all those squiggles!

"Cascading-if" if…else if…else Text if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true }else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true }else { // <-- No Conditional //Executes when none of the above conditions are true. } if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true }else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true }else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true }else { // <-- No Conditional //Executes when none of the above conditions are true. }

"Cascading-if" if…else if…else So, contrary to our typical formatting style of indenting to the braces, it is better to write them at the same indentation level by writing the if on the same line as the else. int grade = 68; if(grade >=0 && grade = 60 && grade = 70 && grade = 80 && grade < 90) { System.out.println("Not too bad a job!"); } else // <-- No conditional { System.out.println("You are at the top of your class!"); }

if (this.frontIsBlocked()) { this.turnAround(); } else if (this.canPickThing()) { this.turnRight(); } else if (this.leftIsBlocked()) { this.turnLeft(); } else { this.move(); }

ICE 15: Loopy Robot Before starting today’s ICE, you may want to look at the Boolean return examples: BooleanReturns1.java BooleanReturns2.java BooleanReturns3.java