Loops. GEEN163 Introduction to Computer Programming

Similar documents
Over and Over Again GEEN163

Using Classes. GEEN163 Introduction to Computer Programming

Bjarne Stroustrup. creator of C++

Decisions, Decisions, Decisions. GEEN163 Introduction to Computer Programming

Loops. CSE 114, Computer Science 1 Stony Brook University

Using Classes. GEEN163 Introduction to Computer Programming

Repetition, Looping. While Loop

More Methods GEEN163

Problem Solving With Loops

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

What two elements are usually present for calculating a total of a series of numbers?

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

Iteration statements - Loops

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal

Review for the Third Exam COMP163

Oct Decision Structures cont d

1 Short Answer (10 Points Each)

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

CSE 114 Computer Science I

Lesson 7 Part 2 Flags

Repetition. Chapter 6

Repetition. Chapter 6

Methods & Classes COMP163

AP CS Unit 3: Control Structures Notes

CONDITIONAL EXECUTION

A+ Computer Science -

SFWR ENG/COMP SCI 2S03 Principles of Programming SOLUTIONS

Introduction to Computer Science Unit 2. Notes

Programming with Java

Chapter 6. Repetition. Asserting Java. Rick Mercer

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

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

St. Edmund Preparatory High School Brooklyn, NY

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

COMP-202 Unit 4: Programming with Iterations

ITERATION WEEK 4: EXMAPLES IN CLASS

CSC 1051 Data Structures and Algorithms I

Java Coding 3. Over & over again!

STUDENT LESSON A12 Iterations

Full file at

AP COMPUTER SCIENCE A

CSC 1051 Data Structures and Algorithms I

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Controls Structure for Repetition

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

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

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

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Chapter 5 Lab Methods

Top-Down Program Development

Midterm Examination (MTA)

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key

Term 1 Unit 1 Week 1 Worksheet: Output Solution

Last Class. While loops Infinite loops Loop counters Iterations

Ch. 6. User-Defined Methods

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

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

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

! 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

Introduction to Computer Science Unit 2. Notes

Chapter 4: Conditionals and Recursion

Building Java Programs

Chapter 3. Ch 1 Introduction to Computers and Java. Selections

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

The action of the program depends on the input We can create this program using an if statement

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

COMP 110 Project 1 Programming Project Warm-Up Exercise

Chapter 3. Selections

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Warm-Up: COMP Programming with Iterations 1

Flow of Control: Loops. Chapter 4

Conditionals, Loops, and Style

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Example Program. public class ComputeArea {

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

CS1150 Principles of Computer Science Loops (Part II)

Building Java Programs

Chapter 1 Lab Algorithms, Errors, and Testing

Faculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)

CSC 1051 Data Structures and Algorithms I

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

CS 177 Recitation. Week 1 Intro to Java

CONDITIONAL EXECUTION

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

Example: Monte Carlo Simulation 1

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

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

Full file at

Chapter 6. Repetition. Asserting Java. Rick Mercer

Scope of this lecture. Repetition For loops While loops

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

Course Outline. Introduction to java

Arrays. Eng. Mohammed Abdualal

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

Transcription:

Loops GEEN163 Introduction to Computer Programming

Simplicity is prerequisite for reliability. Edsger W. Dijkstra

Programming Assignment A new programming assignment has been posted on Blackboard for this week The program requires you to write three programs from the given flowcharts Either problem 1 or problem 3 must be written with a GUI (but not both) Due by midnight on Friday, October 5

ZyBooks Reading Read chapter 7 of the online ZyBooks textbook Answer all of the participation questions in sections 7.1 through 7.9 Due by midnight on Thursday, October 4

