CS 106 Introduction to Computer Science I

Similar documents
CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

Introduction. C provides two styles of flow control:

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

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

Repetition, Looping CS101

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Conditions, logical expressions, and selection. Introduction to control structures

CS 106 Introduction to Computer Science I

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Introduction to the Java Basics: Control Flow Statements

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

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

CS111: PROGRAMMING LANGUAGE II

Repetition CSC 121 Fall 2014 Howard Rosenthal

Math Modeling in Java: An S-I Compartment Model

Lecture Transcript While and Do While Statements in C++

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

STUDENT LESSON A12 Iterations

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

CS 106 Introduction to Computer Science I

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

Repetition, Looping. While Loop

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

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

CS 206 Introduction to Computer Science II

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

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

Java Review. Fundamentals of Computer Science

COMP-202 Unit 4: Programming with Iterations

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

Unit 1 Lesson 4. Introduction to Control Statements

REPETITION CONTROL STRUCTURE LOGO

CS112 Lecture: Loops

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

1007 Imperative Programming Part II

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

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

CS 106 Introduction to Computer Science I

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Java Coding 3. Over & over again!

Chapter 4: Control structures. Repetition

3 The L oop Control Structure

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Lecture Set 4: More About Methods and More About Operators

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

The for Loop. Lesson 11

COMS 469: Interactive Media II

Introduction to Java & Fundamental Data Types

Chapter 4: Control structures

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Program Fundamentals

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

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

CS 106 Introduction to Computer Science I

Warmup : Name that tune!

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

Lecture Set 4: More About Methods and More About Operators

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.

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

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Control Structures in Java if-else and switch

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Chapter 5: Control Structures

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

Scope of this lecture. Repetition For loops While loops

CS302: Self Check Quiz 2

Flow Control. CSC215 Lecture

Chapter 4 Introduction to Control Statements

CS112 Lecture: Repetition Statements

Chapter 4: Conditionals and Loops

Conditionals, Loops, and Style

(Refer Slide Time: 00:26)

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

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

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

cs1114 REVIEW of details test closed laptop period

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

LECTURE 5 Control Structures Part 2

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

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

Iteration statements - Loops

CT 229 Java Syntax Continued

Building Java Programs Chapter 2

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

Controls Structure for Repetition

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

Principles of Computer Science I

Transcription:

CS 106 Introduction to Computer Science I 06 / 04 / 2015 Instructor: Michael Eckmann

Today s Topics Questions / comments? Calling methods (noting parameter(s) and their types, as well as the return type) Logical operators (on booleans) switch statement Loops while for do while

Review Method call Parameter What a method returns How to capture what a method returns Packages / classes / methods

method terminology void another type in Java which is used when no value is needed.

method terminology Parameter methods have 0 or more parameters. These specify what types of values are used when a method call is made. Calling a method invoking a method by giving its name in a statement in your program: e.g. System.out.println( Hey ); // method call for println method height = Integer.parseInt(height_str); // method call for parseint method Note: A String is being passed in as a parameter for println. Same for parseint.

method terminology Return type of a method This is what type the result of a method call gives. e.g. System.out.println( Hey ); // nothing is returned (void) height = Integer.parseInt(height_str); // an int is returned The return type and number of parameters and types are all specified in the definition of a method. For the Java API methods, we can look this stuff up online.

Not! And & or && Or or Logical operators The double ones (&& and ) are short circuit operators --- if left operand is sufficient to determine truth or falsity, then the right operand is not evaluated. The single ones (& and ) always evaluate both operands. This really only matters if you have side-effects, e.g. Like a ++ or --

Logical operators Precedence first!, then && then. Parentheses are still performed first. Should be used to force the order that the programmer desires. Not operator,!, takes one operand to its right. And operator, &&, works on two operands Or operator,, works on two operands

NOT:!true = false,!false = true Logical operators AND: true && true = true true && false = false false && true = false false && false = false OR: true true = true true false = true false true = true false false = false

Logical operators Examples: boolean end_of_file = false; //... if (! end_of_file) //... if (!(age >=21)) //...

Logical operators if (!(age >=21)) //... // how else might we write the above? if ((age <= 12) (age >= 65)) // get a discount at the movies... if (you_are_rich && you_are_good_looking) System.out.println( You got it made. ); // what types must you_are_rich and you_are_good_looking, be?

