Iteration statements - Loops

Similar documents
Repetition, Looping. While Loop

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

Loops. CSE 114, Computer Science 1 Stony Brook University

CS1150 Principles of Computer Science Loops (Part II)

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

Repetition, Looping CS101

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

Controls Structure for Repetition

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

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

REPETITION CONTROL STRUCTURE LOGO

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

STUDENT LESSON A12 Iterations

Example: Monte Carlo Simulation 1

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

Chapter 4: Control structures. Repetition

Repetition CSC 121 Fall 2014 Howard Rosenthal

Loops / Repetition Statements

Problem Solving With Loops

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

Introduction. C provides two styles of flow control:

Chapter 4: Control structures

Some Sample AP Computer Science A Questions - Solutions

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

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

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

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

IST 297D Introduction to Application Programming Chapter 4 Problem Set. Name:

CMPT 125: Lecture 4 Conditionals and Loops

Loops. GEEN163 Introduction to Computer Programming

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

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

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

Important Java terminology

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

Top-down programming design

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

Repetition Structures

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

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Computer Programming I - Unit 5 Lecture page 1 of 14

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

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

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

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

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

CS110D: PROGRAMMING LANGUAGE I

Top-Down Program Development

CS111: PROGRAMMING LANGUAGE II

Recap: Assignment as an Operator CS 112 Introduction to Programming

Introduction to the Java Basics: Control Flow Statements

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

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

Over and Over Again GEEN163

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

CompSci 125 Lecture 11

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

Chapter 3. Selections

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

Loops and Expression Types

Chapter Goals. Contents LOOPS

CS 112 Introduction to Programming

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Bjarne Stroustrup. creator of C++

Loops (while and for)

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Repetition with for loops

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Why Is Repetition Needed?

Chapter 4 Introduction to Control Statements

Assignment 2.4: Loops

Control Structures II. Repetition (Loops)

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Introduction to Java & Fundamental Data Types

CS 177 Week 5 Recitation Slides. Loops

Scope of this lecture. Repetition For loops While loops

COMP-202 Unit 4: Programming with Iterations

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

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

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

Loops. Repeat after me

COMP 202 Java in one week

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

CSC 1051 Data Structures and Algorithms I

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

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

Warmup : Name that tune!

1 Short Answer (10 Points Each)

Java Coding 3. Over & over again!

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

CS 106 Introduction to Computer Science I

ECE 122. Engineering Problem Solving with Java

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

