Expression statements are formed by adding a semicolon to the end of certain types of expressions.

Similar documents
COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

More Control Structures

Oct Decision Structures cont d

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

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

CSC 1051 Data Structures and Algorithms I

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

COMP 202 Java in one week

Java Programming: from the Beginning. Chapter 8 More Control Structures. CSc 2310: Principle of Programming g( (Java) Spring 2013

Repetition, Looping. While Loop

Loops. CSE 114, Computer Science 1 Stony Brook University

COMP 202. Java in one week

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

Values in 2 s Complement

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Chapter 3. Selections

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java I/O and Control Structures

In this chapter, you will:

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

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

Java Basic Programming Constructs

Computer Programming I - Unit 5 Lecture page 1 of 14

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Java I/O and Control Structures Algorithms in everyday life

CSC 1051 Data Structures and Algorithms I

CS111: PROGRAMMING LANGUAGE II

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Chapter 4: Control Structures I

Exam 2, Version 2. For the following code, mark True or False for statements 1.8 to 1.10.

CMPT 125: Lecture 4 Conditionals and Loops

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Iteration statements - Loops

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

AP CS Unit 3: Control Structures Notes

Java Coding 3. Over & over again!

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

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Arithmetic Compound Assignment Operators

3chapter C ONTROL S TATEMENTS. Objectives

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

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

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

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

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

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

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

CS111: PROGRAMMING LANGUAGE II

DM503 Programming B. Peter Schneider-Kamp.

CONDITIONAL EXECUTION

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Control Structures in Java if-else and switch

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

Introduction to the Java Basics: Control Flow Statements

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Building Java Programs

Example: Monte Carlo Simulation 1

1 Short Answer (10 Points Each)

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

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

AP Programming - Chapter 6 Lecture

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Introduction to Computer Science Unit 2. Notes

Term 1 Unit 1 Week 1 Worksheet: Output Solution

switch-case Statements

Some Sample AP Computer Science A Questions - Solutions

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Condensed Java. 12-Oct-15

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

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Top-Down Program Development

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

Important Java terminology

Repetition, Looping CS101

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

Introduction. C provides two styles of flow control:

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Object-oriented programming in...

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

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

CSC 1051 Data Structures and Algorithms I

STUDENT LESSON A12 Iterations

Fundamentals of Programming Data Types & Methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

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

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Combo Lecture Lecture 14/15. Instructor: Craig Duckett

Program Fundamentals

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

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

Conditional Programming

Transcription:

Expression statements are formed by adding a semicolon to the end of certain types of expressions. Variable declaration statements declare variables. int width, height, area; String hello = "Hello, world!"; An assignment expression is an expression involving an assignment. area = width * height; A method call expression has no assignment. System.out.println(...); A block is a sequence of one or more statements enclosed by braces( ). x = 1; y = 2; System.out.println(y); System.out.println(x); A block with declarations int i = 5 + j; // i is declared in this // block j is from where // end of block, i disappears //can t access i here An empty statement or null statement is just a semicolon all by itself and results in no action. x = 1; y = 2;;;;; System.out.println(y); ;;;;; System.out.println(x);

A boolean expression is any expression that evaluates to either true or false. Java includes a primitive type boolean. Relational operators, <, <=, >, >= Equality operators, ==,!= int i = 3, j = 4; boolean flag; flag = 5 < 6; //flag is now true flag = (i == j); //flag is now false flag = (j + 2) <= 6; //flag is now true Operators that take boolean values as operands. x && y - true if x AND y are both true x y - true if either x OR y are true, or both!x - true if x is false - read NOT x boolean b = (ageofperson >= 18 && ageofperson < 65); System.out.println("full fare adult is " + b); b = (ageofperson < 18 ageofperson >= 65); System.out.println("reduced fare is " + b); if The if statement is a conditional statement. if ( BooleanExpr ) Statement If the expression BooleanExpr is true, then the statement, Statement, is executed. Otherwise, Statement is skipped. if statement with a single statement if (temperature < 32) System.out.println("Warning: Below freezing!"); System.out.println("It s " + temperature + " degrees"); if statement with a block if (temperature < 32) System.out.println("Warning: Below freezing!");

Problem A different number is initially placed in each of three boxes, labeled a, b, and c, respectively. The problem is to rearrange or sort the numbers so that the final number in box a is less than that in box b and that the number in box b is less than that in box c. 1. Place the first number in box a. 2. Place the second number in box b. 3. Place the third number in box c. 4. If the number in a is not larger than the number in b, go to step 6. 5. Interchange the number in a with that in b. 6. If the number in b is larger than the number in c, then go to step 7; otherwise, halt. 7. Interchange the numbers in b and c. 8. If the number in a is larger than that in b, then go to step 9; otherwise, halt. 9. Interchange the numbers in a and b. 10.Halt. // SortInput.java - sort three numbers import java.util.*; class SortInput public static void main (String[] args) int a, b, c, t; Scanner scan = new Scanner(System.in); System.out.println("type three integers:"); a = scan.nextint(); b = scan.nextint(); c = scan.nextint(); if (a > b) // swap a and b t = a; a = b; b = t; if (b > c) // swap b and c t = b; b = c; c = t; if (a > b) // swap a and b t = a; a = b; b = t; // This doesn t match the pseudo-code. Why not? System.out.print("The sorted order is : "); System.out.println(a + ", " + b + ", " + c);

if- An if- statement has the following form: if ( BooleanExpr ) Statement1 Statement2 If the expression BooleanExpr is true, then Statement1 is executed and Statement2 is skipped. If BooleanExpr is false, then Statement1 is skipped and Statement2 is executed. Finding the minimum if (x < y) min = x; min = y; System.out.println("min = " + min); A block in an if- statement if (temperature < 32) System.out.println(32 - temperature + " degrees below freezing!"); System.out.println("It s " + temperature + "degrees fahrenheit."); if- if (x < y); System.out.println("The smaller is " + x); if (y < x); System.out.println("The smaller is " + y); if (temperature < 32) System.out.print("It is now"); System.out.print(32 - temperature); System.out.println(" below freezing."); System.out.println("It's " + temperature + "degrees"); The if statement is a full-fledged statement and can be used anywhere a statement is expected. So, you can put another if statement in either branch of an if statement. if (ageofperson >= 18) if (ageofperson < 65) System.out.println("full fare adult"); if (ageofperson >= 18 && ageofperson < 65) System.out.println("full fare adult");

if (temperature < 32) if (temperature < 0) System.out.println((-temperature) + " degrees below Zero!" System.out.println(32 - temperature + "(F) below Freezing!"); System.out.println("It is " + temperature + " degrees fahrenheit."); if (18 <= age < 65). if (ageofperson < 18) System.out.println("child fare"); if (ageofperson < 65) System.out.println("adult fare"); System.out.println("senior fare"); Each statement is surrounded in the following figure. if (ageofperson < 18) System.out.println("child fare"); if (ageofperson < 65) System.out.println("adult fare"); System.out.println("senior fare"); Sometimes this chain of if--if--if- can get rather long, tedious, and inefficient.

while Misleading indentation if (Expression1) if (Expression2) Statement1 Statement2 The indenting suggests that Statement2 is executed whenever Expression1 is false. The proper indenting is if (Expression1) if (Expression2) Statement1 Statement2 Or, uses braces to force the grouping. if (Expression1) if (Expression2) Statement1 Statement2 The while statement allows us to write programs that run repeatedly. while ( BooleanExpr ) Statement Statement is executed repeatedly as long as the expression BooleanExpr is true. class Valentine public static void main(string[] args) int howmuch = 0; while (howmuch < 5) System.out.println("I love you."); howmuch++; Pseudocode using goto 1. Get a number. 2. If the number is 0 go to step 6. 3. Add the number to the running total. 4. Increment the count of numbers read in. 5. Go back to step 1. 6. Divide the running total by the count of number in order to get the average. 7. Print the average. Pseudocode using while Get a number. While the number is not 0 do the following: Add the number to the running total. Increment the count of numbers read in. Get a number. (when the loop exits) Divide the running total by the count of number in order to get the average. Print the average.

// Average.java - compute average of input values import java.util.*; public class Average public static void main(string[] args) double number; int count = 0; double runningtotal = 0; Scanner scan = new Scanner(System.in); // initialization before first loop iteration System.out.println("Type some numbers, the last one being 0"); number = scan.nextdouble(); while (number!= 0) runningtotal = runningtotal + number; count = count + 1; // prepare for next iteration number = scan.nextdouble(); System.out.print("The average of the "); System.out.print(count); System.out.print(" numbers is "); System.out.println(runningTotal / count); int count = 13; System.out.println("The multiples of 13 between 1 and 100 are:"); while (count!= 100) System.out.println(count); count = count + 13; do-while A variant of the while statement. do Statement while ( BooleanExpr ); Statement is executed at least once. Execution stops when the expression BooleanExpr is false. Finding GCD (Greatest Common Divisor) for two integers. import java.util.*; class GreatestCommonDivisor public static void main(string[] args) Scanner scan = new Scanner(System.in); System.out.println("Enter 2 integers."); int num1 = scan.nextint(); int num2 = scan.nextint(); int m = num1, n = num2, remainder; do remainder = m % n; m = n; n = remainder; while( n!= 0); System.out.println("GCD (" + num1 + ", " + num2 + ") = " + m );

for The for statement is a looping statement that captures the initialization, termination test, and iteration preparation all in one place at the top of the loop. for ( ForInit; BooleanExpr; Updateexpr ) Statement // SquareRoots.java - print square roots of 1-10 import static java.lang.math.*; public class SquareRoots public static void main(string[] args) int i; double squareroot; for (i = 1; i <= 10; i++) squareroot = sqrt(i); System.out.println("the square root of " + i + " is " + squareroot); System.out.println("That's All!"); for The ForInit part of the for statement can be a local declaration. for (int i = 1; i <= 10; i++) squareroot = sqrt(i); System.out.println("the square root of " + i + " is " + squareroot); The int variable i is limited to the for statement. Outside the for statement, it disappears. break The break statement causes an exit from the innermost enclosing loop. while (true) //seemingly an infinite loop System("Enter a positive integer:") n = scan.nextint(); if (n < 0) // exit loop if n is negative System.out.print("squareroot of " + n); System.out.println(" = " + Math.sqrt(n)); // break jumps here

continue The continue statement causes the current iteration of a loop to stop and causes the next iteration of the loop to begin immediately. // BreakContinue.java - example of break and continue import java.util.*; class BreakContinue public static void main(string[] args) int n; Scanner scan = new Scanner(System.in); while (true) //seemingly an infinite loop System.out.print("Enter a positive integer "); System.out.print("or 0 to exit:"); n = scan.nextint(); if (n == 0) // exit loop if n is 0 if (n < 0) continue; //wrong value System.out.print("squareroot of " + n); System.out.println(" = " + Math.sqrt(n)); //continue lands here at end of current iteration //break lands here System.out.println("a zero was entered"); switch The switch statement can be used in place of a long chain of if--if--if- statements when the condition tested evaluates to an integer numeric type. Day of week with if- if (dayofweek == 1) System.out.println("Sunday"); if (dayofweek == 2) System.out.println("Monday"); if (dayofweek == 3) System.out.println("Tuesday"); if (dayofweek == 4) System.out.println("Wednesday"); if (dayofweek == 5) System.out.println("Thursday"); if (dayofweek == 6) System.out.println("Friday"); if (dayofweek == 7) System.out.println("Saturday"); System.out.println("Not a day number " + dayofweek); Day of week with switch switch (dayofweek) case 1: System.out.println("Sunday"); case 2: System.out.println("Monday"); case 3: System.out.println("Tuesday"); case 4: System.out.println("Wednesday"); case 5: System.out.println("Thursday"); case 6: System.out.println("Friday"); case 7: System.out.println("Saturday"); default: System.out.println("Not a day number " + dayofweek);

Day of week grouping weekdays and weekends switch (dayofweek) case 1: case 7: System.out.println("Stay home today!"); case 2: case 3: case 4: case 5: case 6: System.out.println("Go to work."); default: println("not a day number " + dayofweek); Several rules of boolean algebra are useful for rewriting boolean expressions. Commutative law a or b == b or a a and b == b and a Distributive and law a and (b or c) == (a and b) or (a and c) Distributive or law a or (b and c) == (a or b) and (a or c) Double negation!!a == a DeMorgan s law!(a or b) ==!a and!b!(a and b) ==!a or!b In the expression x y, y will not be evaluated if x is true. In the expression x && y, y will not be evaluated if x is false. int x = 0; int y = 0; if (x == 0 y++ == 2) System.out.println ( true ); System.out.println ( y = + y); Same Result? int x = 0; int y = 0; if (x == 1 && y++ == 2) System.out.println ( true ); System.out.println ( y = + y); Same Result? int x = 0; int y = 0; if (y++ == 2 x == 0) System.out.println ( true ); System.out.println ( y = + y); int x = 0; int y = 0; if (y++ == 2 x == 1) System.out.println ( true ); System.out.println ( y = + y);