CS 101 - 2/14/12 On the trace code questions: 1. any undeclared variables are of type int 2. Some code is written to save space x = 0; y = 1; z = 3; while ( x < 5) { System.out.print (x + " "); x = x + 1; } 0 1 2 3 4 Beware of + and / "hello" + "bye" 5 + 4 "hello" * 4 10 / 3 10.0 / 3.0 Java Primitive Types for data int (short, long): 5 -6 12345 double (float) : 3.14159 0.0 boolean : true false char : 'a' '5' String : "Hello" "c:\\f1\\f2\\mypicture.jpg" Basic Operations Arithmetic: + : addition or concatenation - : subtraction or change sign * : multiplication / : division (int vs double) % : modulus/remainder ++ : increment -- : decrement Relational: == : equality != : not equal < : less than <= : less than or equal > : greater than >= : greater than or equal -------------------------- int count; count = 0 while ( count < 10 ) { System.out.println (count); count = count + 1; } --------------------- int count; count = 1 while ( count <= 10 ) { System.out.println (count); count = count + 1; } --------------------- int count; count = 7 while ( count > 1 ) // counts down { System.out.println (count); count = count - 1; } --------------------- int count; count = 7 while ( count > 1 ) // infinite loop { System.out.println (count); count = count + 1; } --------------------- int count; count = 7 while ( count < 1 ) // initially false { System.out.println (count); count = count - 1; } --------------------- int count; count = -5 while ( count < 5 ) // counts down { System.out.println (count); count = count + 1; } --------------------- int count; count = 1 while ( count < 15 ) // counts down { System.out.println (count); count = count + 3; } -------------------- What is the value of zafter the code is executed x = 0; z = 0; while ( x < 5 ) { z = z + x; x = x + 1; } z: 0 0 1 3 6 10 x: 0 1 2 3 4 5 -------------------- What is the value of zafter the code is executed x = 0; z = 0; while ( x < 5 ) { x = x + 1; z = z + x; } z: 0 1 3 6 10 15 x: 0 1 2 3 4 5 =========================== Write code questions Q21. Write a code fragment that .... Assume you are in main method and start writing code. You must declare ALL varaibles used. draw a picture using turtles t1.forward () t1.turn () t1.setPenColor ( Color.RED ) Q22. Write a method using a loop... public static void drawHexagon ( Turtle t , int len, Color c) { Color savedColor; savedColor = t.getPenColor(); t.setPenColor (c); int count; count = 0; // draw the shape while ( count < 6 ) { t.forwaard (len); t.turn (360/6); count = count + 1; } t.setPenColor (savedColor); } public static void drawHexagon ( Turtle t , int len, int thickness) { int savedThinkness; savedThinkness = t.getPenWidth(); t.setPenWdith (thinkness); int count; count = 0; // draw the shape while ( count < 6 ) { t.forwaard (len); t.turn (360/6); count = count + 1; } t.setPenWidth (savedThickness); }