Pemrograman Dasar Smt I 2004/2005

Slides:



Advertisements
Similar presentations
Chapter 3: Control Flow S. M. Farhad. Statements and Blocks An expression becomes a statement when it is followed by a semicolon Braces { and } are used.
Advertisements

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.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
UNIT II Decision Making And Branching Decision Making And Looping
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
DAT602 Database Application Development Lecture 5 JAVA Review.
Chapter 4 Program Control Statements
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
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.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
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.
Controlling Execution Dong Shao, Nanjing Unviersity.
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,
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
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.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
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)
JavaScript and Ajax (Control Structures) Week 4 Web site:
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.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Information and Computer Sciences University of Hawaii, Manoa
Core Java Statements in Java.
Lecture 4b Repeating With Loops
‘C’ Programming Khalid Jamal.
Fundamentals of PL/SQL part 2 (Basics)
Java Language Basics.
SWE 510: Object Oriented Programming in Java
Chapter 10 – Exception Handling
The switch Statement, and Introduction to Looping
Control Structures.
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
CiS 260: App Dev I Chapter 4: Control Structures II.
JavaScript: Control Statements.
Basic Java Syntax The Java language will be described by working through its features: variable types and expressions selection and iteration classes exceptions.
Chapter 5: Control Structures II
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
SELECTION STATEMENTS (1)
Control Structures.
Arrays, For loop While loop Do while loop
Chapter 6 More Conditionals and Loops
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Java - Data Types, Variables, and Arrays
CS1100 Computational Engineering
Additional Control Structures
In this class, we will cover:
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Lab5 PROGRAMMING 1 Loop chapter4.
Lecture 11 Objectives Learn what an exception is.
In this class, we will cover:
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Introduction to Programming
Additional control structures
Loops CGS3416 Spring 2019 Lecture 7.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Pemrograman Dasar Smt I 2004/2005 Control Statement Pemrograman Dasar Smt I 2004/2005

Statement (review) The statement is the main building block from which code sequences are constructed. Statements are executed in the order listed and are always terminated by a semicolon. expr; or { expr1; expr2; … exprn; } 11/27/2018 8:32 PM Control Statements

Control Flow Statement We use control flow statement to conditionally execute statements, to repeatedly execute a block of statements, and to otherwise change the normal, sequential flow of control. For example, in the following code snippet, the if statement conditionally executes the System.out.println statement within the braces, based on the return value of Character.isUpperCase(aChar): char c; ... if (Character.isUpperCase(aChar)) { System.out.println("The character " + aChar + " is upper case."); } 11/27/2018 8:32 PM Control Statements

Control Flow Statement in Java Statement Type Keyword Looping while, do-while , for Decision making if-else, switch-case Exception handling try-catch-finally, throw branching break, continue, label:, return 11/27/2018 8:32 PM Control Statements

The if Statement used to conduct a conditional test and execute a block of statements if the test evaluates to true. Syntax: Note you can layout code in any way you want. if ( booleanExpression ) {statement} if ( booleanExpression ) { statement } else 11/27/2018 8:32 PM Control Statements

Example If Else public class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); 11/27/2018 8:32 PM Control Statements

The output from this program is: Grade = C You may have noticed that the value of testscore can satisfy more than one of the expressions in the compound if statement: 76 >= 70 and 76 >= 60. However, as the runtime system processes a compound if statement such as this one, once a condition is satisfied, the appropriate statements are executed (grade = 'C';), and control passes out of the if statement without evaluating the remaining conditions. 11/27/2018 8:32 PM Control Statements

Example If Else 2 import java.util.*; public class Morning { public static void main( String args[] ) { Calendar rightNow = Calendar.getInstance(); if ( rightNow.get( Calendar.AM_PM ) == Calendar.AM ) System.out.println( "Good morning..." ); else System.out.println( "Good afternoon..." ); } 11/27/2018 8:32 PM Control Statements

Dangling Else The else clause is always associated with the nearest if Use { … } to change the association if ( booleanExpression ) statement else 11/27/2018 8:32 PM Control Statements

The switch statement used to evaluate a variable that can later be matched with a value specified by the "case" keyword in order to execute a group of statements. The default case is optional. Syntax: switch ( expression ) { case char/byte/short/int constant : statementSequence … default: statementSequence 11/27/2018 8:32 PM Control Statements

Example public class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; } 11/27/2018 8:32 PM Control Statements

Example public class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; } System.out.println("Number of Days = " + numDays); } } Example 11/27/2018 8:32 PM Control Statements

Switch-Example 3 We use the default statement at the end of the switch to handle all values that aren't explicitly handled by one of the case statements. int month = 8; . . . switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Hey, that's not a valid month!"); break; } 11/27/2018 8:32 PM Control Statements

