Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java LESSON 3 Loops.

Similar presentations


Presentation on theme: "Java LESSON 3 Loops."— Presentation transcript:

1 Java LESSON 3 Loops

2 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

3 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

4 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

5 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

6 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 }

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

8 '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?

9 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?

10 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?

11 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"

12 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

13 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;

14 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 );

15 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;

16 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);

17 '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 !

18 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

19 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.

20 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;

21 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);

22 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 ...");

23 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

24 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 } ....;

25 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

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

27 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

28 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

29 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

30 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 { }

31 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); }

32 '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); }

33 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); }

34 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

35 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

36 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

37 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;

38 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);

39 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; }

40 '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 > ) break; } System.out.println("1 million after "+month+“months"); 1 million after 121 months Is this a good idea?

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

42 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

43 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;

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

45 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'

46 END OF LESSON 3


Download ppt "Java LESSON 3 Loops."

Similar presentations


Ads by Google