Statements and Control Flow The programs we have seen so far do exactly the same list of instructions every time What if we want to do different things.

Slides:



Advertisements
Similar presentations
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
Advertisements

5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Slide 1 of 64 Lecture C Lesson 3: Conditions and Loops Unit 1: The if Statement.
Making Choices (Chap 3) If you wish to defrost, press the defrost button; otherwise press the full power button. Let the dough rise in a warm place until.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 2 Sanjay Goel University at Albany,
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
1 Chapter 3 Flow of Control. 2 Outline  How to specify conditions?  Relational, Equality and Logical Operators  Statements  Statements: compound statement.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Making Choices (Chap 3) If you wish to defrost, press the defrost button; otherwise press the full power button. Let the dough rise in a warm place until.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
TODAY’S LECTURE Review Chapter 2 Go over exercises.
UNIT II Decision Making And Branching Decision Making And Looping
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing.
CSc2310 tutoring session, week 8 Fall, 2012 Haidong Xue 5:30pm—8:30pm 11/06/2012 and 11/07/2012 -Test 3 Study Guide.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 5: Structured Programming
4.1 Object Operations operators Dot (. ) and new operate on objects The assignment operator ( = ) Arithmetic operators + - * / % Unary operators.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Decision Statements, Short- Circuit Evaluation, Errors.
STRUCTURED PROGRAMMING Selection Statements. Content 2  Control structures  Types of selection statements  if single-selection statement  if..else.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Control Statements: Part1  if, if…else, switch 1.
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.
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 # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
Lecture 4b Repeating With Loops
Chapter 3: Decisions and Loops
Selections Java.
The switch Statement, and Introduction to Looping
Control Statements: Part 1
Control Structures.
JavaScript: Control Statements I
JavaScript: Control Statements.
IF if (condition) { Process… }
Selection (if-then-else)
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 4: Control Structures I (Selection)
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chap 7. Advanced Control Statements in Java
CSC215 Lecture Control Flow.
Control Statements:.
Presentation transcript:

Statements and Control Flow The programs we have seen so far do exactly the same list of instructions every time What if we want to do different things for different inputs? –Do some action only if a specified condition is met –We need conditional statements if(value < 0) System.out.println(“Bad input”);

Statements and Control Flow What if we want to repeat some set of instructions some number of times? –Repeat an action some number of times –We need iterative statements while(i < 100) System.out.println(i++);

Statements Declaration Statement: type, followed by a comma-separated list of identifiers, followed by a semi-colon int foo, bar; String name = “Scott”; Expression Statement: expression followed by a semi-colon –Assignment Expression: size = size + 5 –Method Call Expression: System.out.println(…) –Not all expressions can be part of an expression statement (more on this later)

