CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Similar documents
Chapter Goals. Contents LOOPS

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

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

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

LECTURE 5 Control Structures Part 2

CS 106 Introduction to Computer Science I

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

Introduction to Software Development (ISD) Week 3

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

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Computer Programming I - Unit 5 Lecture page 1 of 14

MIDTERM REVIEW. midterminformation.htm

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Visual Programming. Lecture 3: Loops, Arrays. Mahmoud El-Gayyar

Lecture 5: Making Decisions

CT 229 Java Syntax Continued

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

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

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

Java I/O and Control Structures

CS 302: Introduction to Programming

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

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

Loops. CSE 114, Computer Science 1 Stony Brook University

CS 106 Introduction to Computer Science I

Object-Oriented Programming in Java

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

Programming with Java

AP Computer Science A

Java I/O and Control Structures Algorithms in everyday life

CS 302: Introduction to Programming in Java. Lecture 9

Chapter 3. Selections

CS111: PROGRAMMING LANGUAGE II

Object-Oriented Programming

Full file at

ECE 122 Engineering Problem Solving with Java

Arithmetic Compound Assignment Operators

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Chapter 4: Conditionals and Loops

COMP 202 Java in one week

Control Structures in Java if-else and switch

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CS 302: INTRODUCTION TO PROGRAMMING IN JAVA. Chapter 5: Methods. Lecture 10

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

++x vs. x++ We will use these notations very often.

CompSci 125 Lecture 11

CMPT 125: Lecture 4 Conditionals and Loops

Introduction. C provides two styles of flow control:

Conditionals, Loops, and Style

Lecture 5 Tao Wang 1

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

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

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

AP Programming - Chapter 6 Lecture

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Repetition, Looping CS101

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

Control Statements: Part 1

Using Java Classes Fall 2018 Margaret Reid-Miller

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Maximization and Minimization Problems. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

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

Course Outline. Introduction to java

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Java Bytecode (binary file)

CS112 Lecture: Repetition Statements

CS 112 Introduction to Programming

CS 112 Introduction to Programming

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

CS112 Lecture: Loops

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Repetition Structures

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

Assignment 2.4: Loops

AP Computer Science Unit 1. Programs

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

ECE 122. Engineering Problem Solving with Java

Java Outline (Upto Exam 2)

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012

Introduction to Java & Fundamental Data Types

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Lecture Transcript While and Do While Statements in C++

Object Oriented Programming. Java-Lecture 1

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

Java Coding 3. Over & over again!

Question: Total Points: Score:

COMP 202. Java in one week

Repetition, Looping. While Loop

