Download presentation
Presentation is loading. Please wait.
Published byDinah Dennis Modified over 9 years ago
1
Lecture 4: Looping Tami Meredith
2
Back to Basics... Programming requires: 1. Identification of the problem. 2. Solving the problem: A. Selecting the data structures, and Data Management is the key here B. Identifying an algorithm Control Flow is the basis of algorithms 3. Coding the solution 4. Testing, debugging, verifying the solution
3
Control is Power! Control flow is actually very simple: 1. Everything is sequential, unless... 2. Something is optional (last class) Conditional Statements, i.e,. if 3. Something is repeated (this class) Looping Statements, i.e., do, for, while 4. Something complex is broken into simpler parts (last class, next class) i.e., methods, classes, objects
4
Control Flow Until now all programs have been sequential We do the instructions one after another without skipping or jumping over any This is the default flow of execution This is very limiting Need ways to say: "lets only do... when... occurs" "do this.... if.... happens and do.... otherwise" "do this.... X times"
5
Exiting a program There are 3 ways to exit a program 1. Execution ends normally when the end of main is reached 2. Execution ends any time there is a return inside main 3. Execution ends any time, in any method, when System.exit( n ) occurs n is the integer exit code 0 if all is OK, other values for different errors OK for now to always use 0
6
Branching (Conditional Execution) We have the " if " statement in Java to make control flow choices if ( test ) true-actions else false-actions Example: int n1 = 3; int n2 = 4; if (n1 < n2) { // First block, true actions System.out.println("N1 is smaller"); } else { // Second (else) block, false actions System.out.println("N2 is equal or smaller"); }
7
Alternative Format if ( test ) true-actions No "else" part in this version Example: int n1 = 3; int n2 = 4; int result = 0; if (n1 != 0) { // Guard against division by 0 result = n2 / n1; } // println is always done System.out.println("Quotient is " + result);
8
Multiple Definitions We can combine definitions using a comma if they have the same type For example, int count = 0; int stop = 5; is the same as, int count = 0, stop = 5;
9
Blocks We can group a set of statements that we wish to perform Such a group is called a "Block" Blocks are identified with { and } We use blocks to put more than one statement in the "true-actions" and "false-actions" of if statements
10
Example int n1 = 3, n2 = 4, result = 0; if (n1 != 0) // No block, only assignment controlled by if result = n2 / n1; System.out.println("Quotient is " + result); if (n1 != 0) { // Block used, adds clarity result = n2 / n1; } System.out.println("Quotient is " + result);
11
Example Continued, Making println conditional int n1 = 3, n2 = 4, result = 0; // without a block if (n1 != 0) result = n2 / n1; if (n1 != 0) System.out.println("Quotient is " + result); if (n1 != 0) { // with a block result = n2 / n1; System.out.println("Quotient is " + result); }
12
Style Points Things inside a block should be indented Indenting indicates that something is in a block, it does not CAUSE it to be part of the block Blocks should be used liberally Blocks have no detrimental impacts on performance Like parentheses, blocks add clarity and make code more understandable Indentation can be 2, 4, or 8 spaces, but MUST be consistent for the entire program
13
Boolean Operators && (and) Both are true || (or) Either one or the other (or both) are true !(not)Negation, reverses a boolean value Operand 1Operand2Op1 && Op2Op1 || Op2 ! Op1 true false truefalse truefalse truefalsetrue false true
14
Example int min = 0, max = 10, val = 5; if (min <= val) { // Nested If statements, same as AND (&&) if (val <= max) { System.out.println("Value " + val + " is in range [min,max]"); } if ((min <= val) && (val <= max)) { // AND condition to combine tests System.out.println("Value " + val + " is in range [min,max]"); }
15
Example int min = 0, max = 10, val = 5; // Multiple if statements, same as OR (||) if (val < min) { System.out.println("Value " + val + " is not in range [min,max]"); } if (max < val) { System.out.println("Value " + val + " is not in range [min,max]"); } // OR condition to combine tests if ((val < min) || (max < val)) { System.out.println("Value " + val + " is not in range [min,max]"); }
16
Exercise Write a program with an integer variable named val1 If val1 is less than 0 print negative the screen If val1 is greater than 0 print positive to the screen If val1 equals zero, print zero to the screen
17
Solution // Integer variable tester, By Tami Meredith public class inttest { /* Define the method main for the program */ public static void main (String[] args) { int val1 = 77; if (val1 < 0) { System.out.println("negative"); } else if (val1 > 0) { System.out.println("positive"); } else { System.out.println("zero"); } } // end main() } // end class inttest
18
A Note My solutions tend to be a little cramped I am trying to fit things on the slide but keep the font large so you can read it I don't have a lot of space to work with as a result These examples are formatted OK, but could be a lot better! Format variation is allowed... main (String[] args) { main (String[] args) // stuff versus { } // stuff }
19
Placing the Curly Braces // compact, but { harder to see if (x != 0) { System.out.println("Not zero."); } // stand-alone, clearer but longer files if (x < 0) { System.out.println("Negative."); }
20
Choices are not enough if lets us chose whether to do something We create conditions (which are often quite complex) and based on these conditions (i.e., tests) code is either executed or ignored But, making choices is still only half the issue... What if we want to do something more than once?
21
Some Inefficient Code // Program, counts from 0 to the value "stop" int count = 0; int stop = 8 System.out.println(count); // print 0 count = count + 1; if (count <= stop) { System.out.println(count); // print 1 } count = count + 1; if (count <= stop) { System.out.println(count); // print 2 } // And so on, and so on... (need a better way if stop == 100!) // Must have enough tests to ensure we always reach stop
22
Our First Loop // Program, counts from 0 to the value stop int count = 0; int stop = 8; while (count <= stop) { System.out.println(count); count = count + 1; } // end of loop, go back to test
23
Loops Loops repeat an action (or set of actions) while a test is true 3 kinds of loops: while, do, for All just vary only in when the test is applied
24
While Loops Format: while (test) { // body: do while the test is true // May do this 0 times (never!) } Example: int x = 1; while (x < 10) { System.out.println(x); x = x + 1; }
25
Do Loops Format: do { // body: do until the test is true // Always does at least once } while (test); Example: int x = 1; do { System.out.println(x); x = x + 1; } while (x <= 10);
26
For Loops Format: for (init; test; step){ // body: do while the test is true } Init: Done exactly once before the loops begins, Initialisation Test: Done before each time the body is executed Step: Done after each time the body is executed and before the next test Example: int x; for (x = 0; x <= 10; x = x + 1) { System.out.println(x); }
27
Congratulations You are programmers now! Variables/Data + If + Loops = Programs! Just like driving a car = speeding up + slowing down + turning left or right All the rest is the equivalent of knowing when to turn, when to speed up, what the yellow lights mean (go faster)... Programming is knowing when to loop, what variables you need, when to branch You can do everything you need now From this point onwards we learn ways to improve our programs, not do more
28
Infinite Loops Many ways to create an infinite loop Most likely we will do it by accident, but its not hard... int x = 0; while (true) { // print 0 forever System.out.println(x); } for (;;) { // Same thing... System.out.println(x); }
29
Exiting a loop Loops end when we fail the test BUT, we can "jump out" of a loop anytime we want Use break to exit a loop while (true) { System.out.println(x); if (x == 20) { break; } x = x + 2; }
30
Nested Loops Loops can contain other loops! This is confusing at first, we'll come back to it more later on int i, j; for (i = 0; i < 11; i = i + 1) { for (j = 0; j < 11; j = j + 1) { System.out.println((i*10) + j); }
31
Incrementing We tend to increment variables a lot when using loops E.g., i = i + 1; To save typing (remember, programmers are lazy) the increment operators were created: i++ and ++i i++; // First use i, then add 1 to i ++i; // Add 1 before using i int i = 10, j, k; j = i++; // j = 10, i = 11 k = ++i; // k = 12, i = 12
32
Decrementing When we want to count down (instead of up) we decrement a variable E.g., i = i - 1; Thus, the decrement operators were created: i-- and --i i--; // First use i, then subtract 1 ++i; // Subtract 1 before using i int i = 10, j, k; j = i--; // j = 10, i = 9 k = --i; // k = 8, i = 8
33
Increment/Decrement ExpressionAlternative i++;i = i + i; ++i;i = i + 1; i--;i = i – 1; --i;i = i – 1; j = i++;j = i; i = i + 1; j = ++i;i = i + 1; j = i; j = i--;j = i; i = i - 1; j = --i;i = i – 1; j = i;
34
Exercise Write a program that prints the numbers from 100 down to 1 using a loop
35
Solution 1: For // Countdown, By Tami Meredith public class countdown { public static void main (String[] args) { int val; for (val = 100; val > 0; val--) { System.out.println(val); } // end for } // end main() } // end class countdown
36
Solution: While // Countdown, By Tami Meredith public class countdown { public static void main (String[] args) { int val = 100; while (val > 0) { System.out.println(val); val--; } // end while } // end main() } // end class countdown
37
Exercise Write a program that prints the letters of your name, one at a time, using a loop. Remember, charAt(i) gets the letters of a string at index i length() returns the length of a string Strings are indexed from 0 to length-1 Note: You are going to need to be very comfortable with the String class (Figure 2.5, pg 86)!
38
Solution // Letters One by One, By Tami Meredith public class onebyone { public static void main (String[] args) { String name = "Tami Meredith"; int index, len = name.length(); for (index = 0; index < len; index++) { System.out.println(name.charAt(index)); } // end for } // end main() } // end class onebyone
39
Now you understand...
40
STAY TUNED LOTS MORE TO COME!
41
To Do Go to the lab and complete today's assignment Read Chapter 5 (For next class), make notes, write down your questions and bring them next week If you want to work at home, install JDK 1.7 and JCreator LE Read Chapters 1 - 3 (Material from previous classes) and Chapter 4 (Material from this class), if you have not already
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.