SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)
|
|
- Judith Ramsey
- 5 years ago
- Views:
Transcription
1 SOFTWARE DEVELOPMENT 1 Control Structures 2018W (Institute of Pervasive Computing, JKU Linz)
2 WHAT IS CONTROL FLOW? The control flow determines the order in which instructions are executed. Default: from top to bottom. This default behavior can be changed with control structures: 1. Composition: execute a sequence of instructions 2. Selection: choose from at least two alternatives continue with the next instruction or jump to another instruction 3. Iteration: repeat a block of instructions (loop, Schleife); at the end of the block: either jump back to the start of the block and repeat it or continue with the next instruction after the block Selection or iteration are also called branching (Verzweigung), since the control flow branches at this point. Software Development 1 // 2018W // 2
3 JAVA CONTROL FLOW Composition / Sequence Default behavior If there is no explicit branching order, Java executes the following instruction Branching: Selection If if-else if-else if-else if- - else switch Branching: Iteration While do-while for Software Development 1 // 2018W // 3
4 COMPOSITION :: EMPTY INSTRUCTION Syntax: ; An empty instruction is simply stated by a single semicolon. It has no effect whatsoever. Purpose: to fill syntactic holes: Insert an instruction where one is expected, but we do not want anything to happen. Software Development 1 // 2018W // 4
5 COMPOSITION :: BLOCK Syntax: { Instruction1; Instruction2;... Composition is grouping of several instructions in a single block. Instructions in the block will be executed sequentially. The block is syntactically similar to an instruction: it is allowed wherever single instructions are allowed. Variable declarations within a block are only visible and valid within the block. Software Development 1 // 2018W // 5
6 BLOCK :: PRIMITIVE INSTRUCTIONS Variable declarations Type nameofthevariable; Type nameofthevariable = initialvalue; Declaration of a local variable is an instruction Local variables are only visible from the point of their declaration to the end of the enclosing block. Expressions as instructions expression; An expression terminated by an semicolon is an instruction. The return value is discarded. Watch for side effects! Software Development 1 // 2018W // 6
7 VISIBILITY: VARIABLES IN BLOCKS public void withdraw(int amount) { int balance = 12345; System.out.println("Balance: " + balance); Local variables are only visible within the block in which they were declared, and in enclosed blocks. if (amount > 0) { // balance is visible in sub-blocks int newbalance = balance - amount; // after the declaration newbalance is also visible System.out.println("After withdrawal: " + newbalance); // newbalance NOT visible anymore! int newbalance = balance amount - 1; // beginning with the declaration, a new variable newbalance is visible System.out.println("After fees: " + newbalance); Software Development 1 // 2018W // 7
8 CONDITIONAL BRANCHING (IF-ELSE) First the condition is evaluated If the result is true, instruction1 is executed, if the result is false, instruction2 is executed if ( condition ) instruction1; else instruction2; The else part is optional: If there is no else part and the condition evaluates to false, nothing happens. condition Since it is impossible for a condition to be both true and false, only one of the two instructions will be executed, never both. true false instruction1 instruction2 Software Development 1 // 2018W // 8
9 CONDITIONAL BRANCHING (IF-ELSE) // Read a single character from the system input int keycode = System.in.read(); // If the user pressed enter (code 13), // then do nothing (skip the following) if (keycode!= 13) { IF with instruction block no ELSE part // If a letter has been entered, output it as character if (keycode >= 'a' && keycode <= 'z') System.out.println("Letter pressed: " + (char)keycode); // otherwise output just the numeric key code else System.out.println("Other key pressed, code is " + keycode); IF-ELSE with single instructions with ELSE-part SWE1.03 / IfSample1.java Software Development 1 // 2018W // 9
10 CONDITIONAL BRANCHING (IF-ELSE) int temperature = 50, month = 10; String assessment = null; // IF without block { if (temperature < 0) "dangling else" part // inner IF if (month < 5 month > 9) assessment = "cold"; of 1. or 2. IF? else assessment = "very odd"; belongs to 2. IF // IF with block { else if (temperature < 40) { // Dangling ELSE: ELSE always belongs to the directly preceding IF! if (month < 5 month > 9) if (temperature > 20) assessment = "unusually warm"; else assessment = "appropriate"; else assessment = "hot like hell"; // IF without ELSE: if there isn't yet an assessment, set to "typical" if (assessment == null) assessment = "typical"; System.out.println("The temperature is " + assessment + " for this time of year."); Software Development 1 // 2018W // 10 SWE1.03 / IfSample2.java
11 CONDITIONAL BRANCHING (IF-ELSE) "DANGLING ELSE" // Problem: // Alternative 1: if (num > 0) if (num < 10) System.out.println("option 1"); else System.out.println("option 2");? /* In this example we assume, that the else is part of the inner * if-statement. "option 2" should only be displayed, if num > 0 * and num >= 10, which can be combined to num >= 10. */ // Alternative 2: if (num > 0) if (num < 10) System.out.println("option 1"); else System.out.println("option 2"); /* Here it seems the "else" is part of the outer if-statement; * "option 2" should only be displayed if num <= 0... */ Software Development 1 // 2018W // 11
12 CONDITIONAL BRANCHING (IF-ELSE) "DANGLING ELSE" Solution (in Java) Indentation is just for readability. It has no influence on the control flow! For the compiler both examples are identical! Compiler needs to decide for one of the two alternatives. Which one?: Alternative 1 This phenomenon (choosing one else-alternative from two possible if-statements) is called dangling else Rule: else always belongs to the closest preceding if, that is within the current block Software Development 1 // 2018W // 12
13 SHORT-CIRCUIT-EVALUATION // Short-Circuit-Evaluation for &&: // second condition is not evaluated, if the first one is false if (x!= 0 && y / x > 0) z = 0; // equivalent to if (x!= 0) if (y / x > 0) z = 0; // Short-Circuit-Evaluation for : // second condition is not evaluated, if the first one is true if (x == 0 y / x > 0) z = 1; // equivalent to if (x == 0) z = 1; else if ( y / x > 0) z = 1; Software Development 1 // 2018W // 13
14 SWITCH STATEMENTS expression needs to evaluate to one of the primitive numeric data types byte, short, int, char, or to a String, or an Enumeration constantx are constants (literals, final variables) of the same data type as expression switch ( expression ) { case constant1: instructions ; case constant2: instructions ; instructions is a sequence of instructions First, expression is evaluated... Then all instructions, starting from the first constant that matches the result from expression, are executed Software Development 1 // 2018W // 14
15 SWITCH STATEMENTS If no constant matches the result of expression, the instructions starting from the default marker are executed The default part is optional. If no constant matches and there is no default, execution continues after the switch block A break instruction immediately leaves the switch block and continues execution after the block If a instruction sequence is not terminated with break, execution will continue with the instructions from the next case! This is only needed in exceptional cases: do not forget the break! switch ( expression ) { case constant1: instructions ; break; case constant2: instructions ; break;... default: instructions ; Software Development 1 // 2018W // 15
16 SWITCH STATEMENTS :: EXAMPLES int number = 27; // display the last digit as text switch (number % 10) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; case 3: System.out.println("three"); break; case 4: System.out.println("four"); break; case 5: System.out.println("five"); break; case 6: System.out.println("six"); break; case 7: System.out.println("seven"); break; case 8: System.out.println("eight"); break; case 9: System.out.println("nine"); break; SWE1.03 / SwitchSample1.java Software Development 1 // 2018W // 16
17 SWITCH STATEMENTS :: EXAMPLES int month = 2, days; boolean leapyear = false; // Determine number of days for month: switch (month) { case 4: case 6: case 9: case 11: days = 30; break; case 2: if (leapyear) days = 29; else days = 28; break; default: days = 31; System.out.println(days + " days"); SWE1.03 / SwitchSample2.java Software Development 1 // 2018W // 17
18 CONDITIONAL BRANCHING (SELECTION) :: SUMMARY if statements allow to execute instructions only if a condition matches (resolves to true) With the optional else part it is possible to specify alternative instructions to execute if the condition does not match To match an expression with multiple different values, it is more convenient to use a switch statement switch statements are only applicable to certain data types and constant values if ( condition ) instruction1; else instruction2; switch ( expression ) { case constant1: instructions ; break; case constant2: instructions ; break;... default: instructions ; Software Development 1 // 2018W // 18
19 ITERATION :: LOOPS Loops are required to execute an instruction (or instruction block) several times Syntax: Generally a part for initialization The body of the loop, containing instructions A termination condition Different types of loops: Count-controlled loops Condition-controlled loops Infinite loops minimum of zero or minimum of one loops Statements: while, do-while, for Software Development 1 // 2018W // 19
20 WHILE LOOPS First the condition is evaluated If it resolves to true, the instruction is executed and then the control flow returns to evaluating the condition If the condition resolves to false, execution continues after the loop If condition resolves to false from the start, the instruction is never executed In the instruction (or instruction block) some element from the condition needs to be changed. If nothing is changed, the loop will never terminate: Infinite loop while ( condition ) instruction; condition true instruction false Software Development 1 // 2018W // 20
21 WHILE LOOPS :: EXAMPLES // Count-controlled loop: count from 1 to 10 int index = 1; // initialization while (index <= 10) { // termination condition // body System.out.println("This is line number " + index); index++; // Condition-controlled loop: Terminates when the random number // generator returns a number greater 10 int number = 0; // initialization while (number <= 10) { // termination condition // body number = (int) (Math.random() * 20); System.out.println("Random number from 0 to 19: " + number); SWE1.03 / WhileSample1.java Software Development 1 // 2018W // 21
22 WHILE LOOPS :: MINIMUM OF ZERO // "minimum of zero" loop: // Read an arbitrary amount of numbers from the user and sum them up. // Stop if the user enters a negative number. Since the first value // is entered before the while loop, it is possible that the loop body // is never executed. int next, total = 0; next = Input.readInt(); // initialization while (next >= 0) { // termination condition // body total = total + next; next = Input.readInt(); Class Input: Provides several helper methods to make reading inputs easier Is not part of the Java API! Download from the department homepage. Required in the exercise. System.out.println("Sum: " + total); SWE1.03 / WhileSample2.java Software Development 1 // 2018W // 22
23 WHILE LOOPS :: EXAMPLE GCD gcd(x,y) = greatest common divisor of x and y x if x = y gcd(x,y) = gcd(x-y, y) if x > y gcd(x, y-x) if y > x because from x=t*f1 and y=t*f2 infer (x-y) = t*(f1-f2) or: x if y = 0 gcd(x,y) = gcd(y, x mod y) otherwise Software Development 1 // 2018W // 23
24 WHILE LOOPS :: EXAMPLE GCD int divisor, a, b, x, y, z; System.out.println("Enter two numbers: "); a = x = Input.readInt(); b = y = Input.readInt(); //read 2 numbers Version 1 while (a!= b) { if (a > b) a = a - b; else b = b - a; System.out.println("GCD = " + a); // gcd(a,b) = a if a = b // = gcd(a-b,b) if a > b // = gcd(a,b-a) if b > a Version 2 while (y!= 0) { z = x % y; x = y; y = z; System.out.println("GCD = " + x); SWE1.03 / WhileSampleGcd.java Software Development 1 // 2018W // 24
25 DO-WHILE LOOPS Similar to while loop, but with reversed order of body and condition: First the body is executed (at least once) Then the condition is checked while ( condition ) do instruction; instruction; while ( condition ); condition instruction true instruction false true condition false Software Development 1 // 2018W // 25
26 DO-WHILE LOOPS :: EXAMPLE // Condition-controlled loop: // Enter numbers until their sum exceeds 20. int total = 0; // initialization do { // body total += Input.readInt(); System.out.println("Subtotal: " + total); while (total <= 20); // termination condition System.out.println("Total: " + total); Do-while loops are very similar to while loops: Can be used for both condition- and count-controlled loops Somewhere in the body a variable of the condition needs to be changed, so the loop terminates SWE1.03 / DoWhileSample.java Software Development 1 // 2018W // 26
27 FOR LOOPS for ( initialization; condition; increment) instruction; First, the initialization is executed once Then the condition is evaluated If true, the instruction is executed, then the increment, and after that execution returns to evaluating the condition If the condition resolves to false, execution resumes after the for loop Software Development 1 // 2018W // 27
28 FOR LOOPS For loops are very convenient for count-controlled loops. Every for loop can be rewritten to a while loop: for ( initialization; condition; increment) instruction; is identical to initialization; while (condition) { instruction; increment; Software Development 1 // 2018W // 28
29 FOR LOOPS :: EXAMPLES // Ouptut 10 lines with line numbers: // The count variable i is declared within the loop and // only visible within! for (int i = 1; i <= 10; i++) System.out.println("Line " + i); // Here variable i is not valid anymore // Output the powers of 2 for (int i = 1; i <= 256; i *= 2) System.out.print(i + " "); System.out.println(); // Run through a list: // Output all Java system properties import java.util.iterator; import java.util.set; Set propertynames = System.getProperties().stringPropertyNames(); for (Iterator i = propertynames.iterator(); i.hasnext();) { String propertyname = (String) i.next(); String propertyvalue = System.getProperty(propertyName); System.out.println(propertyName + " = " + propertyvalue); SWE1.03 / ForSample.java Software Development 1 // 2018W // 29
30 ENHANCED FOR LOOPS It is very common to execute instructions for each element of a set or array. Therefore an enhanced for loop was introduced for this case: for ( elementvariable : set ) instruction; set is a collection (list, array, ) of elements. Each element in set is assigned once to elementvariable and then the instruction executed. The set can be an array, a container class from the Java-Collection framework, or any custom class that implements the interface Iterable. (More about that in later chapters.) Example: Output all Java System properties (same as previous slide) for (Object propertyname : propertynames) { String propertyvalue = System.getProperty((String)propertyName); System.out.println(propertyName + " = " + propertyvalue); Software Development 1 // 2018W // 30
31 THINGS TO CONSIDER WHEN WRITING LOOPS Loops can be nested indefinitely, however you should be careful: this can easily lead to an immense amount of repetitions: for (int i = 0; i < 1000; i++) for (int j = 0; j < 1000; j++) for (int k = 0; k < 1000; k++) instruction; In this case, instruction will be executed times! Infinite loops will make your program hang. Try to avoid them. Some examples: for (;;) ; while (true) ; for (int i = 0; i!= 5; i += 2) System.out.println(i); Software Development 1 // 2018W // 31
32 BREAK AND CONTINUE LOOPS while ( condition ) { instructions ; continue; instructions ; break; instructions ; continue will immediately redirect the control flow to the end of the loop and begin evaluating the condition again. break terminates the loop and resumes execution after the loop. Jumps like these will usually make your code hard to read, try to use them only where absolutely necessary. Software Development 1 // 2018W // 32
33 BREAK AND CONTINUE LOOPS // Enter numbers until the total exceeds 50. As soon as the total // exceeds 20, a subtotal should be displayed. int total = 0; do { System.out.print("Enter a number: "); total += Input.readInt(); // leave loop, when 50 is reached if (total > 50) break; // if the total is still below 20, jump to the beginning of // the loop, to avoid displaying the subtotal if (total <= 20) continue; System.out.println("Subtotal: " + total); while (total <= 50); System.out.println("Total: " + total); // Identical program without break, continue: total = 0; do { System.out.print("Enter a number: "); total += Input.readInt(); if (total > 20 && total <= 50) System.out.println("Subtotal: " + total); while (total <= 50); System.out.println("Total: " + total); break, continue is here not necessary! SWE1.03 / BreakSample1.java Software Development 1 // 2018W // 33
34 LABELED STATEMENTS If several loops are nested, it can necessary to label them: label: loop label is any identifier, and it is only visible within the loop. break label terminates the according loop. continue label resumes with the condition of the according loop. If break or continue are used without specifying a label (as it is mostly the way), it always means the inner most loop. Software Development 1 // 2018W // 34
35 LABELED STATEMENTS :: EXAMPLE // 2-dim. array [y-axis][x-axis] with sensor data double[][] sensordata = { { 1, 2, 3, {-1, 0, 1, {-5, -3, -2; // Check if the array contains a negative value. // Stop looking as soon as one has been found. boolean foundnegative = false; yloop: for (int iy = 0; iy < 3; iy++) { for (int ix = 0; ix < 3; ix++) { if (sensordata[iy][ix] < 0) { foundnegative = true; break yloop; break requires label, otherwise it would only leave the inner loop. if (foundnegative) System.out.println("Found a negative value."); else System.out.println("All is well..."); SWE1.03 / BreakBsp2.java Software Development 1 // 2018W // 35
36 VISIBILITY OF LOCAL VARIABLES { //... int a; test: for (a = 0; a < 100; a++) { int b; for (int c = 0; c < a; c++) { System.out.println(a * c); int d = 7; System.out.println(a * d); a is visible test is visible b is visible c is visible d is visible Software Development 1 // 2018W // 36
37 LOOPS :: EXAMPLES // Application to show the ASCII Charset public class ShowCharset { public static void main(string[] args) { System.out.println("ASCII Charset:"); for (int i = 2; i < 8; i++) { for (int j = 0; j < 16; j++) { char c = (char) (16 * i + j); System.out.print(c); System.out.println(); ASCII Charset: Char codes are defined, but 0 31 are control characters which we do not want to display SWE1.03 / ShowCharset.java Software Development 1 // 2018W // 37
38 LOOPS :: EXAMPLES public class FactorialLoops { public static void main(string[] args) { int n = 5; int factorial = 1; //calculate n! with for-loop for (int i = 1; i <= n; i++) factorial = factorial * i; System.out.println(n + "! = " + factorial); factorial = 1; //calculate n! with while-loop int i = 1; while (i <= n) { factorial = factorial * i; i++; System.out.println(n + "! = " + factorial); factorial = 1; //calculate n! with do-while-loop i = 1; do { factorial = factorial * i; i++; while (i <= n); System.out.println(n + "! = " + factorial); SWE1.03 / FactorialLoops.java Software Development 1 // 2018W // 38
39 SOFTWARE DEVELOPMENT 1 Control Structures 2018W (Institute of Pervasive Computing, JKU Linz)
Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;
Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationCOMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements
COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationCSE 114 Computer Science I
CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationReview. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char
Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in
More informationswitch-case Statements
switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;
More informationLoops. CSE 114, Computer Science 1 Stony Brook University
Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?
More informationFlow Control. CSC215 Lecture
Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationLoops / Repetition Statements
Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for
More informationDate: Dr. Essam Halim
Assignment (1) Date: 11-2-2013 Dr. Essam Halim Part 1: Chapter 2 Elementary Programming 1 Suppose a Scanner object is created as follows: Scanner input = new Scanner(System.in); What method do you use
More informationCOMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.
More informationControl Structures in Java if-else and switch
Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification
More informationIn this chapter, you will:
Java Programming: Guided Learning with Early Objects Chapter 4 Control Structures I: Selection In this chapter, you will: Make decisions with the if and if else structures Use compound statements in an
More informationSchool of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15
Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL
More informationRepetition, Looping. While Loop
Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions
More informationChapter 4: Control Structures I
Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted
More information10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS
JAVA CONTROL STATEMENTS Introduction to Control statements are used in programming languages to cause the flow of control to advance and branch based on changes to the state of a program. In Java, control
More informationChapter 3. Selections
Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of
More informationConditionals, Loops, and Style
Conditionals, Loops, and Style yes x > y? no max = x; max = y; http://xkcd.com/292/ Fundamentals of Computer Science Keith Vertanen Copyright 2013 Control flow thus far public class ArgsExample public
More information3chapter C ONTROL S TATEMENTS. Objectives
3chapter C ONTROL S TATEMENTS Objectives To understand the flow of control in selection and loop statements ( 3.2 3.7). To use Boolean expressions to control selection statements and loop statements (
More informationBuilding Java Programs Chapter 2
Building Java Programs Chapter 2 Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. Data types type: A category or set of data values. Constrains the operations that can
More informationSOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)
SOFTWARE DEVELOPMENT 1 Operators 2018W (Institute of Pervasive Computing, JKU Linz) OPERATORS Operators are required to form expressions. Depending on the number of operands they take, they are called:
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted
More informationL o o p s. for(initializing expression; control expression; step expression) { one or more statements }
L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat
More informationConditional Programming
COMP-202 Conditional Programming Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2 Introduction So far,
More informationExpression statements are formed by adding a semicolon to the end of certain types of expressions.
Expression statements are formed by adding a semicolon to the end of certain types of expressions. Variable declaration statements declare variables. int width, height, area; String hello = "Hello, world!";
More informationLe L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements
Course Name: Advanced Java Lecture 3 Topics to be covered Control Statements Introduction The control statement are used to control the flow of execution of the program. This execution order depends on
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationCONDITIONAL EXECUTION
CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Conditional Execution if then if then Nested if then statements Comparisons
More informationConditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression
Conditionals, Loops, and Style Control flow thus far yes no x > y? max = x; max = y; public class ArgsExample time 0 String product = args[0]; time 1 int qty = Integer.parseInt(args[1]); time 2 double
More informationIntroduction to Java & Fundamental Data Types
Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains
More informationBuilding Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.
Building Java Programs Chapter 2 bug Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. 2 An Insect Software Flaw 3 4 Bug, Kentucky Bug Eyed 5 Cheesy Movie 6 Punch Buggy
More informationBuilding Java Programs Chapter 2
Building Java Programs Chapter 2 Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. bug 2 An Insect 3 Software Flaw 4 Bug, Kentucky 5 Bug Eyed 6 Cheesy Movie 7 Punch Buggy
More informationFlow of Control: Loops. Chapter 4
Flow of Control: Loops Chapter 4 Java Loop Statements: Outline The while statement The do-while statement The for Statement Java Loop Statements A portion of a program that repeats a statement or a group
More informationPROGRAMMING FUNDAMENTALS
PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write
More informationChapter 7. Additional Control Structures
Chapter 7 Additional Control Structures 1 Chapter 7 Topics Switch Statement for Multi-Way Branching Do-While Statement for Looping For Statement for Looping Using break and continue Statements 2 Chapter
More informationJava+- Language Reference Manual
Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect
More informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationLogic is the anatomy of thought. John Locke ( ) This sentence is false.
Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than
More informationExercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014
Exercises Software Development I 05 Conversions and Promotions; Lifetime, Scope, Shadowing November 5th, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More informationChapter 3 Selection Statements
Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are
More informationIntroduction to the Java Basics: Control Flow Statements
Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared
More informationControl Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003
Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an
More informationCondi(onals and Loops
Condi(onals and Loops 1 Review Primi(ve Data Types & Variables int, long float, double boolean char String Mathema(cal operators: + - * / % Comparison: < > = == 2 A Founda(on for Programming any program
More informationThe Basic Parts of Java
Data Types Primitive Composite The Basic Parts of Java array (will also be covered in the lecture on Collections) Lexical Rules Expressions and operators Methods Parameter list Argument parsing An example
More informationSchool of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn
CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...
More informationIn Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.
CS101, Mock Boolean Conditions, If-Then Boolean Expressions and Conditions The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in
More informationWarmup : Name that tune!
Warmup : Name that tune! Write, using a loop, Java code to print the lyrics to the song 99 Bottles of Beer on the Wall 99 bottles of beer on the wall. 99 bottles of beer. Take one down, pass it around,
More informationExam 2, Version 2. For the following code, mark True or False for statements 1.8 to 1.10.
1. True or False (clearly write True or False on each line). 1.1. It s possible for the body of a do-while loop to execute zero times F For the following code, mark True or False for statements 1.8 to
More informationIntroduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017
Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationCOMP 202 Java in one week
CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language
More informationChapter 4. Flow of Control
Chapter 4. Flow of Control Byoung-Tak Zhang TA: Hanock Kwak Biointelligence Laboratory School of Computer Science and Engineering Seoul National Univertisy http://bi.snu.ac.kr Sequential flow of control
More informationBuilding Java Programs
Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 2 Data and expressions reading: 2.1 3 The computer s view Internally, computers store everything as 1 s and 0
More informationPlease answer the following questions. Do not re-code the enclosed codes if you have already completed them.
Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?
More informationControl Structures. Lecture 4 COP 3014 Fall September 18, 2017
Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls
More informationSelection as a Control Structure
Java the UML Way http://www.tisip.no/javatheumlway/ version 2002-04-17 Selection as a Control Structure Control structures page 2 The Calculator class with a client program page 3-5 Blocks inside methods
More informationMidterm Examination (MTA)
M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and
More informationBasic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java
Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 10 For Loops and Arrays Outline Problem: How can I perform the same operations a fixed number of times? Considering for loops Performs same operations
More informationWrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321
Wrapper Classes To treat values as objects, Java supplies standard wrapper classes for each primitive type. For example, you can construct a wrapper object from a primitive value or from a string representation
More informationEXERCISES SOFTWARE DEVELOPMENT I. 03 Control Flow & Branching Statements if/switch, while/do-while/for 2018W
EXERCISES SOFTWARE DEVELOPMENT I 03 Control Flow & Branching Statements if/switch, while/do-while/for 2018W 1 st Test I INFORMATION FOR THE 1ST TEST General information Date: Monday, November 12, 2018;
More informationSTUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode
STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming (Spring 2012) Lecture #8: More on Conditional & Loop Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements:
More informationFlow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators
Flow of Control of Program Statements CS 112 Introduction to Programming (Spring 2012) q Java provides two types of program flow of control statements: decision statements, or conditional statements: decide
More informationReview for Test 1 (Chapter 1-5)
Review for Test 1 (Chapter 1-5) 1. Introduction to Computers, Programs, and Java a) What is a computer? b) What is a computer program? c) A bit is a binary digit 0 or 1. A byte is a sequence of 8 bits.
More informationJava Basic Programming Constructs
Java Basic Programming Constructs /* * This is your first java program. */ class HelloWorld{ public static void main(string[] args){ System.out.println( Hello World! ); A Closer Look at HelloWorld 2 This
More informationExpressions & Flow Control
Objectives Distinguish between instance and local variables 4 Expressions & Flow Control Describe how instance variables are initialized Identify and correct a Possible reference before assignment compiler
More informationProgram Control Flow
Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationProgram Control Flow
Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More information1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops
1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements
More informationSome Sample AP Computer Science A Questions - Solutions
Some Sample AP Computer Science A Questions - s Note: These aren't from actual AP tests. I've created these questions based on looking at actual AP tests. Also, in cases where it's not necessary to have
More informationExercise (Revisited)
Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price?"); 4 price = input.nextint(); 5 if (price
More informationUnit 6. Loop statements
Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now
More information1.3 Conditionals and Loops
1 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops to infinity and beyond Math primitive data types
More informationTiming for Interfaces and Abstract Classes
Timing for Interfaces and Abstract Classes Consider using abstract classes if you want to: share code among several closely related classes declare non-static or non-final fields Consider using interfaces
More informationCONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops
COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 3
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning
More informationScanner Objects. Zheng-Liang Lu Java Programming 82 / 133
Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object
More informationINTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from
INTRODUCTION TO C++ PROGRAM CONTROL Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Repetition Statement for while do.. while break and continue
More informationRepe$$on CSC 121 Fall 2015 Howard Rosenthal
Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationDefinite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting
Unit 2, Part 2 Definite Loops Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Let's say that we're using a variable i to count the number of times that
More informationConditional Execution
Unit 3, Part 3 Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Simple Conditional Execution in Java if () { else {
More informationCommon Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141
Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates
More informationIntroduction. C provides two styles of flow control:
Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if
More informationSAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1
FACULTY OF SCIENCE AND TECHNOLOGY SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1 ACADEMIC SESSION 2014; SEMESTER 3 PRG102D: BASIC PROGRAMMING CONCEPTS Section A Compulsory section Question
More informationBuilding Java Programs
Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 Data and expressions reading: 2.1 self-check: 1-4 videos: Ch. 2 #1 2 Data types type: A category or set of data
More informationOutline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors
Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A
More informationLectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1
Introduction to Computer Science Shimon Schocken IDC Herzliya Lectures 3-1, 3-2 Control Structures Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 1 Shorthand operators (increment
More informationConditionals and Loops
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
More information