CSE 114 Computer Science I

Similar documents
Loops. CSE 114, Computer Science 1 Stony Brook University

Java Coding 3. Over & over again!

STUDENT LESSON A12 Iterations

Oct Decision Structures cont d

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Object Oriented Programming. Java-Lecture 6 - Arrays

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

CS111: PROGRAMMING LANGUAGE II

Introduction to Java & Fundamental Data Types

Programming with Java

ECE 122. Engineering Problem Solving with Java

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

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

Conditionals, Loops, and Style

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Section 2.2 Your First Program in Java: Printing a Line of Text

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

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

Controls Structure for Repetition

Top-Down Program Development

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Loops. GEEN163 Introduction to Computer Programming

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

Computer Programming, I. Laboratory Manual. Final Exam Solution

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

CS111: PROGRAMMING LANGUAGE II

Course Outline. Introduction to java

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

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

Section 004 Spring CS 170 Exam 1. Name (print): Instructions:

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

AP COMPUTER SCIENCE A

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

Chapter Goals. Contents LOOPS

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 3. Selections

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Last Class. While loops Infinite loops Loop counters Iterations

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Full file at

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Java Bytecode (binary file)

1 Short Answer (10 Points Each)

Condensed Java. 12-Oct-15

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Section 2.2 Your First Program in Java: Printing a Line of Text

AP CS Unit 3: Control Structures Notes

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Repetition. Chapter 6

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Repetition. Chapter 6

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

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Computer Science is...

Exam 2, Version 2. For the following code, mark True or False for statements 1.8 to 1.10.

