Java LESSON 3 Loops.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Control Structures Corresponds with Chapters 3 and 4.
08 Deterministic iteration1May Deterministic iteration CE : Fundamental Programming Techniques.
 2002 Prentice Hall. All rights reserved Control Structures 3 control structures –Sequential structure Built into Python –Selection structure The.
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Loops 1. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved while Loop Flow.
Chapter 5 Loops.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
UCT Department of Computer Science Computer Science 1015F Iteration
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Chapter 4: Looping Structures LECTURER : MRS ROHANI HASSAN
Lecture 4b Repeating With Loops
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
The switch Statement, and Introduction to Looping
Chapter 5: Control Structures II
Loop Structures.
Chapter 4 Loops DDC 2133 Programming II.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Repetition-Counter control Loop
CiS 260: App Dev I Chapter 4: Control Structures II.
Repetition-Sentinel,Flag Loop/Do_While
JavaScript: Control Statements.
Lecture 4B More Repetition Richard Gesick
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Java LESSON 2 Operators & Conditionals
Control Structures - Repetition
Chapter 4 Control structures and Loops
Chapter 5 Control Statements
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Lesson #5 Repetition and Loops.
Java Programming Loops
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Lab5 PROGRAMMING 1 Loop chapter4.
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Java Programming Loops
Loops.
Chap 7. Advanced Control Statements in Java
Looping and Repetition
Chapter 4: Loops and Iteration
Presentation transcript:

Java LESSON 3 Loops

We now know: Sequence begin prompt user read from keyboard BEGIN add 1 print result end BEGIN PROMPT "Enter a number" INPUT number from keyboard increment number PRINT number END

We also know: Selection (aka: Conditonal) begin prompt user read number from keyboard BEGIN PROMPT "Enter a number" INPUT number from keyboard IF number > 5 PRINT "more than 5" ELSE PRINT "5 or less" END IF END true input > 5 ? false print "more than 5" print "5 or less" end

read number from keyboard New: Iteration begin prompt user read number from keyboard end input > 5 ? true false print "another one" BEGIN DO PROMPT "Enter a number" INPUT number from keyboard IF number > 5 PRINT "another one" END IF WHILE number > 5 END More about converting iteration flow chart elements to pseudo code next week

Iteration Iteration means: repeat executing a block of program code 3 iteration types implemented in Java: 'while' loops 'do' - 'while' loops 'for' loops as long as a condition is true Boolean expression