The while Loop While : “used to declare a loop that iterates a block of statements. The loop`s exit condition is specified as part of the while statement.” Syntax: while ( booleanExpression ){ statement } 11/27/2018 8:32 PM Control Statements

Divide public class Divide { public static void main( String args[] ) { int dividend = 35; int divisor = 5; int remainder = dividend; int quotient = 0; while ( remainder >= divisor ) { remainder = remainder - divisor; quotient = quotient + 1; } System.out.println( dividend + " / " + divisor + " = " + quotient); dividend + " % " + divisor + " = " + remainder ); } // Divide 11/27/2018 8:32 PM Control Statements

Square Root public class SquareRoot { public static void main( String args[] ) { double epsilon = 1.0e-9; double number = 2.0; double oldGuess = 0; double newGuess = number; while ( Math.abs( newGuess - oldGuess ) > epsilon ) { oldGuess = newGuess; newGuess = ( ( number / oldGuess ) + oldGuess ) / 2.0; } System.out.println( “The square root of “ + number + “ is “ +newGuess ); } // SquareRoot 11/27/2018 8:32 PM Control Statements

The do-while Loop do-while evaluates the expression at the bottom. Thus the statements associated with a do-while are executed at least once. Syntax: do { statement(s) } while ( booleanExpression ); 11/27/2018 8:32 PM Control Statements

The for Loop Syntax: The initialization is an expression that initializes the loop-it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. This expression is evaluated at the top of each iteration of the loop. When the expression evaluates to false, the loop terminates. Finally, increment is an expression that gets invoked after each iteration through the loop. Each of the expressions is optional, the semicolons are not. for (initialization; termination; increment) { statement } 11/27/2018 8:32 PM Control Statements

Often for loops are used to iterate over the elements in an array, or the characters in a string. The following sample, ForDemo, uses a for statement to iterate over the elements of an array and print them: public class ForDemo { public static void main(String[] args){ int[] arrayOfInts = {32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = 0; i < arrayOfInts.length; i++) { System.out.print(arrayOfInts[i] + " "); } System.out.println(); 11/27/2018 8:32 PM Control Statements

Factorial public class Factorial { public static void main( String args[] ) { int num = 5; int fact = 1; for ( int i = 1; i <= num; i++ ) fact = fact * i; System.out.println( fact ); } } // Factorial 11/27/2018 8:32 PM Control Statements

CharCount public class CharCount { public static void main( String args[] ) { String theString = "Now is the time for all good people ... "; char target = 't'; int count = 0; for ( int i = 0; i < theString.length(); i++ ) if ( theString.charAt( i ) == target ) count++; System.out.println( target + " appears " + count + " times" ); } } // CharCount 11/27/2018 8:32 PM Control Statements

Reverse // This program reverses a given string public class Reverse { public static void main( String args[] ) { String orig = "Hello World"; String reverse = ""; for (int i = 0; I < orig.length(); i++) reverse = orig.charAt( i ) + reverse; System.out.println( reverse ); } } // Reverse 11/27/2018 8:32 PM Control Statements

Mult public class Mult { public static void main( String args[] ) { for ( int i = 0; i < 10; i++ ) { for ( int j = 0; j < 10; j++ ) { if ( i * j < 10 ) System.out.print( " " ); System.out.print( ( i * j ) + " " ); } System.out.println(); } // Mult 11/27/2018 8:32 PM Control Statements

Transfer Statements The break statement can occur anywhere within a switch, for, while or do statement and causes execution to jump to the next statement. The continue statement can occur anywhere within a for, while or do statement and causes execution to jump to the end of the loop body. 11/27/2018 8:32 PM Control Statements

Exception Handling Statements Exception is an event during program execution that prevents the program from continuing normally; generally, an error. It means that the normal flow of the program is interrupted and that the runtime environment attempts to find an exception handler--a block of code that can handle a particular type of error. The exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a gentle exit from the program. The Java supports exceptions with the try, catch, and throw keywords. 11/27/2018 8:32 PM Control Statements

Try-Catch-finally Three statements play a part in handling exceptions: The try statement identifies a block of statements within which an exception might be thrown. The catch statement must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the try block. The finally statement must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block. 11/27/2018 8:32 PM Control Statements

Exception Handling Syntax try { statement(s) } catch (exceptiontype name) { } finally { } 11/27/2018 8:32 PM Control Statements

Branching Statement Java support 3 branching statement: The break statement The continue statement The return statement 11/27/2018 8:32 PM Control Statements

Branching #1 : Break The break statement has two forms: unlabeled and labeled. The unlabeled form of the break statement used with switch earlier. Unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. We can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop. The following sample program, BreakDemo , contains a for loop that searches for a particular value within an array: 11/27/2018 8:32 PM Control Statements

Unlabeled-Break Example public class BreakDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int searchfor = 12; int i = 0; boolean foundIt = false; for ( ; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true; break; } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i); } else { System.out.println(searchfor + "not in the array"); 11/27/2018 8:32 PM Control Statements

Branching: Labeled-Break The labeled form terminates an outer statement, which is identified by the label specified in the break statement. The following program, BreakWithLabelDemo, is similar to the previous one, but it searches for a value in a two-dimensional array. Two nested for loops traverse the array. When the value is found, a labeled break terminates the statement labeled search, which is the outer for loop: 11/27/2018 8:32 PM Control Statements

Labeled-Break Example public class BreakWithLabelDemo { public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i = 0; int j = 0; boolean foundIt = false; search: for ( ; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } if (foundIt) { System.out.println("Found " + searchfor + " at " + i + ", " + j); } else { System.out.println(searchfor + "not in the array"); Labeled-Break Example 11/27/2018 8:32 PM Control Statements

Branching #2 : Continue Statement We use the continue statement to skip the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop, basically skipping the remainder of this iteration of the loop. The following program, ContinueDemo , steps through a string buffer checking each letter. If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a p, the program increments a counter, and converts the p to an uppercase letter. 11/27/2018 8:32 PM Control Statements

Continue - Example public class ContinueDemo { public static void main(String[] args) { StringBuffer searchMe = new StringBuffer( "peter piper picked a peck of pickled peppers"); int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { //interested only in p's if (searchMe.charAt(i) != 'p') continue; //process p's numPs++; searchMe.setCharAt(i, 'P'); } System.out.println("Found " + numPs + " p's in the string."); System.out.println(searchMe); 11/27/2018 8:32 PM Control Statements

Branching #3: Return Statement The last of Java's branching statements is the return statement. We use return to exit from the current method. The flow of control returns to the statement that follows the original method call. The return statement has two forms: one that returns a value and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword: The data type of the value returned by return must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value: return value: return: 11/27/2018 8:32 PM Control Statements