Transcription:

Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or more statements as long as a condition exist. Each repetition statement request : ) מונה הלולאה / משתנה הלולאה ( counter 1. a control variable/loop 2. the initial value of control variable 3. the increment (decrement) by which the control variable is modified each time through the loop 4. the loop continuation condition that determines if looping should continue. 1

Basic elements of iterations /* example with the while statement prints numbers from 1 through 10 */ public class While_Test1 public static void main(string[ ] args) int counter = 1; while(counter <= 10) System.out.print(counter); counter++; System.out.println(); Declare and initialize control variable Loop continuation condition Increment control variable by 1 2

Loop structures?? Do-while structure While structure 3

While loop statement while (loop-continuation-condition) // loop-body; Statement(s); int count = 0; while (count < 100) System.out.println("Welcome to Java!"); count++; count = 0; Loop Continuation Condition? false (count < 100)? false true Statement(s) (loop body) true System.out.println("Welcome to Java!"); count++; (A) 4 (B)

This program section reads a series of integers and computes their average. We designate zero to be a sentinel ( זקיף ( value that indicates the end of the input. A sentinel must always be outside the normal range of values entered. int sum=0,num,count=0;// sum of series, input variable and loop counter double avg; // average of series System.out.println( enter an integer ( 0 to quit) : ); num=reader.nextint(); while (num!= 0) count++; sum+=num; System.out.println( enter an integer ( 0 to quit) : ); num=reader.nextint( ); Casting avg=(double)sum/count; System.out.println( The average is : +avg); Sentinel value of 0 to terminate loop. Sentinel value is not counted. 5

While loop example 1 Input : Two integers num1 and num2 Output : How many times num1 contains num2 This is the result of the integer division num1/num2 Note : Do not use the division operator ( / )! 6

Solution public class Ex1While static Scanner reader = new Scanner(System.in); public static void main(string[ ] args) int res=0; // help variable System.out.println( enter two integers : ); int num1=reader.nextint(); Declaration during input int num2=reader.nextint(); while ( (res+1) * num2 <= num1) res ++; Every iteration res is incremented by 1 System.out.println( num1 contains num2 : +res+ times ); 7

While loop example 2 This program reads an integer and? public class Ex2While static Scanner reader = new Scanner(System.in); public static void main(string[ ] args) int res=0; //? System.out.println( enter a positive number: ); int num=reader.nextint(); while ( num>0) res +=num%10; num/=10; System.out.println( res= : +res); 8

Infinite loops It is the programmer s responsibility to ensure that the condition of a loop will eventually become false. If it doesn t, the loop body will execute forever. ). לולאה אין סופית loop( This situation, called an infinite Example 1: Example 2: int count=1; double num=2.0; while (count!=50) while ( num!=0.0) count+=2; num=num - 0.1; This loop will never terminate because count will never equal 50. This loop will never terminate because num will never have a value exactly equal to 0.0 9

FOR loop statement Equivalent to while Any for loop can be converted to while loop and vice versa. If we want to perform something for a predefined number of times, better use for. If we just wait for something to happen (not after a certain number or iterations), better use while. The for loop has three expressions that are contained within parentheses and separated with a semicolon. 10

Loop for - structure program statements before the for loop for ( Initialization ; ; Conditional ; Iteration ) for loop header for loop body program statements after for loop 11

Loop for order of execution Three kinds of for loop header expressions initialization Initialization is executed only once iteration conditional true For loop body false Before the loop begins the first part of the header, called initialization, is executed. The second part of the header is the boolean condition, which is evaluated before the loop body. If true,the body is executed. The iteration part is executed after each iteration of the loop. 12

For loops example 1 This program section reads an integer and computes its factorial. int fact=1; // factorial System.out.println("enter an integer : "); int n=reader.nextint(); // input variable for (int i=1; i<=n ;i++) fact *= i; System.out.println( factorial is :" + fact); A trace table is a technique used to test programs. ) טבלת מעקב ( table Trace n i i<=n fact output Before loop execution input: 3 3 1 3 1 T 1 3 2 T 2 3 3 T 6 3 4 F 6 14

Trace table (while) public static void main(string[ ] args) int res=0; // sum of digits System.out.println( enter a positive number: ); input: 123 int num=reader.nextint( ); //num=123 while ( num>0) res +=num%10; num/=10; System.out.println( res= : +res); num>0 Num%10 res num output Before loop execution 0 123 T 3 3 12 T 2 5 1 T 1 6 0 F 6 15

For loops example 2 This program section checks if the input integer is the prime number int prime=1; / / help variable System.out.println( enter an integer : ); int x=reader.nextint(); / / input variable if (x>3) for( int i=2 ;i<x && prime==1; i++ ) if( x%i == 0) prime=0; switch (prime) case 1: case 0: / / if (x>3) System.out.println(x+" is prime number ); break; System.out.println(x+" is not prime number ); break; else System.out.println(x+" is prime number "); 16

Do while loop statement do statement(s) while (expression) ; Note that the loop begins with the reserved word do Note that the loop ends with semicolon Similar to while loops Except the condition is evaluated after the loop body. The condition is written at the end of the loop to indicate that it is not evaluated until the loop body is executed. The loop body is always executed at least once, even if the expression is never true. 17

Do while loop execution Statement(s) (loop body) true Loop Continuation Condition? false 18

Do while loop example 1 Waiting for legal input // program statement before the do while loop System.out.print( "Please, enter a positive number: ); do int num= reader.nextint(); if (i<=0) System.out.println( Input error! Try again ); while ( i<=0 ); // program statements after the do while loop 19

Do while loop example 2 This program section reads an integer and reverses its digit mathematically int reversnum = 0; // reversed number System.out.println("enter an integer : "); int num=reader.nextint( ); // input variable do int lastdigit = num%10; reversnum = (reversnum*10 )+ lastdigit; num=num/10; while (num > 0); System.out.println(" That number reversed is "+reversnum); 20

Do while loop example 3 This program section reads an integer and? int x = 1; //? System.out.println("enter an integer : "); int num=reader.nextint( ); // input variable do x *= num; while ( -- num >= 1); System.out.println(" x= + x ); 21

Fibonacci series The Fibonacci sequence is named after Leonardo of Pisa, who was known as Fibonacci. In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence: n: 0 1 2 3 4 5 6... F n : 0 1 1 2 3 5 8... F n 0 n= 0 = 1 n=1 F n 1 Fn 2 Number of element in the series + n >1 22

Fibonacci series sol. public static void main(string[ ] args) int n; // number of element in the series do System.out.print(" Enter an positive integer=> "); n=reader.nextint(); while (n < 0); int Fn2 = 0 ; int Fn1 = 1 ; int Fn = 0 ; if ( n == 1 ) Fn = 1 ; for (int ind=2 ; ind <= n ; ind++) Fn = Fn1 + Fn2; Fn2 = Fn1; Fn1 = Fn; System.out.println("Fib( + n + ")= + Fn); 23

Nested loops The body of loop can contain another loop. This situation is ). לולאות מקוננות ( loop called a nested Note, that for each iteration of outer loop, the inner loop executes completely. The next program section reads the integer number n, real number x and calculates the sum of the mathemaitc serias : 1 2 3 n x x x x 1... 1! 2! 3! n! 24

Nested loops example 1 double sum=1.0; // sum of series int f; // n factorial double h; // x degree int i=1; //loop counter System.out.print( "enter an integer : ); int n= reader.nextint(); System.out.print( "enter real number : ); double x= reader.nextdouble(); while (i<=n) ) לולאה חיצונית ( loop outer f=1; h=1.0; for (int j=1; j<=i ;j++) ) לולאה פנימית ( loop f*=j; // calculates factorial inner h*=x; // calculates x degree sum+=h/f; i++; System.out.print( "sum = : "+sum ); 25

) הוראות קפיצה statements( Jump A jump statement transfers control to another part of the program. There are two kinds of jump statements : break and continue. When break is encountered, the loop is exited regardless of whether the condition is still true. The break statement tells Java to exit a code block ( loop body) defined by opening and closing braces and used in a loop. The program then continues to run from the first line after the while/for/do while body s loop. If called within a nested loop, break breaks out of the inner loop only. When continue is encountered, the rest of the loop is ignored. The program then continues to run from the beginning of the loop. 26

Using break statement program statement before the loop loop(expression).. break;.. //end loop program statement after the loop program statement before the nested loops loop1(expression1). loop2(expression2). break;. // end loop2 // continue with loop1 // end loop1 program statement after the nested loops 27

Using continue statement program statement before the loop loop(expression).. continue;.. program statements after the loop // continue with the program Ignore executing rest of the loop s body in this iteration 28

break and continue examples Brake out of loop at i=5 Skip printing the value 5 for (int i=1; i <= 10; i++) if (i==5) break; System.out.print (i + ); System.out.println ( ); for (int i=1; i <= 10; i++) if (i==5) continue; System.out.print (i + ); System.out.println ( ); Output : 1 2 3 4 Output : 1 2 3 4 6 7 8 9 10 29

Caution Similarly, the following while loop is wrong: int i=0; while (i < 10); Error System.out.println("i is " + i); i++; In the case of the do while loop, the following semicolon is needed to end the loop. int i=0; do System.out.println("i is " + i); i++; while (i<10); Correct 30