Flow Control. Key Notion. Statement Categories. 28-Oct-10

Similar documents
Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

FLOW CONTROL. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

Following is the general form of a typical decision making structure found in most of the programming languages:

Control Structures in Java if-else and switch

CSE 114 Computer Science I

Control Structures in Java if-else and switch

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Flow of Control. Chapter 3 Part 3 The Switch Statement

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

In this chapter, you will:

C++ Programming: From Problem Analysis to Program Design, Third Edition

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Control Structures: if and while A C S L E C T U R E 4

Object-Oriented Programming

Introduction to the Java Basics: Control Flow Statements

Chapter 3. Selections

CompSci 125 Lecture 11

CS111: PROGRAMMING LANGUAGE II

Introduction. C provides two styles of flow control:

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

STUDENT LESSON A12 Iterations

Introduction to Java Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Loops. CSE 114, Computer Science 1 Stony Brook University

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Controls Structure for Repetition

Advanced if/else & Cumulative Sum

Java Bytecode (binary file)

PROGRAMMING FUNDAMENTALS

1 Short Answer (10 Points Each)

Repetition, Looping. While Loop

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Oct Decision Structures cont d

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Flow of Control. Chapter 3

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

The Java language has a wide variety of modifiers, including the following:

204111: Computer and Programming

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Operators Questions

Flow of Control. Chapter 3

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Java I/O and Control Structures

Decision Making in C

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Control structures in C. Going beyond sequential

Selec%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 Fall 2016 Howard Rosenthal

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Topic 14 while loops and loop patterns

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Conditional Programming

Lecture 14. 'for' loops and Arrays

Flow Control. CSC215 Lecture

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Chapter 4: Making Decisions

Chapter 4: Control structures. Repetition

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

CSC 1051 Data Structures and Algorithms I

Chapter 4: Making Decisions

CMPT 125: Lecture 4 Conditionals and Loops

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

LECTURE 04 MAKING DECISIONS

Full file at

Accelerating Information Technology Innovation

Lecture Set 4: More About Methods and More About Operators

AP COMPUTER SCIENCE A

Java Basic Programming Constructs

Chapter 4: Control structures

Java I/O and Control Structures Algorithms in everyday life

Branching. Chapter 5 11/14/16 & 11/15/16

Decisions. Arizona State University 1

CT 229 Java Syntax Continued

Programming Lecture 4

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

40 Absolute difference 42 Trying it 43 Trying it 44 Concepts covered in this chapter 0-2

Data & Variables It s elementary, my dear Riker. Sir.

Introduction to Programming Using Java (98-388)

COMP Flow of Control: Branching 2. Yi Hong May 19, 2015

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

class objects instances Fields Constructors Methods static

Programming Lecture 4

Computer Programming, I. Laboratory Manual. Final Exam Solution

Transcription:

Boaz Kantor Introduction to Computer Science, Fall semester 2010-2011 IDC Herzliya Flow Control Raistlin: This alters time. Astinus: This alters nothing...time flows on, undisturbed. Raistlin: And carries me with it? Astinus: Unless you have the power to change the course of rivers by tossing in a pebble. Raistlin: Watch, Astinus. Watch for the pebble! Key Notion No control flow = statements are executed by order of text, top to bottom Control flow = conditionally break the order: Decision-making Looping Branching Conditionally = everything is based on boolean expressions Boaz Kantor, IDC 2 Statement Categories Decision-making: if, switch, ternary Looping: while do-while for foreach (future) Branching: break; continue; return; (future) Boaz Kantor, IDC 3 1

Boolean Expressions Every expression returns either true or false. Compound expressions are evaluated according to precedence. Operators: Relational: ==!= < <= > >= Logical:! && Note: you can change variable values within boolean expressions. Study all of them: Boaz Kantor, IDC 4 Decision Making: if, if..else Allows choosing one block over the other. Syntax: if (condition) if (condition) else block2 A block can include more flow-control ( nesting ) Boaz Kantor, IDC 5 Decision Making, Example #1 if (cd) { if (--li == 0) { System.out.println( Insert coin ); if (noc >= 1) { li += 3; endgame(); else Easy to understand? Do you now comprehend the importance of styling? Boaz Kantor, IDC 6 2

Decision Making, Example #1 if (characterdied) { if (--lives == 0) { System.out.println( Insert coin ); if (numberofcoins >= 1) { lives += 3; endgame(); Indentation. What a relief! Boaz Kantor, IDC 7 Ternary operator The operator is a combination of an if..else statement and an expression. It evaluates to a value according to the condition: int years = 40; System.out.println("You are " + (years < 30? "young" : "old")); int daysinyear = (years % 4 == 0 && years % 100!= 0)? 366 : years % 400 == 0? 366 : 365; Boaz Kantor, IDC 8 Decision Making: switch Similar to if, more suitable in multi-conditional blocks. Syntax: switch (byte/short/char/int) { case val1: break; case val2: block2 break;.. default: default_block break; Boaz Kantor, IDC 9 3