Block Statement Block Statement: one or more statements inside braces, e.g., { int a = 4;// Statement System.out.println(a); // Statement }// Statement –A Block Statement is a Statement –Block Statements can contain Block Statements –Variables declared within a block disappear when the block has finished executing

Empty Statement Empty statement: do-nothing statement ; –Is a statement, but does nothing Example: –Wait for a condition to become true while(notTimeYet) ; –Question: Which is clearer, that, or this: while(notTimeYet);

Boolean Expression Any expression that evaluates to true or false –true –false –Comparisons –Logical operations

Relational Operators NameSymbolExpression Equal= a = = b Not equal!=a != b Less than<a < b Greater than>a > b Less than or equal to<=a <= b Greater Than or Equal to>=a >= b

Comparisons Comparisons (using relational operators) evaluate to true or false Example: int a = 5, b = 7; boolean flag; flag = (a < b);// boolean expression System.out.println(flag);

Logical Operators Operations on logical values NameOperatorExpression NOT!a = !(b = = c) AND&&a = (b && c) OR||a = (b || c)

Logical Operations Example 1 int x, y; boolean b; x = Console.in.getInt(); y = Console.in.getInt(); b = (x == y); System.out.println(b); Example 2 boolean b = (age >= 18 && age < 65); System.out.println("full fare adult is " + b); b = (age = 65); System.out.println("reduced fare is" + b);

Operator Precedence and Associativity Operator Precedence –The order in which different operators are evaluated, i.e. who goes first –* has higher precedence than +, both higher than = int x = * 5; // x = 23, not 35! Operator Associativity –The order in which operators of the same precedence are applied –* and % have equal precedence, left to right associativity int y = 4 * 3 % 2; // y = 0, not 4!

Operator Precedence and Associativity OperatorsAssociativity ( ) ++ (postfix) -- (postfix)Left to right + (unary) - (unary) ++ (prefix) -- (prefix) !Right to left * / %Left to right + -Left to right >=Left to right = = !=Left to right &&Left to right ||Left to right = += -= *= /= etc.Right to left

What if we want a different evaluation order? Parentheses ( ) have a higher precedence than just about everything else –They can be used to impose a different evaluation order int x = * 5;// x = 23 int x = (3 + 4) * 5;// x = 35 int y = 4 * 3 % 2;// y = 0 int y = 4 * (3 % 2);// y = 4

Conditional Statements Conditionally execute a statement based on the value of a boolean expression –if statement - decide whether or not to take a particular action Execute a particular statement only if a given boolean expression is true –if-else statement - choose between two alternative actions Execute one of two statements based on the value of a given boolean expression

Conditional Statements (cont.) –switch statement: choose among several alternative actions Execute one of a set of statements based on a specified value (not a boolean expression) –while statement: repeat an action as long as a specified condition is true Repeatedly execute a statement as long as the given boolean expression is true –for statement: execute an action a specified number of times Repeatedly execute a statement as long as the given boolean expression is true

if Statement Used to decide whether or not to take a particular action if( ) If the boolean expression is true, the then statement is executed, otherwise it is not

Flowchart For An if Statement Boolean Expression Statement True False The rest of the program

if Statements in Action if(value > 50) System.out.println(“Warning, value too big!”); if(y != 0) z = x / y; if(item.price = item.price) { item.purchase( ); cashOnHand - = item.price; }

Example: Bubblesort Given three numbers, place them in increasing order Algorithm: 1.Put the three numbers in a, b, and c 2.if b is less than a, swap a and b 3.if c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (1) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (1) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (1) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (1) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (1) a b c

Bubblesort (2) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (2) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (2) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (2) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (2) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (2) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (2) a b c 1.Put the three numbers in a, b, and c 2.If b is less than a, swap a and b 3.If c is less than b 1.swap b and c 2.if b is less than a, swap a and b

Bubblesort (2) a b c

// SortInput.java - sort three numbers import tio.*; // use the package tio class SortInput { public static void main (String[] args) { int a, b, c, temp; // Get three numbers from the user System.out.println("type three integers:"); a = Console.in.readInt(); b = Console.in.readInt(); c = Console.in.readInt(); // If b is less than a, swap a and b if (b < a) { temp = a; a = b; b = temp; }

// If c is less than b, swap b and c if (c < b) { temp = b; b = c; c = temp; // if (the new) b is less than a, swap a and b if (a > b) { temp = a; a = b; b = temp; } System.out.print("The sorted order is : "); System.out.println(a + ", " + b + ", " + c); }

If-else Statement Used to choose between two alternative actions if( ) else If the boolean expression is true, the then statement is executed, otherwise the else statement is executed

Flowchart For An if-else Statement Boolean Expression Then Statement True False The rest of the program Else Statement

If-else Statements in Action if (x < y) min = x; else min = y; System.out.println("min = " + min); if(y == 0) System.out.println(“Divide by zero error!”); else z = x / y;

Details Any statement can be a then or an else statement –Expression Statement, Block Statement, Conditional Statement (including if or if-else Statements), etc. Common errors –Look at the ones listed in the book They are exactly right

if-else-if-else If you string if-elses together, each if-else is the statement for the previous else if( ) else if( ) else

Dangling else An else always binds to the nearest previous unmatched if in its block if( ) // if 1 if( ) // if 2 else // binds to “if 2”

Dangling else An else always binds to the nearest unmatched if in its block if( ) { // if 1 if( ) // if 2 } else // binds to “if 1”

while Statement Repeat some action as long as a specified condition is true while( ) Repeatedly execute until is false –May not execute at all

Flowchart For A while Statement Boolean Expression Statement True False The rest of the program

while Statements in Action int value = 0; while(value < 5) System.out.println(value++); char c = ‘a’; while(c != ‘x’) { c = Console.in.getchar(); System.out.println(c); }

for Statement Repeat some action as long as a specified condition is true for( ; ; ) - executed once, at the beginning - checked each time through the loop, before - executed each time, after for statements are the same as while statements, except that init and update are explicitly included

Flowchart For A for Statement Boolean Expression Statement True False The rest of the program Initialization Update

for Statements in Action for(int value = 0; value < 5; value++) System.out.println(value); for(char c = ‘a’; c != ‘x’; System.out.print(c)) c = Console.in.getchar(); for(int i = 1, j = 1; i < 100; j = i +j) { System.out.println(i); i = j; }

break and continue break and continue interrupt the flow of control in a while loop, for loop, or switch statement break –Jumps out of a while or for loop With nested loops, jumps out of innermost one only –Causes a switch statement to terminate If you omit it after a case, control drops into the next case continue –Terminates the current iteration of a loop

break Statement in Action char c = ‘a’; while(c != ‘x’) { c = Console.in.getchar(); System.out.print(c); } while(true) { c = Console.in.getchar(); System.out.println(c); if(c == ‘x’) break; }

continue Statement in Action for(int i = 0; i < 100; i++) { if(i % 2 == 1) continue; System.out.println(i); }

switch Statement Choose among several alternative actions switch( ) { // integer variable or value case value1: // if == value1, do break; case value2 : // if == value2, do break; case valuen : // if == valuen, do break; }

switch Statements in Action switch(dayOfWeek) { case 1: System.out.println(“Sunday”); break; case 2: System.out.println(“Monday”); break; default: System.out.println(“Huh?”); break; }