Presentation is loading. Please wait.

Presentation is loading. Please wait.

John Hurley Cal State LA CS 201 Lecture 5. 2 Loops A loop performs a set of instructions repeatedly as long as some condition is met while (x != 0) {

Similar presentations


Presentation on theme: "John Hurley Cal State LA CS 201 Lecture 5. 2 Loops A loop performs a set of instructions repeatedly as long as some condition is met while (x != 0) {"— Presentation transcript:

1 John Hurley Cal State LA CS 201 Lecture 5

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

3 3 The Loops of Yore What loops looked like before we had modern loop syntax This is BASIC, although modern BASIC loops are similar to Java ones 10 x = 1 20 print x 30 x = x + 1 40 if x = 10 goto 60 50 goto 20 60 print "done"

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

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

6 Endless Loop You might deliberately write an endless loop (presumably with some other way to terminate it!) 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 c or by just closing the window

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

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

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

10 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 max = 10; for(int a = 1; a <= max; a++){ for(int b = 1; b <= max; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); count++; } System.out.println("\ntotal number of prints: " + count); } At the end of the method, count = max 2

11 Nested Loops What about this one? public class NestedLoopDemo3{ public static void main(String[] args){ int count = 0; int max = 5; for(int a = 0; a < max; a++){ for(int b = 0; b < a; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); count++; } System.out.println("\ntotal number of prints: " + count); } At the end of the method, count = 0+ 1 + 2 + … + (max – 1)

12 12 Math Operations Modulo operator % find the remainder after division, discard the quotient 10 % 1 = 0 10 % 5 = 0 10 % 4 = 2 10 % 3 = 1

13 13 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: Stooge 0, Stooge 1, and Stooge 2 will share some number of slaps on the head. We can only slap one Stooge at a time. slaps lapNum goes to Stooge i, where i = currSlapNum % 3 int stoogeNum = slapNum % 3;

14 14 Math Operations 012

15 15 Modulo Operations

16 16 Shortcuts OperatorExampleEquivalent +=i += 8i = i + 8 -=f -= 8.0f = f - 8.0 *=i *= 8i = i * 8 /=i /= 8i = i / 8 %=i %= 8i = i % 8

17 17 Increment and Decrement Operators OperatorNameDescription ++varpreincrementThe expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++postincrementThe expression (var++) evaluates to the original value in var and increments var by 1. --varpredecrementThe 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.

18 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); System.out.println(++num); System.out.println(num); } Outputs this sequence: 0 1 2

19 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: 0 1 2 3 4

20 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: 0 2 4

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

22 Character Codes Computers store information in bits There are several code systems to assign numeric values to characters

23 Character Codes ASCII developed in the early 1960s, when memory was much more expensive than it is now 128 (2 7 ) possible characters The first 33 are control characters, originally used to control teletypes

24 Character Codes Unicode Used in Java Superset of ASCII 65536 values The first 128 are the same as ASCII Adds other alphabets, mathematical symbols,etc.

25 Unicode and Hardware

26 Character Codes public class ASCIIUnicodeDemo{ public static void main(String[] args){ for(int charNum = 0; charNum < 128; charNum++){ System.out.println("Character " + charNum + " is " + (char) charNum); } Why do we get a blank line after 10 and before 11?

27 Character Codes chars can be compared using operators Apply the math operators to the Unicode values It’s probably obvious that ‘a’ < ‘b’ Not obvious that ‘A’ < ‘a’ ‘0’ < ‘a’ ‘/’ < ‘a’ 8 < ‘5’ !!

28 Character Codes public class UnicodeCompare{ public static void main(String[] args){ boolean isLessThan = false; for(int charNum = 0; charNum < 128; charNum++){ char currChar = (char) charNum; System.out.println("'" + currChar + "': " + " less than 'A'? " + (currChar < 'A')); } System.out.println("And by the way, it is " + (8 < '5') + " that 8 < '5'"); }

29 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

30 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

31 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 100); System.out.println("You entered " + age);

32 Validation We could still easily make the program above break enter “a” enter We will come back to validation soon

33 Equality with Floating Point Types Recall that, due to the imprecision of floating point types, it is unwise to test floats and doubles with == operator

34 Equality with Floating Point Types public class GPAWrong{ public static void main(String[] args){ double grade = 4.0; do{ System.out.println("grade = " + grade); // BAD CODE AHEAD!!!! if(grade == 4.0 || grade == 3.3 || grade == 3.0 || grade == 2.3) grade -= 0.3; else grade -= 0.4; }while(grade > 2.0); }double grade = 4.0; do{ JOptionPane.showMessageDialog(null, "grade = " + grade); // BAD CODE AHEAD!!!! if(grade == 4.0 || grade == 3.3 || grade == 3.0 || grade == 2.3) grade -= 0.3; else grade -= 0.4; }while(grade > 2.0); }

35 Equality with Floating Point Types Instead of using equality test, use Math.abs as follows: Math.abs(a-b) < tolerance; In the first project, we can’t test accurately whether a grade value ends in.7 The project will require a test like the following: if ((Math.abs(grade - 3.7) <.02) || (Math.abs(grade - 2.7) <.02)) grade -=.4; There will also be an else statement after this.

36 36 Programming Errors Syntax Errors Detected by the compiler Runtime Errors Cause the program to abort Logic Errors Produces incorrect result

37 37 Errors public class Errors{ public static void main(String[] args){ i += 1 System.out.println(i); i/= 0; }

38 38 Errors public class Errors{ public static void main(String[] args){ int y = 10; for(int x = 0; x <=10; x++){ y -= 1; System.out.println(10 / y); }

39 39 Logic Errors public class PowerError{ public static void main(String[] args){ int answer = 1; for(int power = 0; power <= 10; power++){ answer = answer * 2; System.out.println("2 ^ " + power + " = " + answer); }

40 40 Escape Sequences Some characters will cause confusion in output What will happen if we try to execute this: System.out.println(""Hi,Mom""); Others are used to control the format of output Use escape characters for these cases

41 41 Escape Sequences Description Escape Sequence Backspace \b Tab \t Linefeed \n Carriage return \r (think of a typewriter) Backslash \\ Single Quote \ ' Double Quote \ "

42 42 Escape Sequences public class Escape{ public static void main(String[] args){ System.out.println("A\tB\rB\tC D\nDD\b E\\F \'Hi, Mom\' \"Hi, Mom\""); }

43 43 String Concatenation // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB To concatenate to existing String, create a new String and use concat(): String myString = “Good”; String myOtherString = myString.concat(“ Morning”);

44 Test Your Work So far, it has been easy to test our programs, since there is only one sequence the computer can follow: public class Power{ public static void main(String[] args){ int answer = 1; for(int power = 0; power <= 10; power++){ System.out.println("2 ^ " + power + " = " + answer); answer = answer * 2; }

45 Test Your Work Soon, we will start writing programs that take user input Users are human beings The next slide shows a statistically representative sample of human beings

46

47 Test Your Work Program execution becomes more complex when unpredictable human beings intervene Make sure to test thoroughly We have it easy. Testing involves saving, compiling, and running on a machine that is at our fingertips It hasn’t always been that way.

48

49

50

51


Download ppt "John Hurley Cal State LA CS 201 Lecture 5. 2 Loops A loop performs a set of instructions repeatedly as long as some condition is met while (x != 0) {"

Similar presentations


Ads by Google