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.

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

Slide 1 of 64 Lecture C Lesson 3: Conditions and Loops Unit 1: The if Statement.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Loops – While, Do, For Repetition Statements Introduction to Arrays
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
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Unit 3 1 Flow of control H We will talk about: conditional statements  if-then-else  logical and conditional operators  switch repetition statements.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
UNIT II Decision Making And Branching Decision Making And Looping
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
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.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Chapter 5 Loops.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
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 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.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights.
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.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
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.
1 b Boolean expressions b truth tables b conditional operator b switch statement b repetition statements: whilewhile do/whiledo/while forfor Lecture 3.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
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.
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:
Loop Structures.
Operator Precedence Operators Precedence Parentheses () unary
Boolean Expressions and If
Boolean Expressions & the ‘if’ Statement
Outline Altering flow of control Boolean expressions
Outline Boolean Expressions The if Statement Comparing Data
Logic of an if statement
Repetition Statements
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)
Chap 7. Advanced Control Statements in Java
Conditionals and Loops
Boolean Expressions & the ‘if’ Statement
Presentation transcript:

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 are executed consecutively Control structures let us control the flow of control  Decide if certain statements should be executed  Repeat the execution of certain statements

3 The if Statement Syntax ::= if ( ) else Curly braces can be used to make it a compound statement ::= { ; ;…} This applies wherever a statement can occur

4 Logic of an if statement boolean expression statement true false

5 Boolean Expressions Evaluate to true or false Relational operators:  >(greater than)  <(less than)  >=(greater than or equal to)  <=(less than or equal to)  ==(equal to)  !=(not equal to) Be careful distinguishing = and ==

6 An if Example class IfExample { public static void main(String[] args) { int value = 6; if ( value == 6 ) System.out.println("equal"); System.out.println(“Always printed."); }

7 Indentation Indent the if statement to indicate that relationship Consistent indentation style makes a program easier to read and understand "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding

8 Braces or No Braces? These are both valid: if(value==6) { System.out.println(“equal”); } if(value==6) System.out.println(“equal”); Rule of thumb: only omit braces when it is obvious where the conditional starts/ends

9 What do these statements do? if (top >= MAXIMUM) top = 0; Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total != stock + warehouse) inventoryError = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse if (total > MAX) System.out.println ("Error!!"); errorCount++; Confusing indentation!! errorCount gets incremented, no matter what the value of total is

10 The if-else Statement An else clause is added to give an alternative statement to execute There isn’t really an “else if” in Java  … you can fake it, however…  The statement following else can be another if statement  … we’ll see an example in a minute

11 Logic of an if-else statement boolean expression statement1 true false statement2

12 An else-if Example class ConditionalExample { public static void main(String[] args) { int value = 6; if ( value == 6 ) System.out.println("equal"); else if ( value < 6 ) System.out.println("less"); else System.out.println("more"); }

13 More Boolean Expressions boolean operators:  !(not)  &, &&(and)  |, ||(or) These operators take boolean operands and return boolean values Methods can also return boolean values

14 Logical NOT Also called logical negation 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 a!a truefalse true

15 Logical AND and Logical OR a && b is true if both a and b are true, and false otherwise a || b is true if a or b or both are true, and false otherwise

16 Logical AND and Logical OR The truth table shows all possible true-false combinations of the terms aba && ba || b true false true falsetruefalsetrue false

17 Lazy Operators && and || are “lazy”  They only evaluate the right side if they have to & and | are “active”  They always evaluate both operands This differs from related programming languages

18 Complex Expressions Several operators in one statement: if (total < MAX+5 && !found) System.out.println ("Processing…"); All logical operators have lower precedence than the relational operators Logical NOT has higher precedence than logical AND and logical OR

19 Complex Expressions Specific expressions can be evaluated using truth tables total < MAXfound!foundtotal < MAX && !found false truefalse truefalse truefalsetrue false

20 More Conditionals The conditional operator condition ? expression1 : expression2 The switch statement  Useful for enumerating a series of conditions Covered in text

21 Thoughts on Comparing Values Be careful using == with floating point values  defining a threshold sometimes better Be extra special super careful using == with Strings  you are comparing references, not strings  use the equals method if that’s what you want Same for other object types  in the future, we’ll be defining equals methods

22 Repition Statements Also called loops Let certain statements be executed multiple times Controlled by boolean expresssions Java has 3 kinds of loops:  while  do  for

23 The While Statement Syntax: ::= while ( ) If the expression is true, then the statement is executed After executing the statement, we check the expression again and repeat The statement will run 0 or more times

24 Logic of a while Loop statement true false boolean expression

25 Example class WhileExample { public static void main(String[] args) { int count = 0; while ( count < 5 ) { System.out.print(count); System.out.print(" "); count++; } Output:

26 Infinite Loops The body of a while loop must eventually make the boolean expression false  …otherwise it is an infinite loop Always check to make sure your loops will terminate An infinite loops continues until interrupted (CTRL-C) or a memory error occurs

27 Nested Loops How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; } count1++; } 10 * 20 = 200

28 The do…while Statement syntax: ::= do while ( ) Run the condition, then check the boolean expression and repeat  The statement will run 1 or more times

29 Logic of a do Loop true boolean expression statement false

30 Example class DoWhileExample { public static void main(String[] args) { int count = 0; do { System.out.print(count); System.out.print(" "); count++; } while ( count < 5 ); }

31 The for Loop syntax: ::= for ( ; ; ) Three things in the parentheses:  The initialization statement  The continuation condition  The increment (or step) statement

32 Logic of a for loop statement true boolean expression false increment initialization

33 Example class ForExample { public static void main(String[] args) { int count; for ( count=0; count<5; count++ ) { System.out.print(count); System.out.print(" "); }

34 Equivalent while Structure A for loop is functionally equivalent to: initialization; while(condition) { statement; increment; } In general, all the loop statements are equivalent… use the “easiest” loop for each application

35 More on the for Loop Often used when a loop is to be executed a fixed number of times known in advance Formally, all the parenthetic information is optional There is also an Iterator version… this will make more sense when we know what Iterators are

36 User Input Traditionally this was messy in Java  New in Java 5.0 – the Scanner class Create a Scanner object with input from the console Use Scanner methods to retrieve input of appropriate type Keyboard input is represented by the System.in object

37 Creating a Scanner The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner (System.in); The new operator creates the Scanner object Once created, the Scanner object can be used to invoke various input methods, such as: answer = scan.nextLine();

38 Scanner Example import java.util.Scanner; // for Java 5.0+ class ScannerExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i = sc.nextInt(); double d = sc.nextDouble(); System.out.print("First value: "); System.out.println(i); System.out.print("Second value: "); System.out.println(d); } Historical Interlude