Logical operators if ((age >=21) && (++count > 10)) //... here if age is not >= 21 then regardless of what's on the right hand side of the &&, the whole thing will be false (because false AND anything = false), because && is the short circuit format of the AND operator, (++count > 10) will not be evaluated. if ((age >=21) & (++count > 10)) //... here, even if age is not >= 21 the right hand side WILL be evaluated What's the difference in the result?

Logical operators && (short circuit AND) vs. & (non-short circuit AND) if ((age >=21) && (++count > 10)) //... if ((age >=21) & (++count > 10)) //... The difference is, that 1 will be added to count (and compared to 10) regardless of whether or not age is >= 21 in the second if, but in the first if, 1 will be added to count (and compared to 10) only if age is indeed >=21.

Logical operators if ((height >= 72) (countpeople() <= 100)) //... here if height is >= 72, then the whole condition is guaranteed to be true (because true OR anything = true) and the causes the right hand side NOT to be evaluated. Therefore, the method countpeople() would not be called if ((height >= 72) (countpeople() <= 100)) //... here even if height is >=72, the righthand side WILL be evaluated because of the use of the non-short circuit OR.

Logical operators (short circuit OR) vs. (non-short circuit OR) if ((height >= 72) (countpeople() <= 100)) //... if ((height >= 72) (countpeople() <= 100)) //... The difference is, that countpeople() method will ALWAYS be called in the second if but won't be called in the first if if the left hand side evaluates to true

Logical operators if ((height >= 72) (countpeople() <= 100)) //... Would countpeople() be called (and it's returned value compared to 100) if height happens to be < 72? Why or why not?

Logical operators if ((height >= 72) (countpeople() <= 100)) //... Would countpeople() be called (and it's returned value compared to 100) if height happens to be < 72? Why or why not? Yes it would because the LHS being false doesn't determine the outcome of the whole condition, even though we are using the short-circuit version of OR.

Logical operators if ((age >=21) && (++count > 10)) //... Would ++count > 10 occur if age is >= 21? Why or why not?

Logical operators if ((age >=21) && (++count > 10)) //... Would ++count > 10 occur if age is >= 21? Why or why not? Yes it would because the LHS being true doesn't determine the outcome of the whole condition, even though we are using the && short-circuit version of AND.

switch (some_var) { } Switch case 1: // do stuff if some_var's value is 1 break; case 2: // do stuff if some_var's value is 2 break; default: // do stuff if none of the cases executed.

Switch break; // this statement exits out of the curly braces in which is it enclosed and program continues after the } let's write some code showing an example use of switch to emulate a menu like, 1. print *'s 2. print $'s 3. print @'s 4. print!'s

Switch Important comments about switch. The value in the switch is compared in order to the cases. If it is unequal to a case, it gets compared to the case below it and so on. When/if it gets to an equal case, then the code within that case is executed and if there is no break, the code in lower cases continues to be executed until a break statement or the }. BE CAREFUL about putting break; statements in. Unless you're trying to do something fancy, they should be used at the end of each case. If the value in the switch doesn't equal any of the cases, the optional default case executes.