One or the Other With an if else statement, either the if part or the else part are executed, but never both if ( logical expression ) { Executed only if true else { Executed only if false

nested if If the true part is another if, then it becomes a nested if if (cat == 3) else if (bull == 7) else x = 1; // cat is 3 and bull is 7 x = 2; // cat is 3 and bull is not 7 x = 3; // cat is not 3, bull doesn t matter

else if When the false part of an if-else is another if, it become an else if if ( cow > bull ) else dog = 5; if (cow == 0) dog = 3;

else if When the false part of an if-else is another if, it become an else if if ( cow > bull ) dog = 5; else if (cow == 0) dog = 3; // Java allows whitespace

One or maybe the Other With an else if statement, second if is evaluated only if the first if is false if ( logical 1 ) { Executed only if true else if ( logical 2 ){ Executed only if logical 1 is false and logical 2 is true

Connecting else to if An else statement is always related to the if of the previous block or statement if (cow == 3) if (bat == 7) dog = 1; // cow is 3 and bat is 7 else dog = 3; // cow is 3 and bat is not 7

What is displayed? int rabbit = 3, bunny = 5, hare = 7, pika = 9; if (rabbit < 4) if (bunny < hare) else pika = 2; pika = 6; System.out.println( pika ); A. 2 B. 4 C. 6 D. 9 E. none of the above

Conditional Assignment Java provides a little known method for putting an if statement in the middle of an expression logical expression? true part : false part dog = cat == 0? cow : goat; if cat is equal to zero, set dog to the value of cow, else set dog to the value of goat

Conditional Operator Example int cow= 3, cat = 5, dog = 7, goat = 17; dog = keyboard.nextint(); cow = (dog == 0? cat : goat) + 1; is the same as if (dog == 0 ) cow = cat + 1; else cow = goat + 1;

Conditional Used in a Method Call The conditional operator can be using almost any place an equation can be used System.out.println( "You "+ (score >= 50)? "pass" : "fail");

What is displayed? int wren = 2, robin = 5, hawk = 17; hawk = robin > 4? wren-1 : robin+ 2; System.out.println( hawk ); A. 1 B. 4 C. 7 D. 17 E. none of the above

Repeating Many programs do the same task many times Java provides several ways of creating a program loop while do while for

Java while statement A while statement is like an if statement that repeats until the logical expression is false int cat = 47, sum = 0; while (cat > 0) { cat = keyboard.nextint(); sum = sum + cat; System.out.println( sum );

Java while statement A while statement is like an if statement that repeats until the logical expression is false int cat = 47, sum = 0; while (cat > 0) { cat = keyboard.nextint(); sum = sum + cat; System.out.println( sum );

Loop Parts A while loop has a loop condition and a body The body is repeated while the loop condition is true while (loop condition ) { // loop body

while Flowchart comparison true false Do something

while loop operation When the program execution encounters a while statement, it will check the loop condition If the loop condition is false, the loop body will not be executed. Execution will continue with the statements after the loop body The body of the loop will be executed if the loop condition is true At the end of the body of the loop, the loop condition will be evaluated again. If it is true, the body of the loop will be executed again

{ Brackets A while loop can be written without curly brackets around the loop body Without brackets, the loop body will be the one statement following the loop condition It is recommended that you always use brackets

Example Program This is a program to display the average of a series of numbers. The end of the list of numbers is denoted by a value of zero You calculate the average by adding all the values and then dividing by the number of values

import java.util.scanner; public class LoopExample { public static void main(string[] junk) { double num, avg, sum = 0.0; int count = 0; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number"); num = keyboard.nextdouble(); while (num!= 0.0) { sum = sum + num; count = count + 1; System.out.print("Enter a number"); num = keyboard.nextdouble(); avg = sum / count; System.out.println("The avg is " + avg);

Observations about the Program The program continues until a zero is read. The while loop checks for a zero We need to both sum the numbers and count how many numbers There was a priming read before the while and another read in the while loop body You should not divide until after the loop

Maybe Never The logical expression of a while loop is tested for the first time before the statement is executed If the logical expression is false the first time, the loop is never executed int hen = 5; while ( hen < 4 ) { hen = hen * hen; System.out.println( hen );// 5

A. 2 B. 4 C. 5 D. 8 What is displayed? int dog = 2, cat = 0; while ( cat < 3 ) { dog = dog + cat; cat = cat + 1; System.out.println( dog ); E. none of the above

Infinite Loops Many students have written programs with infinite loops. These programs have a loop that will repeat forever A program with an infinite loop will appear hung or stuck It is necessary that some statement inside a while loop modifies at least one of the variables used in the while statement s logical expression

Infinite Examples int cat = 5, bird = 7; while (bird > cat) { cow = bird + cat; while (bird > cat) { bird = bird + cat;

Looping a Specified Number of Times Frequently you may want your program to loop n times. int i = 1, n = 10; double principle= 10000.0; while (i <= n) { principle = principle * 1.05; i++; System.out.println("The value is "+ principle);

Looping a Specified Number of Times Computer scientist often count starting at zero int i = 0, n = 10; double principle= 10000.0; while (i < n) { principle = principle * 1.05; i++; System.out.println("The value is "+ principle);

What is displayed? int dog = 2, cat = 0; while ( dog > 0 ) { dog = dog + cat; cat = cat + 1; System.out.println(dog); A. 2 B. 4 C. 5 D. 8 E. none of the above

Caution The following loop is wrong because of the semicolon int i=0; Logic Error while (i < 10); { System.out.println("i is " + i); i = i + 1; 33

Flowchart Symbols while (dog == cat) dog = cat if( dog > 5 ) dog > 5 System.out.println(cow); goat = keyboard.nextint(); Output: cow input: goat

Flowchart to Find the Biggest

Java Program to Find the Biggest int number, biggest = 0; System.out.print("Enter a number >"); number = keyboard.nextint(); while (number!= 0) { if ( number > biggest ) { biggest = number; System.out.print("Enter a number >"); number = keyboard.nextint(); System.out.println("biggest is "+biggest);

Practice with your Team With the students around you, write a Java segment that sums all of the whole numbers from 1 to 47

Possible Solution int num = 1; int sum = 0; while (num <= 47) { sum = sum + num; num++;

Boolean Variables A boolean variable can be set to true or false or the result of a logical expression int x=3, y=5, z=7; boolean bat = true, bird = false; bird = x > y; bat = (x!= y) && (z > y); The expression is evaluated once and the boolean variable is then set to true or false Changing x,y or z will not change the value of the boolean variables after the above equations

What is displayed? int sum = 0, number = 47; while (sum < 100) { System.out.print("Enter a number >"); number = keyboard.nextint(); sum = sum + number; System.out.println( sum ); A. 0 B. 100 C. number greater or equal to 100 D. number less than 100 E. unknown

boolean variables in IF You can use a boolean variable in an if statement without a comparison. boolean problem = false; problem = true; if ( problem ) { System.out.println("look out");

boolean variable in a while boolean bear = true; int deer = keyboard.nextint(); while (bear) { // something if ( deer is weird ) bear = false; // some more stuff deer = keyboard.nextint();

boolean Methods A method can return a boolean (true or false) value boolean close(double cat, double dog) { if ( Math.abs(cat dog) < 0.01 ) { return true; return false;

A Shorter boolean Method A comparison results in a true or false value which can be returned boolean close(double cat, double dog) { return Math.abs(cat dog) < 0.01;

Using boolean Methods A boolean method can be used in an if double cobra = 0.666, mamba = 2.0 / 3.0; if ( close( cobra, mamba ) ) { System.out.println("same"); Other boolean methods include equals, equalsignorecase and others

boolean Variables Hold Logical Values A boolean variable can only hold the value true or false true and false are keywords, not strings, but they will print as strings int cat = 3, dog = 5; boolean fish = cat < dog; dog = -1; System.out.println("fish is "+ fish); will print fish is true

What is displayed? int cat = 11, dog = 5, cow = 7, goat = 1; boolean squid; squid = dog + cow == cat + 1; A. 1 dog = 3; if (squid ) B. 5 goat = 8; C. 8 else goat = 5; D. 12 System.out.println( goat ); E. none of the above

Input Validation Using a boolean int input; boolean good = false; while (!good ) { // repeat until good input System.out.println("Enter a number from 1-5"); input = keyboard.nextint(); if (input < 1 input > 5) { System.out.println("Pay attention!!"); else { good = true;

Thinking about programs If a program has to do something many times, it will need a loop The parts of the program that are not repeated will be outside the loop If a program does something different sometimes, the program will have an if statement

Write this in Java with your team good = 0 better = number good = better? yes display better good = better better = no good + number good 2

Complete the Program import java.util.scanner; public class Root { public static void main(string unused) { Scanner keyboard = new Scanner(System.in); int good = 0, better, number; System.out.print( Enter a number > ); number = keyboard.nextint(); // your Java here System.out.println( Answer is +better);

Possible Solution import java.util.scanner; public class Root { public static void main(string unused) { Scanner keyboard = new Scanner(System.in); int good = 0, better, number; System.out.print( Enter a number > ); number = keyboard.nextint(); better = number; while (good!= better) { good = better; better = (good + number/good) / 2; System.out.println( Answer is +better);

Summations in Mathematics In mathematics you can specify a sum as sum = which is equivalent to n i=1 1 2i sum = 1 2 + 1 4 + 1 8 + + 1 2n

Summations in Java We can write the same sum in Java n sum = i=1 1 2i double sum = 0.0; int i = 1, n = something; while ( i <= n ) { sum += 1.0 / (2.0 * i); i++;

Calculating Terms A more complex summation is e x = xi i=0 i! = 1 + x + x2 2! + x3 3! + The factorial of a number n is 1*2*3* *n In this summation next term = previous term * x i

Sum in Java double x, sum, next, i = 2.0; // set x to a value sum = 1.0 + x; // first two terms next = x; while ( next > 0.0001 ) { next = next * x / i; sum += next; i = i + 1.0; // until only small changes

What while sums the numbers from low to high? int sum = 0, low = 3, high = 12, num; num = low; // which while goes here { sum = sum + num; num++; A. while ( num <= high ) B. while ( low <= high ) C. while ( num > high ) D. while ( sum!= high )

Programming Assignment A new programming assignment has been posted on Blackboard for this week The program requires you to write three programs from the given flowcharts Either problem 1 or problem 3 must be written with a GUI (but not both) Due by midnight on Friday, October 5

ZyBooks Reading Read chapter 7 of the online ZyBooks textbook Answer all of the participation questions in sections 7.1 through 7.9 Due by midnight on Thursday, October 4