John Hurley Cal State LA CS 201 Lecture 5 John Hurley Cal State LA
Loops A loop performs a set of instructions repeatedly as long as some condition is met while (x != 0) { //statements } executes the statements repeatedly as long as the value of x is not equal to 0 when it is tested, which is at the beginning of each run through the loop. Loops are one of the most important techniques in programming. Why is this?
For Loop for(int i = 0; i <10; i++) { } System.out.println(i); } Declares an integer variable named i i is a loop counter. Many programmers would actually name it something like “counter” to make this as clear as possible; this is a very good practice: for(int counter = 0; counter < 10; counter++){ } Initially i is set to 0 Tests whether i is less than 10 If so, prints the values of I, then increments i by 1 If not, continues to whatever is after the loop the statements between the backers are a block could contain any number of statements, all of which execute each time through the loop.
Count from 0 to 9 public class Count{ public static void main(String[] args) { for (int i = 0; i < 10; i++){ System.out.println(i); }
Endless Loop You might deliberately write an endless loop (presumably with some way to terminate it other than the loop test) Also, it turns out that there is no algorithm that can determine whether a loop will eventually terminate Accordingly, the compiler and JVM do not protect you from accidentally writing one At the command line, you can stop a program gone awry by hitting <ctrl> c or by just closing the window
More on While Loops A while loop will continue as long as the test is true. public class WhileDemo{ public static void main(String[] args){ int thisVar = 0; while(thisVar < 10) System.out.println(thisVar++); }
More on While Loops The test may use a variable that does something more sophisticated than counting the loop: public class WhileDemo{ public static void main(String[] args){ int thisVar = 0; while(thisVar < 10) { // get a value of thisVar from input System.out.println(thisVar); }
Running of the Bulls int runnerPosition = 400, bullPosition = 600; int runnerSpeed = 4, bullSpeed = 7; int currSecond = 0; while(bullPosition > runnerPosition && runnerPosition > 0){ int runnerLead = bullPosition - runnerPosition; System.out.println("At " + currSecond + " second(s), runner is " + runnerPosition + " meters from safety and bull is " + runnerLead + " meters behind him."); runnerPosition -= runnerSpeed; bullPosition -= bullSpeed; currSecond++; } if(runnerPosition <= 0) System.out.println("Runner reached safety!"); else System.out.println("Runner gored at " + runnerPosition + " meters from safety!");
Nested Loops One loop may be inside another one Inner loop will execute its full run for every iteration of the outer loop Inner loop may use variables controlled by the outer loop How many times does the statement in bold execute? public class NestedLoopDemo{ public static void main(String[] args){ for(int a = 1; a <= 10; a++){ for(int b = 1; b <= 10; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); } How would you do a multiplication table?
Nested Loops Consider a case in which, for each iteration of the outer loop, the inner loop executes the same number of times as the outer loop: public class NestedLoopDemo2{ public static void main(String[] args){ int count = 0; int n = 5; for(int a = 1; a <= n; a++){ for(int b = 1; b <= n; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); count++; } System.out.println("\ntotal number of prints: " + count); } Inner loop System.out.println() executes n2 times
Math Operations Modulo operator % find the remainder after division, discard the quotient 10 % 1 = 0 10 % 5 = 0 10 % 4 = 2 10 % 3 = 1
Math Operations Modulo operations have many uses in programming. One is to create a sequence of unlimited length using a finite set of resources, by taking turns in round-robin fashion Example of modulo logic: Stooge0, Stooge1, and Stooge2 will share some number of slaps on the head. We can only slap one Stooge at a time. slapslapNum goes to Stoogei, where i = currSlapNum % 3 int stoogeNum = slapNum % 3;
Math Operations 1 2
Modulo Operations
Shortcuts Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8
Increment and Decrement Operators Operator Name Description ++var preincrement The expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++ postincrement The expression (var++) evaluates to the original value in var and increments var by 1. --var predecrement The expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var-- postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1.
Increment and Decrement Operators public class Increments{ public static void main(String[] args){ int num = 0; System.out.println(num); System.out.println(num++); System.out.println(++num); } Outputs this sequence: 1 2
Increment and Decrement Operators public class Increments{ public static void main(String[] args){ for(int num = 0; num < 5; num++) System.out.println(num); } outputs this sequence: 1 2 3 4
Increment and Decrement Operators What will this one do? public class Increments{ public static void main(String[] args){ for(int num = 0; num < 5; ++num) System.out.println(num--); }
Do…While Similar to while loop, but with test at the end, not the beginning Always executes at least once int x = 0; while ( x > 0) {} will never execute do{ } while ( x > 0); will execute at least once
Do…While Similar to while loop, but with test at the end, not the beginning Always executes at least once int x = 0; while ( x > 0) {} will never execute do{ } while ( x > 0); will execute at least once
Validation We have covered one way to get user input, using Scanner to get it form the console We will soon cover at least one additional way to get input We have noted that users are human beings and accordingly are impossible to predict Input is not always usable
Validation Screen input for problems before using it while and do… while loops are very handy for this Example: Scanner sc = new Scanner(System.in); int age; do { System.out.println("How old are you?"); age = sc.nextInt(); } while (age < 0 || age > 100); System.out.println("You entered " + age);
Validation We could still easily make the program above break enter “a” enter <esc> We will come back to validation soon