L EC. 03: C ONTROL STATEMENTS Fall. 2014 0 Java Programming.

Slides:



Advertisements
Similar presentations
ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Advertisements

8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Introduction to Control Statements Presented by: Parminder Singh BCA 5 th Sem. [ Batch] PCTE, Ludhiana 5/12/ Control Statements.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
CSCI1402: Lecture 1 Week 6 Dr. David A. Elizondo Centre for Computational Intelligence School of Computing Office: Gateway 6.61
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 (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CSCI1402: Lecture 2 Week 6 Dr. David A. Elizondo Centre for Computational Intelligence School of Computing Office: Gateway 6.61
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
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.
JAVA Control Statement.
UNIT II Decision Making And Branching Decision Making And Looping
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
L EC. 02: D ATA T YPES AND O PERATORS (1/2) Fall Java Programming.
Chapter 4 Program Control Statements
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,
Flow of Control Part 1: Selection
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Switch Statement Is a selection control structure for multi-way branching. SYNTAX switch ( IntegralExpression ) { case Constant1 : Statement(s); // optional.
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
Chapter 05 (Part III) Control Statements: Part II.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Sahar Mosleh California State University San MarcosPage 1 Program Control Statement.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Decision Making and Branching (cont.)
The for loop.
Application development with Java Lecture 6 Rina Zviel-Girshin.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
5 Copyright © 2004, Oracle. All rights reserved. Controlling Program Flow.
Loops and Logic. Making Decisions Conditional operator Switch Statement Variable scope Loops Assertions.
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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 4b Repeating With Loops
Control Structures.
Chapter 5: Control Structures II
Chapter 5: Control Structures II
CSS161: Fundamentals of Computing
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
CSC215 Lecture Control Flow.
Presentation transcript:

L EC. 03: C ONTROL STATEMENTS Fall Java Programming

C ONTENT  Using System.in object to input data  Definition of Java statements  Categories of flow control statements  Condition constructs: if and switch  Iteration constructs: for, while and do-while  Nested constructs  Special control instructions: break and continue Fall Java Programming

A SIMPLE WAY FOR INPUTTING DATA  System.in is an object representing the input stream associated with the console input, i.e. the keyboard.  When it receives the read() message, it waits until the user presses a key and then returns the result to the message sender.  Browsing the methods defined in java.io.InputStream class!  The character returned from read() is an int, so it must be cast into a char to assign it to a char variable. Fall Java Programming

E XAMPLE OF USING System.in // Read a character from the keyboard. class KbIn { public static void main(String args[]) throws java.io.IOException { char ch; for(;;) { System.out.print("Press a key followed by ENTER: "); ch = (char) System.in.read(); // get a char System.out.println("Your key is: " + ch); if(ch == ‘z’) break; } Fall Java Programming This declaration will be discussed later! DO NOT remove it, otherwise, you will get error message.

J AVA STATEMENTS  A Java statement forms a complete unit of execution.  Each statement is terminated by a semicolon (;).  Types of statements  Expression statements  Declaration statements  Control flow statements (the major topic of this lecture) Fall Java Programming

E XPRESSION STATEMENTS  A expression statement is one of the following expressions.  Assignment expressions  Any use of ++ or --  Method invocations  Object creation expressions  Examples  val = 3.2;  ++x;  System.out.println();  new Integer(3); Fall Java Programming

D ECLARATION STATEMENTS  A declaration statement declares a variable.  Example  Double obj;  double dVal; Fall Java Programming

C ATEGORIES OF FLOW CONTROL  Sequential  Sequential is the flow type where instructions are executed one after another, from top to bottom.  Selection  Selection is the flow type where one path out of a number of possibilities is taken.  Iteration  Iteration is the flow type where one or more instructions is executed repeatedly if certain conditions are fulfilled.  Transfer  Transfer is the flow type where the point of execution jumps to a different point in the program.  Using transfer is considered as a poor programming style and makes the code maintenance difficult.  Java only supports the forward transfer, which transfer the execution point to a point beyond the current execution point. Sometimes forward transfer makes the code less complex. Fall Java Programming

if - CONSTRUCT  Syntax form if( ) statement else statement  if and else parts control a single statement.  If more than one statement needed to be controlled, use code block.  The else part is optional.  The else part must be associated with an if -part if it exists.  The condition expression must be a boolean expression.  If the conditional expression is true, the target of the if will be executed; otherwise, if it exists, the target of the else will be executed. Fall Java Programming if( i > 0 ) a++; // this if statement is terminated here b++; // since the target of if statement is a single statement // if( i > 0 ) statement is terminated here else c++; // no if part to match, so it’s illegal

F LOWCHART FOR if - CONSTRUCT Fall Java Programming Statement true Next statement false Statement

A GUESSING GAME // Guess the letter game. class Guess { public static void main(String args[]) throws java.io.IOException { char ch, answer = 'K'; System.out.println("I'm thinking of a letter between A and Z."); System.out.print("Can you guess it: "); // read a char from the keyboard ch = (char) System.in.read(); if(ch == answer) System.out.println("** Right **"); else System.out.println("...Sorry, you're wrong."); } Fall Java Programming

N ESTED if - CONSTRUCT  A nested if -construct is an if statement that is the target of another if or else.  An else statement always refers to the nearest if statement that is within the same block as the else and not already associated with an else. Fall Java Programming

E XAMPLES OF NESTED IF - CONSTRUCT  Example 1  Example 2 Fall Java Programming if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; else a = c; // this else refers to if(k > 100) } else a = d; // this else refers to if(i == 10) if(i == 10) { if(j < 20) { a = b; if(k > 100) c = d; } else a = c; // this else refers to if(j<20) } else a = d; // this else refers to if(i == 10) Java’s syntax is free of position! Using proper indentation makes programs clearer!

switch - CONSTRUCT  The switch -construct enables a program to select among several alternatives.  Syntax form Fall Java Programming switch( ) { case : statement sequence break; case : statement sequence break; case : statement sequence break; … default: statement sequence }

Executing switch - CONSTRUCT  Evaluating and comparing the result sequentially, from top to bottom, with constants following case -clauses.  When a match is found, the statements associated with that case are executed until the break is encountered or, in the case of default or the last case, until the end of the switch is reached.  The default statement sequence, if it exists, is executed if no case constant matches the expression.  The default -clause is optional.  If default -clause is not present, no action takes place if all matches fail. Fall Java Programming

S YNTAX RULES FOR switch - CONSTRUCT  Prior to JDK 7, the controlling the switch must be of type byte, short, int, char, or enum.  Beginning with JDK 7, can also be of type String.  Each value specified in the case clauses must be a unique constant expression.  A constant expression is a expression which can be evaluated during the compiling time.  The type of each value specified in the case clauses must be compatible with the type of. Fall Java Programming

D EMO SEGMENT FOR switch - CONSTRUCT switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12 : System.out.println(“There are 31 days"); break; case 2: System.out.println(“There are 28 or 29 days"); break; case 4: case 6: case 9: case 11: System.out.println(“There are 30 days"); break; default: System.out.println("Invalid month."); } Fall Java Programming

LOOPING  Java provides four types of looping (iteration) statements  Traditional for  while  do-while  Enhanced for Supported after Java 2 version 1.5  All looping have 4 parts  Initialization  Iteration condition  Body  Termination condition Fall Java Programming

T RADITIONAL for - CONSTRUCT Fall Java Programming  Syntax of while-statement for ( ; ; ) single-statement; Test_ exp statement true Next statement false init-_exp post-_exp Example int sum = 0; for(int count=0; count<=n; ++count ) { sum += count; } // count does not exist after this point

M ORE ON for - CONSTRUCT  The type of control variable can be any numeric types and char.  The loop control variable can be modified by any amount in.  It is a pre-condition looping.  The is tested at the beginning of each loop.  The code inside the loop may not be executed at all.  The and may consist of more than one expression separated by comma. Fall Java Programming int i, j; for(i=0, j=i+10; i < j; i++, j--) System.out.println("i and j: " + i + " " + j);

M ORE ON for - CONSTRUCT  The must be a boolean expression.  It does not need to involve the loop control variable.  All of the, and are option, but all three semicolons are not.  Missing means the result of is always true.  The simplest for -construct for(;;); will perform nothing for ever.  When you declare a variable inside a for loop, the scope of that variable ends when the for statement does. Fall Java Programming for( int i = 0; i < 100; i++) sum += i; System.out.print(sum / i); // illegal since i is not declared

while - CONSTRUCT Fall Java Programming  Syntax of while statement while ( ) single-statement; statement true Next statement false Example int sum = 0; int count = 0; while ( count <= n ) { sum += count; count++; } The while statement is a pre-test looping.

do-while - CONSTRUCT Fall Java Programming  Syntax of do-while statement do single-statement; while ( ); statement true Next statement false Example int sum = 0; int count = 0; if ( count <= n ) do { sum += count; count++; } while ( count <= n ); The do-while statement is a post-test looping.

break STATEMENT  The break statement is used to force an immediate exit from a loop enclosing the statement, bypassing any remaining code in the body of the loop and the loop’s conditional test.  The break statement can be only used within a loop body or the body of switch -construct. Fall Java Programming

D EMO PROGRAM FOR BREAK STATEMENT // Using break with nested loops. class Break3 { public static void main(String args[]) { for(int i=0; i<3; i++) { System.out.println("Outer loop count: " + i); System.out.print(" Inner loop count: "); int t = 0; while(t < 100) { if(t == 10) break; //terminate while loop if t is 10 System.out.print(t + " "); t++; } System.out.println(); } System.out.println("Loops complete."); } Fall Java Programming

break STATEMENT WITH LABEL  The break statement with label can be used to terminate the execution of a code block.  The code block terminated by using a break statement with label does not need to be the body of loop or switch.  Syntax form for break statement with label break ;  A label is the identifier used to identify a code block or a statement.  Syntax form for labeling code block : { }  When this form of break executes, control is transferred out of the named code block or statement.  The labeled code block or statement must enclose the break statement, but it does not need to be the immediately enclosing block.  This means that you can use a labeled break statement to exit from a set of nested blocks. Fall Java Programming

D EMO PROGRAM FOR break STATEMENT WITH LABEL // Using break with a label. class Break4 { public static void main(String args[]) { int i; for(i=1; i<4; i++) { one: { two: { three: { System.out.println("\ni is " + i); if(i==1) break one; if(i==2) break two; if(i==3) break three; System.out.println("won't print"); // this is never reached } System.out.println("After block three."); } System.out.println("After block two."); } System.out.println("After block one."); } System.out.println("After for."); } Fall Java Programming

T RY THIS … class Break6 { public static void main(String args[]) { int x=0, y=0; // here, put label before for statement. stop1: for(x=0; x < 5; x++) { for(y = 0; y < 5; y++) { if(y == 2) break stop1; // stop the for loop System.out.println("x and y: " + x + " " + y); } System.out.println(); // now, put label immediately before { for(x=0; x < 5; x++){ stop2: { for(y = 0; y < 5; y++) { if(y == 2) break stop2; // stop the body of for, not for System.out.println("x and y: " + x + " " + y); } Fall Java Programming

continue - CONSTRUCT  The continue statement forces the next iteration of the loop to take place, skipping any code between itself and the conditional expression that controls the loop.  In while and do-while loops, a continue statement will cause control to continues the loop by directly evaluating the.  In the case of the for, the of the loop is evaluated, then the loop continues by evaluating the. Fall Java Programming

D EMO PROGRAM FOR continue - CONSTRUCT // Use continue. class ContDemo { public static void main(String args[]) { int i; // print even numbers between 0 and 100 for(i = 0; i<=100; i++) { if((i%2) != 0) continue; // skipping the println and // continuing the next loop System.out.println(i); } Fall Java Programming The boolean expression is true for odd number.

continue STATEMENT WITH LABEL  The continue may specify a label to describe which enclosing loop to continue.  The statement labeled by a label used with continue statement must be a loop statement. Fall Java Programming

D EMO PROGRAM FOR continue STATEMENT WITH LABEL // Use continue with a label. class ContToLabel { public static void main(String args[]) { outerloop: for(int i=1; i < 10; i++) { System.out.print("\nOuter loop pass " + i + ", Inner loop: "); for(int j = 1; j < 10; j++) { if(j == 5) continue outerloop; // continue outer loop System.out.print(j); } Fall Java Programming