Condi(onals and Loops

Introduction to Software Development (ISD) Week 3

Arrays. Eng. Mohammed Abdualal

Over and Over Again GEEN163

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

1007 Imperative Programming Part II

Math Modeling in Java: An S-I Compartment Model

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

1. [3 pts] What is your section number, the period your discussion meets, and the name of your discussion leader?

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Glossary. (Very) Simple Java Reference (draft, v0.2)

APCS Semester #1 Final Exam Practice Problems

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

The for Loop. Lesson 11

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Conditional Execution

Introduction to Programming Using Java (98-388)

Introduction to Computer Science Unit 2. Exercises

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

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Bjarne Stroustrup. creator of C++

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

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

Scope of this lecture. Repetition For loops While loops

CS1150 Principles of Computer Science Loops (Part II)

CS 177 Recitation. Week 1 Intro to Java

Introduction to Computer Science Unit 2. Notes

Example: Monte Carlo Simulation 1

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Software Practice 1 Basic Grammar

Transcription:

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? Imagine 3 instructions A, B, & C Instruction C can be jump A, meaning go back to A Iteration might result in: Execute A Execute B Execute C Execute A

Why use iteration? To make our code more practical and efficient To make our code more flexible and dynamic

For Example How would we write code to print N! (factorial), where N is a number entered by the user? Without iteration (or recursion) this would be impractical! We do not know N, when we are about to write the program.

Is this practical? Without iteration or recursion: System.out.print("Enter N: "); int N = Keyboard.readInt(); int factorial = 1; if ((N == 1) (N == 0)) factorial = 1; else if (N == 2) factorial = 2 * 1; else if (N == 3) factorial = 3 * 2 * 1; else if (N == 4) factorial = 4 * 3 * 2 * 1; else if (N == 5) factorial = 5 * 4 * 3 * 2 * 1; System.out.println(factorial); Inefficient coding!

import java.util.scanner; public class FactorialPrinter public static void main(string[] args) Scanner input = new Scanner(System.in); System.out.print("Enter N: "); int N = input.readint(); int factorial = calculatefactorial(n); System.out.println(factorial); return type Using Iteration and Methods Method argument type and name public static int calculatefactorial(int n) int count = n; int fact = 1; while (count > 0) fact *= count--; return fact; return value Helper method

Can Anyone guess what 1000! is? 4023872600770937735437024339230039857193748642107146325437999104299385123986290205920442084869694048004799886 1019719605863166687299480855890132382966994459099742450408707375991882362772718873251977950595099527612087497 5462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323 9584630755574091142624174743493475534286465766116677973966688202912073791438537195882498081268678383745597317 4613608537953452422158659320192809087829730843139284440328123155861103697680135730421616874760967587134831202 5478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810 2130927612448963599287051149649754199093422215668325720808213331861168115536158365469840467089756029009505376 1647584772842188967964624494516076535340819890138544248798495995331910172335555660213945039973628075013783761 5307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892 1879602238389714760885062768629671466746975629112340824392081601537808898939645182632436716167621791689097799 1190375403127462228998800519544441428201218736174599264295658174662830295557029902432415318161721046583203678 6906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958 6526822728070757813918581788896522081643483448259932660433676601769996128318607883861502794659551311565520360 9398818061213855860030143569452722420634463179746059468257310379008402443243846565724501440282188525247093519 0620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814 9001407673104466402598994902222217659043399018860185665264850617997023561938970178600408118897299183110211712 2984590164192106888438712185564612496079872290851929681937238864261483965738229112312502418664935314397013742 8531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602 7898643211390835062170950025973898635542771967428222487575867657523442202075736305694988250879689281627538488 6339690995982628095612145099487170124451646126037902930912088908694202851064018215439945715680594187274899809 4254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105 9339838357779394109700277534720000000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000 Impossible to calculate using Java s primitive data types, instead we would have to use the BigInteger class double type can estimate up until 170! (7.257415615308004 E306)

Any exceptions? All programs need iteration one and done programs Why do they all need iteration? because the start up, then wait for the user to act Most programs work as follows: 1. Initialize variables 2. Present options to user 3. Wait for user input 4. Respond to user input 5. Go back to step 2

GUIs and Iteration Think of a GUI. How does it work? 1. Draw the GUI 2. Check for input from user 3. Respond to user input, if any 4. Go back to Step 1

Java and iteration We have 3 types of iterative statements a while loop a do while loop a for loop All 3 can be used to do similar things Which one should you use? a matter of individual preference/convenience

The while Statement Syntax Diagram: while ( boolean Expr ) Statement Statement Flowchart: false true boolean Expr Statement(s) Loop Condition Loop Body

Bracketing is again important Use either: while (boolean expression) statement; Or: Be careful NOT to put a semicolon, ;, here while (boolean expression) statement; statement;

while statement example What does this method do? public static String whatdoesthisdo(int x, char c) // null character "" String result = ""; while (x > 0) result = result + c; x--; return result; What do we get if we call: String s; s = whatdoesthisdo(5,'a'); System.out.println(s); s = whatdoesthisdo(0,'a'); System.out.println(s); AAAAA

while statement example 2 What does this method do? public static String whatdoesthisdo2(int x, char c) String result = ""; while (x > 0) result = result + c; x--; c++; return result; What do we get if we call: String s; s = whatdoesthisdo2(5, 'A'); System.out.println(s); ABCDE

while statement example 3 What does this method do? public static String whatdoesthisdo3(int x, char c) String result = ""; while (x > 0) result = c + result; x--; c++; return result; What do we get if we call: String s; s = whatdoesthisdo3(5, 'A'); System.out.println(s); EDCBA

Using a flag A flag is a boolean loop control boolean flag = true; How does it work? flag used as loop condition inside the loop, test for ending condition when condition is reached, turn flag off once turned off, loop ends

flag example public static int factorial(int N) boolean moreworkflag = true; int factorial = 1; while (moreworkflag) factorial *= N; N--; if (N == 1) moreworkflag = false; return factorial; What do we get if we call: int fact; fact = factorial(5); System.out.println(fact); 120

The do-while Statement Syntax Diagram: do Statement Statements while ( boolean Expr ) ; Flowchart: Loop Body Statement(s) Loop Condition boolean Expr false true

Bracketing is again important Use either: do statement; while (boolean expression); Or: do You MUST put a semicolon, ;, here statement; statement; while (boolean expression); NOTE: though they can be used to do similar operations, while statements and do-while statements are different Java constructs.

do while statement example What does this method do? public static String whatdoesthisdowhiledo( String result = ""; do result += c; x--; while (x > 0); return result; int x, char c) What do we get if we call: String s; s = whatdoesthisdowhiledo(5,'a'); System.out.println(s); s = whatdoesthisdowhiledo(0,'a'); System.out.println(s); AAAAA A

How could we fix this? public static String whatdoesthisdowhiledo String result = ""; if (x > 0) do result += c; x--; while (x > 0); return result; (int x, char c) Now what s the output? String s; s = whatdoesthisdowhiledo(5,'a'); System.out.println(s); s = whatdoesthisdowhiledo(0,'a'); System.out.println(s); AAAAA

Why use do while? So what s the point? For when you have a loop body that must execute at least once Example: a program menu

Console Program Menu Example String selection; PrintStream out = System.out; Scanner in = new Scanner(System.in); int counter = 0; do out.println("choose a Menu Option:"); out.println("p) Print Counter"); out.println("q) Quit"); out.print("enter: "); selection = in.nextline(); if (selection.touppercase().equals("p")) out.println("counter: " + counter++); while(!selection.touppercase().equals("q")); out.println("goodbye!");

Choose a Menu Option: P) Print Counter Q) Quit ENTER: P Counter: 0 Choose a Menu Option: P) Print Counter Q) Quit ENTER: A Choose a Menu Option: P) Print Counter Q) Quit ENTER: P Counter: 1 Choose a Menu Option: P) Print Counter Q) Quit ENTER: Q An Example Session

The for Statement Syntax Diagram: for ( Init. Operation ; boolean Expr ; Update Operation ) Statement Statement