Review of Boolean Expressions 6 Comparison Operators > greater than < smaller than >= greater than or equal to <= less than or equal == equal to != not equal to && and || or ! not 3 Logical Operators if ( !(a>b) || (c>d) && (x==y) ) { // then do stuff here }

Structure of 'while' Loops while ( boolean expresion is true ) { // do stuff // do some more stuff // whatever } // end of while loop

'while' Loop Example Number is 5 Number is 4 Number is 3 Number is 2 int number= 5; while ( number >= 0 ) { System.out.println( "Number is " + number ); -- number; } // end while number >= 0 System.out.println( "End" ); Number is 5 Number is 4 Number is 3 Number is 2 Number is 1 Number is 0 End What gets printed?

Another 'while' Example int number = 1; while ( number <= 4 ) { System.out.println( number ); ....; ++ number; } // end of while loop System.out.println( "End" ); 1 2 3 4 End What gets printed?

Same 'while' Example Again (well, almost, spot the difference) int number = 1; while ( number <= 4 ) { ++ number; …. ; System.out.println( number ); } // end of while loop System.out.println( "End" ); 2 3 4 5 End What gets printed?

Incrementing (subtle weirdness….) int number = 0; while ( ++number < 5 ) { System.out.println( number ); ....; } ++ number 1. increment 2. compare 1 2 3 4 "pre - operator" int number = 0; while ( number++ < 5 ) { System.out.println( number ); ....; } number ++ 1. compare 2. increment 1 2 3 4 5 "post - operator"

Stylish Loops Alignment & indentation Numbers in loops number <= 10 while ( … ) { ...; // code here } Numbers in loops If what you really want is to execute the loop 10 times, then use ’10’: number <= 10 but don’t write: number < 11

Task (5 minutes) Add together the sequence 1 + 1/2 + 1/4 + 1/8 + ... while the terms you are adding together are larger than 1/100. Use the following variables: float total=0.0; float counter = 1.0;

Solution float total = 0.0; float counter = 1.0; while ( (1.0/counter) > (1.0/100.0) ) { total = total + 1.0/counter; counter = counter * 2.0; } System.out.println( "Sum is " + total );

Task 2 (5 minutes) Read positive integer numbers from the keyboard using UserInput.readInt() Find out if the number just entered is larger than all others before (use an 'if' statement) Input terminates when a zero has been entered Print the biggest number Use the following variables int input = 1, biggestSoFar = 0;

Solution int input=1; int biggestSoFar=0; while (input != 0) { System.out.println("Enter a number : "); input = UserInput.readInt(); if( input > biggestSoFar ) { biggestSoFar = input; } System.out.println("The biggest number was " +biggestSoFar);

'do' - 'while' Loops 6 AT LEAST ONCE ! int number = 1; do { ++number; } while ( number <= 5 ); System.out.println(number); 6 'while'-'do' loops test at beginning of loop 'do' loops test at the end of the loop the loop is always executed AT LEAST ONCE !

Increment 'n Test int number = 1; do { 1 2 System.out.println( number ); } while ( ++number <= 3 ); System.out.println( number+ " End" ); 1 2 3 4 End

Notes ( ++number <= 3 ); is the form of combined "increment and test" that experienced JAVA programmers would prefer. For now, avoid it. It is generally safer to test at the start of a loop; "while" loops are generally safer and more common than "do"-"while" loops.

Task using 'do'-'while' Read positive integer numbers from the keyboard using UserInput.readInt() Find out if the number just entered is larger than all others before (use an 'if' statement) Input terminates when a zero has been entered Print the biggest number Use the following variables int input, biggestSoFar = 0;

Solution int input; int biggestSoFar=0; do { Note the difference to the 'while' loop where we wrote: int input=1; int input; int biggestSoFar=0; do { input = UserInput.readInt(); if( input > biggestSoFar ) { biggestSoFar = input; } } while (input != 0) System.out.println("The biggest number was " +biggestSoFar);

Advanced Stuff (1 of 3) On rare occasion you want an "emergency exit" out of the (innermost) loop Use the 'break' statement while ( i > 0 ) { ....; if ( j == .... ) { break; // leave the loop } ....; } // end of the loop body System.out.println( "continues here ...");

Advanced Stuff (2 of 3) Also on rare occasions inside a loop you want to skip executing the remainder of the loop. Use the 'continue' statement. A "while" or "do"-"while" loop moves directly to the next test at the head or foot of the loop, respectively. while ( i > 0 ) { .....; if ( j == .... ) { continue; } i=i -1; // on ‘continue’ this line gets skipped

Advanced Stuff (3 of 3) On very rare occasion you want an "emergency exit" out of the entire program sort of "crashing out" that is bad, bad style, mind. Use the ‘System.exit(0)' statement if ( j == .... ) { System.exit(0); // leave program } ....;

Check your knowledge now: What is wrong here ? int a; int sum = 0; while ( a< 10 ); { sum = sum + a; a=a-1; if ( a = 5 ) { a = 9; } System.out.println( a ); // what's the output ? a=0; 'a' not initialised: 'int a=0;' ';' ---> endless loop ! correct a=a+1; endless loop: should be 'a=a+1;' if ( a==5) { Should be 'a==5' endless loop? --> no, OK 1 2 3 4 9 10

Intermediate Summary Today we have ... revised 'boolean expressions' statements introduced 'while' loops introduced 'do' - 'while' loops (looked at 'break', 'continue' and 'exit(0)')

The Problem with 'do'-Loops begin BEGIN DO PROMPT "Enter a number" INPUT number from keyboard IF number > 5 PRINT "another one" END IF WHILE number > 5 END prompt user read number from keyboard do { System.out.println("Enter number "); number = UserInput.readInt(); print "another one" if ( number > 5 ) { System.out.println( "another one" ); input > 5 ? yes } // end of if } while ( number > 5 ); no 'if' ? No sign of that in the Flow Chart! end

Solution: Use 'while' - Loops and "Read Ahead" begin Solution: Use 'while' - Loops and "Read Ahead" Prompt user and read number from keyboard BEGIN PROMPT "Enter a number" INPUT number from keyboard WHILE number > 5 PRINT "another one" END WHILE END System.out.println("Enter number "); number = UserInput.readInt(); input > 5 ? no yes print "another one" while ( number > 5 ) { System.out.println( "another one" ); System.out.println("Enter number "); number = UserInput.readInt(); Prompt user and read number from keyboard } // end of while end

New Now: 'for' - Loops Java has three types of loop structures: 'while' - loops 'do' - 'while' - loops (avoid) 'for' - loops Usually preferred when: amount of iterations is not known a priori for a known amount of iterations

Structure of the 'for' - Loop Boolean expression, evaluated before loop runs, defining when to stop Starting value of "loop variable" which has to be of integer type: (char, byte, int, long) Action performed on "loop variable" after each loop run Single set { } of curly braces for ( x=1; x<3; x ++) { System.out.println("loop no. " +x); } Keyword 'for' (all lowercase) Single set ( ) of round braces, three items, ; Body of the loop between { }

How the 'for' - Loop Works for ( x=1; x<3; x++ ) { Starting value of "loop variable", initialisation only once, before first 'round' of loop only Boolean expression, defining how often to loop. Executed before each 'round' of the loop Action performed on "loop variable" after each 'round' of the loop for ( x=1; x<3; x++ ) { System.out.println("loop no. " +x); }

'for' vs. ‘while’ Loops x=1; while ( x<3 ) { System.out.println("loop no. " +x); x++ ; } for ( x=1; x<3; x++ ) { System.out.println("loop no. " +x); }

The Output is Therefore…. 1. Initialisation of 'loop variable' to 1 "x=1;" 2. Evaluate boolean expression "1<3 ?" -->true 3. Print "loop no. 1" 4. Execute "++x". ‘x’ is now 2 5. Boolean expression "2<3 ?" -->true 6. Print "loop no.2" 7. Execute "++x". ‘x’ is now 3 8. Boolean expression "3<3 ?" -->false 9. Loop ends and program continues for ( x=1; x<3; x++ ) { System.out.println("loop no. " +x); }

Example 1: Counting Backwards int i; System.out.println("Start"); for ( i=4; i>=1; --i ) { System.out.println("counter=" +i); } System.out.println("End"); Start counter=4 counter=3 counter=2 counter=1 End

Example 2: Counting in Steps of 3 int i; System.out.println("Start"); for ( i=0; i<10; i=i+3 ) { System.out.println("counter=" +i); } System.out.println("End"); Start counter=0 counter=3 counter=6 counter=9 End

Example 3: Exponential Growth int i; System.out.println("Start"); for ( i=2; i<100000; i=i*i ) { System.out.println("i is " +i); } System.out.println("End"); Start i is 2 i is 4 i is 16 i is 256 i is 65536 End

Example 4: Stats Complete it int i, min=1000, max=0, sum=0, in; System.out.println("Enter 10 numbers between 0 and 1000"); for ( i=0; i<10; i ++) { } System.out.println("Largest number was" +max); System.out.println("Smallest number was" +min); System.out.println("Average was" +(sum/10)); System.out.println("Enter number " +(i+1)); in = UserInput.readInt(); if ( in>max ) max=in; // no curlies? if ( in<min ) min=in; // none here either? sum=sum + in;

Task Now: Write a 'for' - loop that adds all numbers between (and including) 1 and 10. Print the sum for each 'round' of the loop. Sum=1 Sum=3 Sum=6 Sum=10 Sum=15 Sum=21 Sum=28 Sum=36 Sum=45 Sum=55 Final=55 int i, sum=0; for ( i=1; i<=10; i ++) { sum=sum + i; System.out.println("Sum=" +sum); } System.out.println("Final=" +sum);

Nesting Value of shares which increase by 10% every month after ten years. Starting value: £10. int year, month; float sValue=10.0; for ( year=1; year<=10; year++ ) { } System.out.println("After 10 years: " +sValue); £ 927,091.50 for ( month=1; month<=12; ++month ) { sValue=sValue+ sValue *0.1; }

'break' - The Great Escape On occasion you want an "emergency exit" out of the (innermost) loop int month; float sValue=10.0; for ( month=1; month<=1000; month++ ) { sValue=sValue+ sValue *0.1; if (sValue > 1000000) break; } System.out.println("1 million after "+month+“months"); 1 million after 121 months Is this a good idea?

Use 'while' - Loops When the Amount of Iterations is Unknown int month=0; float sValue=10.0; while ( sValue < 1000000) { sValue=sValue+ sValue *0.1; ++month; } System.out.println("1 million after"+month+"months");

Initialising the Loop Variable int i; System.out.println("Start"); for ( i=4; i>=1; i --) { System.out.println("counter=" +i); } System.out.println("i is " +i); Alternative 1: the 'normal' way 'i' is known inside and outside the loop System.out.println("Start"); for ( int i=4; i>=1; i-- ) { System.out.println("counter=" +i); } System.out.println("i is" +i); Alternative 2: initialisation inside the 'for' statement 'i' is known only inside the loop

Check your knowledge now: What is wrong here ? float a; System.out.println("This loop will run 5 times"); for ( int k=1 k<5 ++k ); { k=k-1; if ( k != 0 ) { a = 15 / k; System.out.println( a ); // what's the output ? } System.out.println( k ); // what's the output ? 'for' - loop runs 4 times only both ';' inside ( ) missing, but misplaced outside ( ) for ( int k=0; k<5; k ++) { causes endless loop, delete. correct - jumps division by 0 mixing float and int in calc. a = 15.0f / (float) k; 15.0 7.5 5.0 3.75 0 1 2 3 4

Summary 1 Today we have ... revised 'boolean expressions' statements introduced 'while' loops introduced 'do' - 'while' loops (looked at 'break', 'continue' and 'exit(0)')

Summary 2 Today we also have ... introduced 'for' loops structure: for, ( ), three statements ';' separated, { } counting forwards / backwards / in steps loops inside loops: nesting introduced 'in-loop' loop initialisation: for( int i=... revised 'break'

END OF LESSON 3