Decision Making, Example #2 Scanner s = new Scanner(System.in); char choice = s.next().touppercase().charat(0); switch (choice) { case A : playagain(); break; case P : pause(); break; case N : next(); break; case Q : quit(); break; default: System.out.println( Unsupported + command ); break; Boaz Kantor, IDC 10 Decision Making, Example #2 if (choice == A ) { playagain(); else if (choice == P ) { pause(); else if (choice == N ) { next(); else if (choice == Q ) { quit(); System.out.println( Unsupported command ); Boaz Kantor, IDC 11 Fall-Through switch (month) { case 2: daysinmonth = 28; break; case 4: case 6: daysinmonth = 40; case 9: case 11: daysinmonth = 30; break; default: daysinmonth = 31; break; Boaz Kantor, IDC 12 4

Looping: while, do-while As long as condition is true, run the block over and over again. do-while runs at least once then checks while first checks then runs (hence may never run) Syntax: while (condition) block do block while (condition); Boaz Kantor, IDC 13 Looping, Example #1 boolean someonewon = true; String winner = ; do { game.playround(); winner = game.getwinnername(); someonewon =!winner.isempty(); while (!someonewon); System.out.println( The winner is: + winner); do {game.playround(); while (game.getwinnername().isempty()); Boaz Kantor, IDC 14 Looping, Example #2 int x = 1024; while (x > 2) { x /= 2; Is this the same? while ((x /= 2) > 2) { How about this one? do { while((x /= 2) > 2); Boaz Kantor, IDC 15 5

Looping: for Similar to other loops, more suitable for counting steps. Syntax: for (initialization; condition; increment) block 1 2 4 3 5 7 6 8 Boaz Kantor, IDC 16 1: 1 2: 1 2 Looping, Example #3 3: 1 3 4: 1 2 4 for (int x = 1; x <= 20; ++x) { System.out.print(x + ":"); for (int y = 1; y <= x; ++y) { if (x % y == 0) 5: 1 5 6: 1 2 3 6 7: 1 7 8: 1 2 4 8 9: 1 3 9 10: 1 2 5 10 System.out.print( + y); 11: 1 11 System.out.println(); 12: 1 2 3 4 6 12 13: 1 13 14: 1 2 7 14 15: 1 3 5 15 Boaz Kantor, IDC. Etc.. 17 Branching: break, continue, return break stops the execution of the current switch, for, while, do-while continue stops the execution of the current iteration of the loop return stops the execution of the current method (future material) Boaz Kantor, IDC 18 6

Flow Control, Overall Example private static final int M = 100; public static void main(string[] args) { boolean hd = false; int t = 0; for (int n = 3; n <= M; n++) { if (0 == n % 2) continue; hd = false; for (int d = 3; d <= Math.ceil(Math.sqrt(n)); ++d) { if (n % d == 0) { hd = true; break; if (!hd) t++; System.out.println(t); Boaz Kantor, IDC 19 http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html http://java.sun.com/docs/books/tutorial/java/nutsandbolts/flow.html TUTORIALS Following slides: - - Best practices Boaz Kantor, IDC 20 if, while, for if, general format: if (condition) { if (condition) { block2 if (condition1) { else if (condition2) { block2 while, general format: while (condition); while (condition) { do { while (condition); Boaz Kantor, IDC 21 7

for, general format: if, while, for for (init; condition; step;) { for (init; condition; step;); for (init1, init2; condition; step1, step2;) { Always use braces for controlled blocks, even if they include a single row. Bad: While (i % 2 == 0) i++; if (i % 2 == 0) i++; ------------------------ Good: if (i % 2 == 0) { i++; Boaz Kantor, IDC 22 if, while If the boolean condition is too long, prefer breaking after logical operators, then indent twice to differentiate from block code: if (a > b + 1000 && c > d.somelongmethodname() e.somemethod().somebooleanmethod()) { i++; Boaz Kantor, IDC 23 all boolean conditions In a boolean expression, use nothing or! Instead of == true or == false: Good: if (!a.somemethod()) { if (a > b) { Bad: if (a.somemethod() == false) { if (a > b == true) { Boaz Kantor, IDC 24 8

for If the condition is too long, prefer breaking after logical operators, and indent twice to differentiate from block code: for (init; a > b && c > d.somelongmethod() e < f + 50000 / g.othermethod; step;) { Boaz Kantor, IDC 25 switch, general format: switch (value) { case value1: ; break; case value2: ; break;.. default: ; break; switch Prefer writing cases in a single line, where possible switch (x) { case 1: x++; break; case 2: x++; y = x; break; case 3: { x++; y = x; z = somestaticmethod; break; default: ; break; Boaz Kantor, IDC 26 ternary operator (? )?, general format: condition? ; : block2; If nested, prefer differentiating with parentheses condition1? (condition2? : block2) : block3; Boaz Kantor, IDC 27 9

Best practices Prefer using else if over nesting. Use break even in the default case. Prefer break over boolean flags Prefer writing blocks shorter than 10 lines. If longer, consider writing a separate method. Boaz Kantor, IDC 28 Best practices Prefer writing the shorter blocks first: if (condition) { line1; line1; line2; line3; line4; Boaz Kantor, IDC 29 Best practices If an if block exits the method, omit the else block: if (condition) { line1; return true; line2; return false; if (condition) { line1; return true; line2; return false; Boaz Kantor, IDC 30 10