Condi(onals and Loops

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Transcription:

CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8

Hopefully the Programming Assignment #1 released by tomorrow

REVIEW The switch statement is an alternative way of writing what? How do you end a case in a switch statement? What is a better way of writing: if (b == false) //assume b is a declared and initialized boolean //do something if (1 + 2 < 3!(5 > 2*2)) evaluates to?

BRACES = Used to group blocks of code So far we use them: Group code in a class Group code in method Group code for an if/else if/else block Group code for a switch statement Code inside braces is indented with a tab (eclipse usually does this automatically for you) To auto format: Windows: control-a control-i Mac: apple-a apple-i

LOOPS Sometimes we need to run the same code multiple times, but we don't want to copy and paste our code Solution: loops 3 Types: For While Do while The for loop is used when you know from the start how many times you want to loop to run

FOR LOOP Simple example: print numbers 1 5 Could just have 5 System.out.println() calls Or: for (int i = 1; i < 6; i++) System.out.println(i);

FOR LOOP For loops are based around a loop control variable Parts of a for loop for reserved word Initialization of loop control variable Condition checking to see if the loop should continue to run Updating the loop control variable for (int i = 1; i < 6; i++) System.out.println(i);

EXECUTION OF A FOR LOOP 1. Initialize i = 1 2. Check condition is i < 6? 3. Execute Code within braces 4. Update i i now equals 2 Repeat from step 2 check condition is i < 6? for (int i = 1; i < 6; i++) System.out.println(i);

FOR LOOP Can also count down instead of up Don't have to increment by 1 for (int i = 6; i > 1; i--) System.out.println(i); for (int i = 1; i < 6; i *= 2) System.out.println(i);

SCOPE Variables declared within the loop are available only within the loop and are reinitialized every time the loop runs for (int i = 1; i < 6; i++) int x = 1; x++; System.out.println(x); System.out.println(x); System.out.println(i);

SCOPE If you want to use variables in and out of the loop, declare them before the loop int x = 0; int i; for (i = 1; i < 6; i++) x = 1; x++; System.out.println(x); System.out.println(x); System.out.println(i);

HOW MANY ITERATIONS FOR THE FOLLOWING LOOPS? for (int i = 0; i <= 10; i++) for (int i = -2; i > -10; i--) for (int i = 0; i < 100; i += 2) for (int i = -2; i < 10; i *= -1)

PRACTICE 1 Generate 100,000 random dots in a square inside which there is a tangential circle, and output the ratio of the number of dots appearing in the circle to the total number of random dots. Origin is set at the center of the circle. Diameter of the circle is 1 (side length of the square is also 1) Hint: Pythagorean equation

BREAK AND CONTINUE for (int i = 0; i < 10; i++) if (i == 5) break; for (int i = 0; i < 10; i++) if (i == 5) continue; S.O.P(i); S.O.P(i); Use break when you need to exit a loop immediately Use continue to proceed with next iteration immediately

PRACTICE 2 Palindrome Use Scanner object to read in a string Test whether the string is a palindrome.

LOOPS Sometimes we need to run the same code multiple times, but we don't want to copy and paste our code Solution: loops 3 Types: For While Do while While loops are used when you have no idea how many times the loop will run

WHILE LOOP Used when we don't necessarily know from the start how many times the loop will run We want to run it 0, 1, or many times while (boolean expression) //code to execute for each iteration

WHILE LOOP VS FOR LOOP Simple example: print numbers 1 5 for (int i = 1; i < 6; i++) System.out.println(i); int i = 1; while (i < 6) System.out.println(i); i++;

WHILE LOOP EXAMPLES while (!found && position < str.length()) char currchar = str.charat(position); if (currchar == goal) found = true; else position++; OR while (position < str.length()) char currchar = str.charat(position); if (currchar == goal) break; position++;

IFS VS WHILE LOOPS If statements Executes 0 or 1 times if (boolean expression) //code Loops Execute 0, 1 or many times while (boolean expression) //code

LOOPS Sometimes we need to run the same code multiple times, but we don't want to copy and paste our code Solution: loops 3 Types: For While Do while Do while loops are used when you know the loop should run at least once.

DO WHILE LOOP Used when we want to run the loop at least once but maybe more We want to run it 1 or many times do //code to execute for each iteration while (boolean expression); //Remember there is a ; at the end of the while!

FOR VS WHILE VS DO WHILE Simple example: print numbers 1 5 For: for (int i = 1; i < 6; i++) System.out.println(i); int i = 1; do Do: System.out.println( i); i++; while (i < 6); While: int i = 1; while (i < 6) System.out.println(i); i++;

DO WHILE LOOP EXAMPLES Reading input: double weight = -1; do System.out.print("Enter Weight (>= 0): "); if (in.hasnextdouble()) else weight = in.nextdouble(); System.out.println("Please enter a double"); in.nextline(); //Need to clear the input buffer! while (weight < 0);

NESTED LOOPS Loops can be nested in the same way if statements can be Remember that code will run in sequence Ex. for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) System.out.println("Hello"); How many times will Hello be printed?

SCANNER ANNOYANCES (DEMO) From the API: next(), nextint(), nextdouble() skip any input that matches the delimiter pattern and then attempt to return the next token (word/int/double) nextline() - Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. Eclipse Demo for next(), nextint(), nextdouble() and nextline()

PRACTICE 3 Write a program to assist an instructor in calculating grades for a single student Input: multiple scores (each out of 100), -1 to quit Example input: 77(then hit enter) 90(then hit enter) 57( ) 88( ) - 1( ) Output: The number of scores entered The sum of all scores entered Highest single score Average score Don't count the -1 as a valid score! 1). Validate input type (must be int); 2). Scores must be 0<= scores <= 100 which should be checked by the program!!