Chapter 5 Conditionals and Loops Conditionals and Loops
- Slides: 33
Chapter 5 Conditionals and Loops
Conditionals and Loops • Now we will examine programming statements that allow us to: § make decisions § repeat processing steps in a loop • Chapter 5 focuses on: § § § boolean expressions conditional statements comparing data repetition statements iterators 2
Outline The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements © 2004 Pearson Addison-Wesley. All rights reserved 3
Flow of Control • Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence • Some programming statements allow us to: § decide whether or not to execute a particular statement § execute a statement over and over, repetitively • These decisions are based on boolean expressions (or conditions) that evaluate to true or false • The order of statement execution is called the flow of control © 2004 Pearson Addison-Wesley. All rights reserved 4
Conditional Statements • A conditional statement lets us choose which statement will be executed next • Therefore they are sometimes called selection statements • Conditional statements give us the power to make basic decisions • The Java conditional statements are the: § if statement § if-else statement § switch statement © 2004 Pearson Addison-Wesley. All rights reserved 5
The if Statement • The if statement has the following syntax: if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped. 6
Logic of an if statement condition evaluated true false statement © 2004 Pearson Addison-Wesley. All rights reserved 7
Boolean Expressions • A condition often uses one of Java's equality operators or relational operators, which all return boolean results: higher precedence == != < > <= >= 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 (=) 8
The if Statement • An example of an if statement: if (sum > MAX) delta = sum - MAX; System. out. println ("The sum is " + sum); • First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not • If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped. • Either way, the call to println is executed next © 2004 Pearson Addison-Wesley. All rights reserved 9
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 • Although it makes no difference to the compiler, proper indentation is crucial "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live. " -- Martin Golding © 2004 Pearson Addison-Wesley. All rights reserved 10
The if Statement • What do the following 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) inventory. Error = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse • The precedence of the arithmetic operators is higher than the precedence of the equality and relational operators © 2004 Pearson Addison-Wesley. All rights reserved 11
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) 12
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 a !a true false true Consider a ‘condition’ something like (age > 25) It is either true or false (boolean result) 13
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 both are true, and false otherwise Examples: if ( a> 14 && b == 6) a++; if (a > 14 || b == 6) b--; 14
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, which have lower precedence than arithmetic operators. • Logical NOT has higher precedence than logical AND and logical OR 15
Logical Operators • 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 a && b a || b true true false true false © 2004 Pearson Addison-Wesley. All rights reserved 16
Boolean Expressions • Specific expressions can be evaluated using truth tables total < MAX found !found total < MAX && !found false true false true false 17
Short-Circuited Operators • The processing of logical AND and logical OR is “short-circuited” • If the left operand is sufficient to determine the result, the right operand is not evaluated if (count != 0 && total/count > MAX) System. out. println ("Testing…"); • This type of processing must be used carefully © 2004 Pearson Addison-Wesley. All rights reserved 18
Outline The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements © 2004 Pearson Addison-Wesley. All rights reserved 19
The if-else Statement • An else clause can be added to an if statement to make an if-else statement if ( condition ) statement 1; else statement 2; • If the condition is true, statement 1 is executed; if the condition is false, statement 2 is executed • One or the other will be executed, but not both 20
Logic of an if-else statement condition evaluated true false statement 1 statement 2 © 2004 Pearson Addison-Wesley. All rights reserved 21
The Coin Class • Let's examine a class that represents a coin that can be flipped • Instance data is used to indicate which face (heads or tails) is currently showing © 2004 Pearson Addison-Wesley. All rights reserved 22
//********************************** // Coin. Flip. java Author: Lewis/Loftus // // Demonstrates the use of an if-else statement. //********************************** public class Coin. Flip { //--------------------------------// Creates a Coin object, flips it, and prints the results. //--------------------------------public static void main (String[] args) { Coin my. Coin = new Coin(); my. Coin. flip(); System. out. println (my. Coin); if (my. Coin. is. Heads()) System. out. println ("You win. "); else System. out. println ("Better luck next time. "); } } © 2004 Pearson Addison-Wesley. All rights reserved 23
// Coin. java Author: Lewis/Loftus Please note that I have taken GREAT liberties in formatting to ‘fit’ public class Coin { private final int HEADS = 0; private final int TAILS = 1; private int face; public Coin () // Sets up the coin by flipping it initially { flip(); } public void flip () // Flips the coin by randomly choosing a face value. { face = (int) (Math. random() * 2); } public boolean is. Heads () // Returns true if the current face of the coin is heads. { return (face == HEADS); } public String to. String() // Returns the current face of the coin as a string. { String face. Name; if (face == HEADS) face. Name = "Heads"; else face. Name = "Tails"; return face. Name; }© 2004 Pearson Addison-Wesley. All rights reserved } 24
Indentation Revisited • Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) System. out. println ("Error!!"); error. Count++; Despite what is implied by the indentation, the increment will occur whether the condition is true or not Discuss!!!! © 2004 Pearson Addison-Wesley. All rights reserved 25
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!!"); error. Count++; } Explain. 26
Block Statements • In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { System. out. println ("Error!!"); error. Count++; } else { System. out. println ("Total: " + total); current = total*2; } • See Guessing. java 27
// Guessing. java Author: Lewis/Loftus // Demonstrates the use of a block statement in an if-else. import java. util. *; public class Guessing { // Plays a simple guessing game with the user. public static void main (String[] args) { final int MAX = 10; int answer, guess; Scanner scan = new Scanner (System. in); // Creates a scan object; Random generator = new Random(); // creates a new random number object = generator answer = generator. next. Int(MAX) + 1; // generates another integer random number <= 10. System. out. print ("I'm thinking of a number between 1 and “ + MAX + ". Guess what it is: "); guess = scan. next. Int(); // gets the guess from the input… if (guess == answer) // compares the guess to the random number generated, answer. System. out. println ("You got it! Good guessing!"); / executed if predicate is true. else { System. out. println ("That is not correct, sorry. "); // executed (both statements) if predicate System. out. println ("The number was " + answer); // is false. } // end else } 2004 // end main © Pearson Addison-Wesley. All rights reserved 28 }// end Guessing
The Conditional Operator • Java has a conditional operator that uses a boolean condition to determine which of two expressions is evaluated • Its syntax is: condition ? expression 1 : expression 2 • If the condition is true, expression 1 is evaluated; if it is false, expression 2 is evaluated • The value of the entire conditional operator is the value of the selected expression 29
The Conditional Operator • The conditional operator is similar to an if-else statement, except that it is an expression that returns a value • For example: larger = ((num 1 > num 2) ? num 1 : num 2); • If num 1 is greater than num 2, then num 1 is assigned to larger; otherwise, num 2 is assigned to larger • The conditional operator is ternary because it requires three operands 30
The Conditional Operator • Another example: System. out. println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); • If count equals 1, then "Dime" is printed • If count is anything other than 1, then "Dimes" is printed 31
Nested if Statements • The statement executed as a result of an if statement or else clause could be another if statement • These are called nested if statements • See Min. Of. Three. java • 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 32
// Min. Of. Three. java Author: Lewis/Loftus // Demonstrates the use of nested if statements. import java. util. Scanner; public class Min. Of. Three { // Reads three integers from the user and determines the smallest value. public static void main (String[] args) { int num 1, num 2, num 3, min = 0; Scanner scan = new Scanner (System. in); System. out. println ("Enter three integers: "); num 1 = scan. next. Int(); num 2 = scan. next. Int(); num 3 = scan. next. Int(); if (num 1 < num 2) if (num 1 < num 3) min = num 1; else min = num 3; else if (num 2 < num 3) min = num 2; else min = num 3; System. out. println ("Minimum value: " + min); // end main ©}2004 Pearson Addison-Wesley. All rights reserved } // end Min. Of. Three 33
- While loops and if-else structures
- Branches in electrical circuit
- Small basic
- Pulmonary loop
- Reddish loops of gas
- Matlab for loop break
- Types of loops in matlab
- Programming puzzle
- Break in python nested loop
- Drilling fluid
- For statement matlab
- Cakewalk loops
- Featureless loops of wangensteen
- Adobe audition loops
- Nested loops python
- Matlab do while
- Python sentinel loop
- Pseudocode if else
- Is nested loops bad
- Hirschsprung disease
- Reddish loops of gas that link parts of sunspot regions
- Dynamic and adynamic intestinal obstruction
- Forward path in signal flow graph
- Control roadmap
- Loops o repeticiones
- Be8255
- Arduino parallel loops
- Virtual loops
- Nested for loop complexity
- Seninelle
- A node having only outgoing branches
- Nested pseudocode
- N nested for loops
- Mesh analysis 3 loops