CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

Control Structures Corresponds with Chapters 3 and 4.
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.
Slide 1 of 64 Lecture C Lesson 3: Conditions and Loops Unit 1: The if Statement.
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.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
UNIT II Decision Making And Branching Decision Making And Looping
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
Chapter 05 (Part III) Control Statements: Part II.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Introduction to Java Java Translation Program Structure
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
If Statement if (amount
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Decisions Bush decision making.
Control statements Mostafa Abdallah
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
5 Copyright © 2004, Oracle. All rights reserved. Controlling Program Flow.
Control Statements: Part1  if, if…else, switch 1.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Chapter 4 – C Program Control
The switch Statement, and Introduction to Looping
CiS 260: App Dev I Chapter 4: Control Structures II.
JavaScript: Control Statements.
3 Control Statements:.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Lab5 PROGRAMMING 1 Loop chapter4.
PROGRAM FLOWCHART Iteration Statements.
Chap 7. Advanced Control Statements in Java
CSC215 Lecture Control Flow.
Control Statements:.
Presentation transcript:

CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3

CSM-Java Programming-I Lesson-1 Objectives Review of last class Statements and Blocks if-else Comparing values and objects switch while, do-while for break, labels, continue

CSM-Java Programming-I Lesson-1 Statements Expression Statement: Those that are terminated by a semi-colon. Assignment Expression: Those that contain =. Declaration statements: Those that declare a variable and initialize it to a value. Method calls and control flow statements. Object creation expressions. Prefix or postfix forms of ++ and --.

CSM-Java Programming-I Lesson-1 Block A block statement groups together several statements, by enclosing them in braces {}. A block can be used where any single statement is allowed because a block is a compound statement.

CSM-Java Programming-I Lesson-1 if-else The if-else statement lets a program carry out different actions depending on the outcome of a condition. The syntax is: if (boolean-expression) statement1 else statement2 The boolean expression is evaluated first. If its value is true, then statement1 is executed; otherwise, if there is an else clause, statement2 is executed. The else clause is optional.

CSM-Java Programming-I Lesson-1 Comparing Values The relational operators are used to compare values. Eg: >, >=, <, <=, ==. != The == operator tests for equality. To compare strings, use the equals method, not the == operator. if (str1.equals(str2)) tests if they are equal to each other. if (str1 == str2) tests whether the two string variables refer to the identical string object.

CSM-Java Programming-I Lesson-1 Comparing Strings To ignore the letter case, use the equalsIgnoreCase method. if (str1.equalsIgnoreCase(str2)) To compare strings in dictionary order, use compareTo method. if (str1.comapreTo(str2)) < 0 // str1 comes before the str2 in the dictionary. Eg: str1 =“Harry” and str2=“Hell”. if ( str1.compareTo(str2)) > 0 // str1 comes after str2 in the dictionary if (str1.comapreTo(str2)) == 0 // str1 equals str2

CSM-Java Programming-I Lesson-1 Comparing objects The == operator tests whether two object references are identical. To compare the contents of the objects, use the equals method. Rectangle cerealBox = new Rectangle(5,10,20,30); Rectangle r = cerealBox; Rectangle oatmealBox = new Rectangle(5,10,20,30); cerealBox == r is true cerealBox == oatmealBox is false cerealBox.equals(oatmealBox); is true The null reference refers to no object. if (account == null ) is valid.

CSM-Java Programming-I Lesson-1 switch A sequence of if/else/else that compares a single integer value against several constant alternatives can be implemented as a switch statement. int digit; ……….. switch (digit) { case 1: Sytem.out.print(“one”); break; case 2: Sytem.out.print(“two”); break; case 3: Sytem.out.print(“three”); break; default: Sytem.out.print(“error”); break; }

CSM-Java Programming-I Lesson-1 switch For if statement the same example would be: int digit; …….. if (digit == 1) System.out.print(“one”); else if (digit == 2) System.out.print(“two”); else if (digit == 2) System.out.print(“three”); else System.out.print(“error”);

CSM-Java Programming-I Lesson-1 switch The test cases (in the above example “digit”) in a switch statement must be integers or characters. switch (name) { case “one”: …break; //error …… } If the break is missing, execution falls through to the next branch, and so on, until finally a break or end of the switch is reached.

CSM-Java Programming-I Lesson-1 Boolean Expressions Complex tests can be performed using the operators &&, || and !. if (0 < amt <1000)… // Error if (0 < amt && amt <1000)… // correct //tests if amt greater than 0 and less than if (ch == ‘S’ || ‘M)… // Error if (ch == ‘S’ || ch == ‘M)… // Correct // tests if the ch is ‘S’ or ‘M’.

CSM-Java Programming-I Lesson-1 Boolean Expressions if (!input.equals(“S))…. // tests if the string input is not equal to “S”. private boolean married; // test of boolean in if if (married) …… else …….

CSM-Java Programming-I Lesson-1 Logical operations ABA || B trueanytrue falsetrue false ABA &&B true false anyfalse De-Morgan’s Law !(A && B) is same as !A || !B !(A || B) is same as !A && !B A!A truefalse true

CSM-Java Programming-I Lesson-1 while A while statement executes a block of code repeatedly. A termination condition controls how often the loop is executed. while (condition) statements If the condition is true then the loop will never end.

CSM-Java Programming-I Lesson-1 while – Infinite loops A common reason for infinite loops is forgetting to advance the variable that controls the loop. int years = 0; while (years < 20) { double interest = balance * rate/100; balance = balance + interest; } // value of years is always 0

CSM-Java Programming-I Lesson-1 while – Infinite loops Another common reason for infinite loop is accidentally incrementing a counter that should be decremented (or vice versa). int years = 20; while (years > 0) { years++; // should have been years--; double interest = balance * rate / 100; balance = balance + interest; }

CSM-Java Programming-I Lesson-1 do-while Sometimes you want to execute the body of a loop at least once and perform the loop test after the body was executed. do statement while (condition); The statement is executed while the condition is true. The condition is tested after the statement is executed, so the statement is executed at least once.

CSM-Java Programming-I Lesson-1 do-while Suppose you want to make sure that a user enters a positive number. double value; do { // keep prompting the user for a positive number as // long as the user enters a negative number. } while (value <= 0); You need to get the user input before you can test it.

CSM-Java Programming-I Lesson-1 for The for statement is used to loop over a range of values from beginning to end. for (init-expr; condition; incr-expr) statement; This is equivalent to init-expr; while (condition) { statement incr-expr; }

CSM-Java Programming-I Lesson-1 for for (i = 1; i <= n; i++) { statements……. } The initialization and iteration statements of a for loop can be a comma-separated list of expressions. for (;;)- infinite for loop statement

CSM-Java Programming-I Lesson-1 Labels Statements can be labeled. Labels are typically used on blocks and loops. A label precedes a statement. label : statement Java has no goto construct to transfer control to an arbitrary statement in a method. Use a labeled break statement for purpose.

CSM-Java Programming-I Lesson-1 Labels outerloop: while (outer loop condition) {……. while (inner loop condition) {…… if (condition) break outerloop; } jumps here once the if condition is true.

CSM-Java Programming-I Lesson-1 break A break statement is used to exit from any block, not just from a switch. It can be used to exit a while, for or a do loop. public void breakLoop(String str) { int i = 0; while (i < 100) { if (i == 10) break; // terminate loop if i is 10 System.out.println(“i: “ + i); i++; }

CSM-Java Programming-I Lesson-1 continue A continue statement skips to the end of a loop's body and evaluates the condition that controls the loop. It has meaning only inside a loops. It forces early iteration of a loop.

CSM-Java Programming-I Lesson-1 continue class Continue { public static void main (String args[]) { for (int i=0; I < 10; i++) { System.out.print(i + “ “); if (i%2 == 0) continue; System.out.println(“”); }

CSM-Java Programming-I Lesson-1 continue In this example continue causes two numbers to be printed on each line. The % operator checks if i is even. If it is, the loop continues without printing a newline. Result is :