Flowchart: The for Statement Initialization false Boolean Expr Update true Statement(s)

A for loop example public static int indexof(string s, char c) for (int i = 0; i < s.length(); i++) if (s.charat(i) == c) return i; return -1; 3-1 2 What s the output? String word = "London Calling"; int index = indexof(word, 'd'); System.out.println(index); index = indexof(word, 'x'); System.out.println(index); index = indexof(word, 'n'); System.out.println(index);

for loops and counting for loops are popular for counting loops through the indices of a string through the indices of an array (later) through iterations of an algorithm Good for algorithms that require a known number of iterations counter-controlled loops

Do you understand the order of operations? for (int i = 0; i < 10; i++) System.out.print(i); 1) int i = 0; 2) i < 10; 3) System.out.print(i); 4) i++; 5) i < 10; 6) System.out.print(i); 7) i++; 8) i < 10; 9) System.out.print(i); 10) i++; 11) i is 0 i is 1 i is 2 i is 3

Examples of for Statements int sum = 0; for (int i=1; i<=4; i++) sum = sum + i; sum i 0 1 1 2 3 3 6 4 10 5 int sum = 0; for (int j=1; j<=4; j++) sum = sum + j; j++; sum j 0 1 1 3 4 5 Be careful not to double the update of your counting variable

Examples of for Statements int product = 1; for (int i=1; i<4; i+=1) product *= i; Can be used equivalently in many cases int product = 1; for (int j = 1; j<= 3; j+=1) product *= j; product i 1 1 1 2 2 3 6 4 product j 1 1 1 2 2 3 6 4

Equivalence of Loops for ( INIT ; BOOL_EXPR; UPDATE ) LOOP_BODY INIT if ( BOOL_EXPR ) INIT while ( BOOL_EXPR ) LOOP_BODY UPDATE do LOOP_BODY UPDATE while ( BOOL_EXPR );

Are these loops equivalent? int sum = 0, count = 0; while (count < x) sum += y; count++; System.out.println("sum is " + sum); int sum = 0, count = 0; for (count = 0; count < x; count++) sum += y; System.out.println("sum is " + sum); int sum = 0, count = 0; do sum += y; count++; while (count < x); System.out.println("sum is " + sum); Test using: x = 5, y = 3 OUTPUT: Sum is 15 Sum is 15 Sum is 15 x = 0, y = 3 OUTPUT: Sum is 0 Sum is 0 Sum is 3 Not Equivalent!

Syntax Diagram: WATCH OUT! ; The empty statement if (score > 21); System.out.println("Bust! You Lose"); if (score > 21 ) System.out.println("Bust! You Lose"); else; System.out.println("Hit or Stay?"); ; This is a valid line of code that does nothing, but can create unexpected problems.

The empty statement (cont d) int sum = 0; for (int i = 1; i <= 4; i++); sum = sum + i; int sum = 0, i = 1; while (i <= 4); Infinite loop! sum = sum + i; i = i + 1; Compiler Error

Nested Loops for (int i = 1; i <= 10; i++) for (int j = 1; j <= 10; j++) int product = i*j; System.out.print(product + ); System.out.print( \n ); 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30

Beware Improper Nesting int sum = 0, count = 0; if (x > 0) do sum += y; count++; while (count < x); System.out.println(sum); IS NOT int sum = 0, count = 0; if (x > 0) do sum += y; count++; while (count < x); System.out.println(sum); This loop is regarded as a single statement

Advice: Align your brackets Indenting properly is really important: if (flag) if (flag) if (y > 0) if (y > 0) x = 0; x = 0; GOOD BAD

Local Variables and Blocks A block (a compound statement) is the set of statements between a pair of matching braces (curly brackets) A variable declared inside a block is known only inside that block it is local to the block, therefore it is called a local variable when the block finishes executing, local variables disappear references to it outside the block cause a compiler error

Local Variables and Blocks (cont d) Some programming languages (e.g., C and C++) allow the variable name to be reused outside the local block it is confusing and not recommended, nevertheless, it is allowed However, a variable name in Java can be declared only once for a method although the variable does not exist outside the block, other blocks in the same method cannot reuse the variable's name

When and Where to Declare Variables Declaring variables outside all blocks but within the method definition makes them available within all the blocks Good programming Practice: declare variables just before you use them initialize variables when you declare them do not declare variables inside loops it takes time during execution to create and destroy variables, so it is better to do it just once for loops) OK to declare loop counters in the Init field of for loops, e.g. for(int i=0; i < 10; i++) the Init field executes only once, when the for loop is first entered

Java Comments Important for you and for others wishing to use your code. Always specify author, version. For classes, explain what the class is and how it is to be used. For methods, explain what it does. For programs, explain the input and output. 2 ways to add comments // Everything after the double slashes is ignored /* Everything inside the slash star is ignored */