CS 102: Programming1 Lecture 5 - Java Flow Control PDF

Document Details

AuthoritativeDemantoid

Uploaded by AuthoritativeDemantoid

Horus University

2024

Dr. Mona Alnaggar

Tags

java programming flow control programming computer science

Summary

These lecture notes for CS 102: Programming 1, Fall 2024, cover Java's flow control structures, including if-else, switch, and ternary operators. The content also includes examples and explanations for the concepts.

Full Transcript

CS 102: Programming1 Lecture 5 – Java Flow Control Dr. Mona Alnaggar Fall 2024 outlines Flow Control in Java if...else Statement Ternary Operator Switch Statement Shorthand Operators Flow of Control Unless specified otherwise, the order of statement execution...

CS 102: Programming1 Lecture 5 – Java Flow Control Dr. Mona Alnaggar Fall 2024 outlines Flow Control in Java if...else Statement Ternary Operator Switch Statement Shorthand Operators 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 3 4 Control Structures Sequential execution – Program statements execute one after the other Transfer of control – Three control structures can specify order of statements Sequence structure (default) Selection structure Repetition structure Activity diagram – Models the workflow (flowchart) Action-state symbols Transition arrows 5 Control Structures cont. Java has a sequence structure “built-in” Java provides three selection structures – if – if…else – if…else if … – switch Java provides three repetition structures – while – do…while – for Each of these words is a Java keyword 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 if statement has the following syntax: The condition must be a boolean expression. It must if is a Java evaluate to either true or false. reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped. if Single-Selection Statement Single-entry/single-exit control structure condition evaluated Perform action only when condition is true true Action/decision programming model false statement if (studentGrade >= 60) { System.out.println (“Passed”); } [grade >= 60] print “Passed” [grade < 60] Fig if single-selections statement activity diagram. 8 Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to != not equal to < less than > greater than = greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=) 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 5-10 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) Logical Operators Expressions that use logical operators can form complex conditions if (count != 0 && total/count > MAX) System.out.println ("Testing…"); All logical operators have lower precedence than the relational operators Logical NOT has higher precedence than logical AND and logical OR 5-12 if…else Selection Statement Perform action only when condition is true Perform different specified action when condition is false Conditional operator (?:) Nested if…else selection structures if (studentGrade >= 60) { System.out.println (“Passed”); } [grade < 60] [grade >= 60] else print “Failed” print “Passed” { System.out.println (“Failed”); } if…else double-selections statement activity diagram. 13 The if-else Statement condition evaluated An else clause can be added to an if statement to make an if-else statement true false if ( condition ) statement1; statement1 statement2 else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both 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!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; } The Conditional (Ternary )Operator Java has a conditional operator that uses a boolean condition to determine which of two expressions is evaluated Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression The Conditional (Ternary ) Operator cont. The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands Example of Conditional (Ternary ) Operator 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 Example: System.out.println (studentGrade >= 60 ? “Passed”: “Failed”); If studentGrade is greater than or equal 60 , then “Passed" is printed If studentGrade is not greater than nor equal 60, then “Failed" is printed 5-19 Nested If statements Since an “If” statement is a statement, it can appear inside another if statement. if (condition1) if (condition2) statement; It can also appear in an “else” clause if (condition1) statement1; else if (condition2) statement2; else statement3; The else if Statement Use the else if statement to specify a new condition if the first condition is false. if (condition1){ // block of code to be executed if condition1 is true } else if (condition2){ // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false } Example : int time = 22; if (time < 10) { System.out.println("Good morning."); } else if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening." Another Selection Statement The if and the if-else statements are selection statements, allowing us to select which statement to perform next based on some Boolean condition Another selection construct, called the switch statement, provides another way to choose the next action The switch statement evaluates an expression, then attempts to match the result to one of a series of values. Execution transfers to statement list associated with the first value that matches The switch statement provides another way to decide which statement to execute next. The switch statement evaluates an expression, then attempts to match the The switch result to one of several possible cases. Statement Each case contains a value and a list of statements. The flow of control transfers to statement associated with the first case value that matches. The switch Statement The general syntax of a switch statement is: switch switch ( expression ) and { case case value1 : are statement-list1 reserved case value2 : words statement-list2 case value3 : statement-list3 If expression case... matches value2, control jumps } to here 5-25 The switch Statement Often a break statement is used as the last statement in each case's statement list. A break statement causes control to transfer to the end of the switch statement. If a break statement is not used, the flow of control will continue into the next case. Sometimes this may be appropriate, but often we want to execute only the statements associated with one case. The switch Statement An example of a switch statement: switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: System.out.println(“default.. "); } 5-27 The switch Statement A switch statement can have an optional default case. The default case has no associated value and simply uses the reserved word default. If the default case is present, control will transfer to it if no other case value matches. If there is no default case, and no other value matches, control falls through to the statement after the switch. 5-28 The switch Statement The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int, long) or a char It cannot be a boolean value or a floating-point value (float or double) The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement 5-29 Example: int day = 4; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Looking forward to the Weekend"); } // Outputs "Thursday" (day 4) Shorthand Operators Shorthand Operators Many operations are very commonly used x = x + 1; sum = sum + x; Java has shorthand notations for these increment and decrement operators assignment operators The Increment and Decrement Operators The increment operator (++) adds one to its integer or floating- point operand The decrement operator (--) subtracts one The statement count++; is essentially equivalent to count = count + 1; The Increment and Decrement Operators The increment and decrement operators can be applied in prefix (before the variable) or postfix (after the variable) form When used alone in a statement, the prefix and postfix forms are basically equivalent. That is, count++; //postfix is equivalent to ++count; //prefix The Increment and Decrement Operators When used in a larger expression, the prefix and postfix forms have a different effect. In both cases the variable is incremented (decremented). But the value used in the larger expression depends on the form Expressions Operation Value Of expression count++ add 1 old value ++count add 1 new value count-- subtract 1 old value --count subtract 1 new value The Increment and Decrement Operators If count currently contains 45, then total = count++; assigns 45 to total and 46 to count If count currently contains 45, then total = ++count; assigns the value 46 to both total and count The Increment and Decrement Operators If sum contains 25, what does this statement print? System.out.println (sum++ + " " + ++sum + " " + sum + " " + sum--); Prints the following result: 25 27 27 27 sum contains 26 after the line is complete Thanks! Do you have any questions?

Use Quizgecko on...
Browser
Browser