while loops While loops are used to repeat lines of code until some condition is met. e.g. while (condition) { // statements to do while condition is true. } condition is evaluated and if true the code within the curly braces executes. Then condition is tested again and if true the code within the curly braces executes. This continues until the condition is false (or a break; statement is hit.)

while loops It's extremely important for you to know exactly what code is executed in what order for you to be able to follow what a program is doing. Let's follow the code below line by line in order. (assume that it is inside a main method of a class.) int x = 1; System.out.println( Just before the loop ); while (x < 4) { } System.out.print( * ); x++; System.out.println( \njust got out of the loop );

int total = 0; while (total < 100) { } while loops total = total + 10; System.out.println( total = + total); System.out.println( finished printing totals ); // What would this code do?

while loops Sentinel controlled loops vs. counter controlled loops. Counter controlled loops are those loops that usually execute a set number of times every time. A sentinel is a value that is used to terminate a loop. For instance, if you wanted a user to enter in some numbers (but you didn't know how many s/he was going to enter) to be averaged (and assuming that they are all supposed to be positive) we can ask the user to enter in -1 after s/he enters all the numbers so we know s/he's finished. Let's see an example.

while loops int inputnum=0, count = 0; String inputstr; double total = 0.0; while (inputnum!= -1) { } inputstr = JOptionPane.showInputDialog( Enter a number to be averaged ); inputnum = Integer.parseInt(inputStr); total += inputnum; count++; System.out.println( average = + (total / count)); // any problems with this code???? Hint: yes there's a logic error.

while loops Sentinel controlled loops vs. counter controlled loops. Counter controlled loops are those loops that usually execute a set number of times every time. As a programmer what value makes sense to choose as the sentinel is specific to the situation. Could anyone characterize what would be a bad value to choose as the sentinel?

while loops Order of execution of a while loop. First the condition is tested. If it is true the statements within the curly braces execute Then condition is tested again If it is true the statements within the curly braces execute again Then condition is tested again... This continues until the condition is false when tested. At that time, program control continues with the code after the right curly brace. Note: It IS possible that even on the first test of the condition, that it may be false. If it is, the statements within the loop don't execute at all.

while loops What happens to loops that do not alter the value of a variable in the condition?

while loops What happens to loops that do not alter the value of variable(s) in the condition? If that condition is true the first time, it will stay true forever and we will have an infinite loop. e.g. int x = 2; while (x > 0) { System.out.println( x = + x); }

while loops Any other ways to get an infinite loop?

Would this be infinite? while loops int x = 2; while (x > 0) { System.out.println( x = + x); x++; }

Loop terminology We say that a loop iterates some number of times. One iteration of a loop is one execution of the block of code inside it.

for loops The for loop is a counter controlled repetition structure that compactly lets a programmer specify the control variable, its initial value, the condition to be checked each time through the loop and the amount to increment (or decrement) the control variable for ( expression1; expression2; expression3 ) statement or compound statement

for loops for ( expression1; expression2; expression3 ) statement or compound statement where expression1 contains the declaration and initialization of the control variable expression2 contains the continuation condition and the ending value of the control variable expression3 contains the increment or decrement of the control variable (and the amount of this change in value each time through the loop)

for loops 1 4 for ( expression1; expression2; expression3 ) { 2 } statements 3 (if 2 was true) Order of operations: 1. expression1 executes first (and only once) 2. expression2 executes and if the result is false, program control goes to the code after the right curly brace 3. if the result is true, then the statements within the curly braces of the for loop execute in order then expression3 executes (which usually alters the value of the loop variable.) Then goto 2 above.

for loop example for ( int x = 10; x >= 1; x-- ) { do some statements here... } note that we used x-- to subtract 1 from the counter each time through the loop, we could have used: x = x - 1 or x -= 1 or --x

for loop Each of the three expressions in the for loop structure are optional. don t need expression1 if control variable declared and initialized before the loop don t need expression2 if you desire having an infinite loop don t need expression3 if you change the value of the control variable within the loop

for loop for ( int cntr = 1; cntr <= 20; cntr = cntr + 1 ) { do some statements here... } this is essentially the same thing as the following while loop int cntr = 1; while ( cntr <= 20 ) { do some statements here... cntr = cntr + 1; } except, the variable cntr is not available to the program after the for loop, but it is available to be referenced after the while loop

exercise Write an application that calculates the product of the odd integers from 1 to 15 and then displays the results in a message dialog. Let's write it using a while loop Then let's write it using a for loop

do while loops While loops and for loops all have the possibility of having the statements inside them execute zero or more times. Zero being the key word here. When would it be possible for those loops to execute zero times? The big difference between those kinds of loops and dowhile loops are that do-while loops execute their statements at least once (that is, one or more times.)

do { statements to do } while (condition); do while loops In this kind of loop, the condition is tested after the loop executes the first time. If the condition is true it does the statements again, and so on until the condition is false.

do while loops do { statements to do 1,3 (if 2 was true) } while (condition); 2 In this kind of loop, the condition is tested after the loop executes the first time. If the condition is true it does the statements again, and so on until the condition is false.

do while loops int cntr = 1; while ( cntr <= 20 ) { } do some statements here... cntr = cntr + 1; // the above is basically equivalent to: int cntr = 1; do { do some statements here... cntr = cntr + 1; } while (cntr <= 20);

break; We've seen how break; reacts in switch statements. break; acts similarly within the curly braces of a while loop, for loop or do-while loop. It terminates the loop and program control continues after the loop as if it ended normally.

break; int x = 0; while (x <= 10) { if (x == 5) break; System.out.println( x = + x); x++; } // what's this code going to do?