Values in 2 s Complement
|
|
- Sara Holland
- 5 years ago
- Views:
Transcription
1 Values in 2 s Complement Java uses an encoding known as 2 s complement 1, which means that negative numbers are represented by inverting 2 all of the bits in a value, then adding 1 to the result. For example, = Then = can be derived from inverting to plus 1. 1 In 1 s complement, simply inverting all of the bits creates , which creates negative zero. The trouble is that negative zero is invalid in integer math. 2 Changing 1 s to 0 s and vice versa. Zheng-Liang Lu Java Programming 50 / 146
2 Identifiers Identifiers are the names that identify the elements such as variables, methods, and classes in a program. All identifiers must obey the following rules: a sequence of characters that consists of letters, digits, and underscores ( ) start with a letter or an underscore ( ) can be of any length cannot start with a digit cannot be a reserved word cannot be true, false, or null cannot contain +,,, and % Note that Java is case sensitive 3. 3 The letters A and a are different. Zheng-Liang Lu Java Programming 51 / 146
3 Reserved Words 4 4 See Appendix A in YDL, p Zheng-Liang Lu Java Programming 52 / 146
4 When To Declare Variables: Two Before Rules Every variable has a scope. The scope of a variable is the part of the program where the variable can be referenced. A variable must be declared before it can be assigned a value. A declared variable must be assigned a value before it can be used. 5 The detail of variable scope is introduced later. 5 In symbolic programming, such as Mathematica and Maple, a variable can be manipulated without assigning a value. Zheng-Liang Lu Java Programming 53 / 146
5 Data Types Java is a strongly typed programming language. Every variable has a type. Every expression has a type. Every type is strictly defined. All assignments are checked for type compatibility. 6 There are two categories of date types: primitive data types, referential data types. 6 By Java compiler. Zheng-Liang Lu Java Programming 54 / 146
6 Primitive Data Types 7 7 See Figure 3-4 in Sharan, p. 67. Zheng-Liang Lu Java Programming 55 / 146
7 Integers The most commonly used integer type is int. long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. Note that when byte and short values are used in an expression, they are promoted to int when the expression is evaluated. 8 8 Due to the first bullet. Zheng-Liang Lu Java Programming 56 / 146
8 Floating Points Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. All transcendental math functions, such as sin(), cos(), and sqrt(), return double values. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. Be aware that floating-point arithmetic can only approximate real arithmetic. (Why?) Zheng-Liang Lu Java Programming 57 / 146
9 Example: = 0? 1 public class displaytime { 2 public static void main(string args[]) { 3 System.out.println( ); 4 } 5 } The result is surprising. Why? Decimal-binary converter Zheng-Liang Lu Java Programming 58 / 146
10 IEEE Floating-Point Representation 9 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either between 1 and 2 ɛ, or between 0 and 1 ɛ. The exponent E weights the value by a (possibly negative) power of 2. 9 William Kahan (1985) Zheng-Liang Lu Java Programming 59 / 146
11 Illustration See Figure 2-31 in Byrant, p Zheng-Liang Lu Java Programming 60 / 146
12 Assginment Statement An assignment statement designates a value for a variable, by the following syntax: myvar = expression; 3... The equal sign (=) is used as the assignment operator. For example, is the expression x = x + 1 correct? From the right-hand side to the left-hand side An expression represents a computation involving values, variables, and operators that evaluates to a value. To assign a value to a variable, you must place the variable name to the left of the assignment operator. 11 For example, 1 = x is wrong. 11 x can be a L-value and R-value, but 1 and other numbers can be only r-value but not l-value. See Value. Zheng-Liang Lu Java Programming 61 / 146
13 Variable Initialization Initialization once declaration int x = 1, y = 2; // Equivalent to int x, y; x = 1; y = 2; 3... Dynamical initialization double x, y = 3.0; 3 x = y; 4... y is assigned in the compilation stage; x is assigned in the runtime stage. Zheng-Liang Lu Java Programming 62 / 146
14 Numeric Operators 12 Note that when both operands of a division are integers, the result of the division is an integer and the fractional part is truncated. So, the operator depends on the operands. 12 See Table 2-3 in YDL, p. 46. Zheng-Liang Lu Java Programming 63 / 146
15 Example int a, b; 3 double c,d; 4 a = c = b = d = / 2.; 5... a =? b =? c =? d =? Zheng-Liang Lu Java Programming 64 / 146
16 Type Conversion If the two types are compatible, then Java will perform the conversion automatically. However, not all types are compatible, and thus, not all type conversions are implicitly allowed. The two types are compatible. The destination type is larger than the source type. For example, there is no automatic conversion defined from double to byte. (Why?) To do so, you must use a cast, which performs an explicit conversion between incompatible types. Zheng-Liang Lu Java Programming 65 / 146
17 Casting 1 public class test { 2 public static void main (String[] args) { 3 double x = 1.234; 4 int y; 5 y = (int) x; // (target type) 6 System.out.println("y = " + y); 7 } 8 } Target-type specifies the desired type to convert the specified value to. In this example, a different type of conversion will occur when a floating-point value is assigned to an integer type, as known as, truncation. Zheng-Liang Lu Java Programming 66 / 146
18 Example 1 public class promote { 2 public static void main(string[] args) { 3 byte b = 42; 4 char c = a ; // single quote for a letter, a > 97 5 short s = 1024; 6 int i = 50000; 7 float f = 5.67; 8 double d =.1234; 9 double result = (f b) + (i / c) (d s); 0 System.out.println((f b) + " + " + (i / c) + " " + 1 (d s) + " = " + result); 2 } 3 } (i/c) =? How to correct? Zheng-Liang Lu Java Programming 67 / 146
19 Type Promotion (Concluded) Type promotion rules are as follows: All byte, short, and char values are promoted to int. If one operand is a long, the whole expression is promoted to long. Similarly, if one is float, then promoted to float. Also, if any of the operands are double, then promoted to double. Zheng-Liang Lu Java Programming 68 / 146
20 Characters A character is stored in a computer as a sequence of 0s and 1s. The char data type is a 16-bit unsigned Java primitive data type. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. Zheng-Liang Lu Java Programming 69 / 146
21 ASCII (7-bit version) Zheng-Liang Lu Java Programming 70 / 146
22 Example Characters can also be used as an integer type on which you can perform arithmetic operations. For example, char x = a ; // Cannot be "a" 3 System.out.println(x + 1); 4 System.out.println((char)(x + 1)); 5 System.out.println(x + "1"); 6 System.out.println("This is " + x + 1); 7 System.out.println("This is " + (x + 1)); 8... x =? Note that the plus (+) operator is overloaded. Zheng-Liang Lu Java Programming 71 / 146
23 Character Escape Sequences See Table 3-1 in HS, p. 44. Zheng-Liang Lu Java Programming 72 / 146
24 Boolean Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. boolean is also the type required by the conditional expressions that govern the control statements such as if and for. Note that a boolean value cannot be cast into a value of another type, nor can a value of another type be cast into a boolean value. Zheng-Liang Lu Java Programming 73 / 146
25 Rational Operators 14 They are all binary operators. Rational expressions return Boolean values. Note that the equality comparison operator is two equal signs (==), not a single equal sign (=), which is the assignment operator. 14 See Table 3-1 in YDL, p. 82. Zheng-Liang Lu Java Programming 74 / 146
26 Example a = 4 > 3; 3 b = 4 < 3; 4 c = 4 == 3; 5 d = 4!= 3; 6 e = 4 > 3 > 2; 7... a =? b =? c =? d =? e =? Be aware that e is logically correct but syntaxically wrong. Zheng-Liang Lu Java Programming 75 / 146
27 Logical Operators 15 Sometimes, whether a statement is executed is determined by a combination of several conditions. For example, 4 > 3 > 2 should be (4 > 3)&&(3 > 2) in the program, where && refers to the and operator. 15 See Table 3-2 in YDL, p Zheng-Liang Lu Java Programming 76 / 146
28 Arithmetic Compound Assignment Operators += ( =) is called the addition (subtraction) assignment operator. The increment (++) and decrement ( ) operators are for incrementing and decrementing a variable by 1. Zheng-Liang Lu Java Programming 77 / 146
29 Example int a = 1; 3 System.out.println(a+=1); // a = a System.out.println(a++); // a = a System.out.println(++a); // a = a System.out.println( a); // a = a 1 7 System.out.println(a ); // a = a What are the results? Zheng-Liang Lu Java Programming 78 / 146
30 Bitwise Operators Java defines several bitwise operators that can be applied to the integer types: long, int, short, char, and byte. Zheng-Liang Lu Java Programming 79 / 146
31 Example int a = 3; // or 0011 in binary 3 int b = 6; // or 0110 in binary 4 int c = a b; 5 int d = a & b; 6 int e = a ˆ b; 7 int f = ( a & b) (a & b); 8 int g = a & 0x0f; 9 System.out.println(a >>= 2); 0 System.out.println(b <<= 2); 1... c =? d =? e =? f =? g =? h =? i =? In Line 9 and 10, what are the results? Zheng-Liang Lu Java Programming 80 / 146
32 Operator Precedence See Table3-10 in YDL, p Zheng-Liang Lu Java Programming 81 / 146
33 A Tip: Using Parentheses Parentheses raise the precedence of the operations that are inside them. Adding parentheses to reduce ambiguity does not negatively affect your program. Zheng-Liang Lu Java Programming 82 / 146
34 Scanner Class It is not convenient to modify the source code and recompile it for a different radius. Reading input from the console enables the program to receive input from the user. Scanner class provides methods for console input. Java uses System.in to refer to the standard input device. By default, the input device is the keyboard. Zheng-Liang Lu Java Programming 83 / 146
35 Example: Reading Input From The Console Write a program which receives a number as input, and determine the area of the circle. 1 import java.util.scanner; // import a class Scanner input = new Scanner(System.in); // create an object radius = input.nextdouble(); // return a double to radius input.close(); 8... Zheng-Liang Lu Java Programming 84 / 146
36 1 import java.util.scanner; 2 3 public class ComputeAreaWithConsoleInput { 4 public static void main (String[] args) { 5 Scanner input = new Scanner(System.in); 6 System.out.println("Enter a number for radius: "); 7 double radius = input.nextdouble(); 8 double area = radius radius ; 9 System.out.println("The area for the circle of radius " 0 + radius + " is " + area +"."); 1 input.close(); 2 } 3 } In the listing, Scanner input = new Scanner(System.in) creates a Scanner object and assigns its memory address to the variable input. So, input is a referential type variable. We will discuss the objects and referential variables in detail. Zheng-Liang Lu Java Programming 85 / 146
37 Methods Within Scanner Objects See Table 2-1 in YDL, p. 38. Zheng-Liang Lu Java Programming 86 / 146
38 Example: Mean and Standard Deviation Write a program which calculates the sample mean and the sample standard deviation of any 3 numbers. Sample mean of three numbers is given by µ = Also, the sample standard deviation is given by 3 i=1 x i. 3 σ = 3 You may use these two methods: Math.pow(double x, double y) for x y Math.sqrt(double x) for x See more methods within Math class. i=1 (x i µ) 2. 2 Zheng-Liang Lu Java Programming 87 / 146
39 public static void main (String[] args) { 3 Scanner input = new Scanner(System.in); 4 System.out.println("Enter a =?"); 5 double a = input.nextdouble(); 6 System.out.println("Enter b =?"); 7 double b = input.nextdouble(); 8 System.out.println("Enter c =?"); 9 double c = input.nextdouble(); 0 double mean = (a + b + c) / 3; 1 a = mean; // Deviation from mean 2 b = mean; 3 c = mean; 4 double std = Math.pow(a,2) + Math.pow(b,2) + Math.pow(c,2); 5 std /= 2; 6 std = Math.sqrt(std); 7 System.out.println("Mean = " + mean + "\n 8 Standard Deviation = " + std); 9 } 0... Zheng-Liang Lu Java Programming 88 / 146
40 Problem Set Exercise 2.1 (Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows: yf = ( 9 5 ) xc + 32 Exercise 2.2 (Sum the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14. Zheng-Liang Lu Java Programming 89 / 146
41 Exercise 2.3 (Find the number of years) Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays the number of years and days for the minutes. For simplicity, assume a year has 365 days. Exercise 2.4 (Heron s formula.) Write a program that prompts the user to enter three points (x 1, y 1 ), (x 2, y 2 ), (x 3, y 3 ) of a triangle and displays its area. Zheng-Liang Lu Java Programming 90 / 146
42 Exercise 2.5 (Return rate) Write a program that reads in investment amount X, future value of investment Y, and number of years n, and displays the return rate of the investment r using the following formula: r = n Y X 1. Zheng-Liang Lu Java Programming 91 / 146
43 1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 / References 8 [1] Ch. 3 in YDL 9 / Zheng-Liang Lu Java Programming 92 / 146
44 Flow Controls The basic algorithm or program constitutes the following operations: Sequential operations: instructions executed in order. Selective operations: first check if the condition is satisfied, then select the next instruction based on boolean values. Repetitive operations: repeat the execution of a block of instructions until the criteria is not satisfied. Zheng-Liang Lu Java Programming 93 / 146
45 Note that the three types of operations are not mutually exclusive. In most cases, they are involved with each other. For example, recall how to find the highest score of math quiz in the class? Zheng-Liang Lu Java Programming 94 / 146
46 Selections Java has several types of selection statements: one-way if statements two-way if-else statements nested if statements switch-case statements conditional expressions Zheng-Liang Lu Java Programming 95 / 146
47 One-Way if Statements A one-way if statement executes an action if and only if the condition is true. Zheng-Liang Lu Java Programming 96 / 146
48 1 if (condition) { 2 // selection body 3 } The keyword if is followed by the parenthesized condition. The condition should be a boolean expression or a boolean value. It the condition is true, then the statements in the selection body will be executed once. If not, then the program won t enter the selection body. Note that the braces can be omitted if the block contains a single statement. Zheng-Liang Lu Java Programming 97 / 146
49 Example Write a program which receives a nonnegative number as input for the radius of a circle, and determines the area of the circle if (radius >= 0) { 3 area = radius radius ; 4 System.out.println("The area of the circle with radius " + 5 radius + " is " + area + "."); 6 } 7... But, the world is not well-defined. Zheng-Liang Lu Java Programming 98 / 146
50 Two-Way if-else Statements A two-way if-else statement decides which statements to execute based on whether the condition is true or false. 1 if (condition) { 2 // selection body 1 3 } 4 else { 5 // selection body 2 6 } Zheng-Liang Lu Java Programming 99 / 146
51 Zheng-Liang Lu Java Programming 100 / 146
52 Example Write a program which receives a number as input for the radius of a circle. If the number is nonnegative, then determine the area of the circle; otherwise, print Not a circle if (radius >= 0) { 3 area = radius radius ; 4 System.out.println("The area of the circle with radius " + radius + " is " + area + "."); 5 } 6 else { 7 System.out.println("Not a circle."); 8 } 9... Zheng-Liang Lu Java Programming 101 / 146
53 Example: Nested if Statements An if statement can be inside another if statement to form a nested if statement if (score >= 90) System.out.println("A"); 3 else { 4 if (score >= 80) System.out.println("B"); 5 else { 6 if (score >= 70) System.out.println("C"); 7 else { 8 if (score >= 60) System.out.println("D"); 9 else System.out.println("F"); 0 } 1 } 2 } 3... Zheng-Liang Lu Java Programming 102 / 146
54 Example: Multi-Way if-else if (score >= 90) System.out.println("A"); 3 else if (score >= 80) System.out.println("B"); 4 else if (score >= 70) System.out.println("C"); 5 else if (score >= 60) System.out.println("D"); 6 else System.out.println("F"); 7... An if-elseif-else statement is a preferred format for multiple alternatives, in order to avoid deep indentation and makes the program easy to read. The order of conditions may be relevant. (Why?) The performance may degrade due to the order of conditions. (Why?) Zheng-Liang Lu Java Programming 103 / 146
55 Common Errors in Selection Statements Two bugs? if (r > 0); 3 area = r r pi; 4 System.out.println("Area = " + area); 5... How to revise in order to determine the maximum? int i = 1, j = 2, k = 3; 3 if (i > j) 4 if (i > k) 5 System.out.println("Max = " + i); 6 else if (j > k) 7 System.out.println("Max = " + j); 8 else 9 System.out.println("Max = " + k); 0... Zheng-Liang Lu Java Programming 104 / 146
56 Example Generating random numbers Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows =? If the user answers 7, then the program reports Correct. and terminates. Otherwise, the program reports Wrong answer. The correct answer is 7. for this case. You may use Math.random() for a random value between 0.0 and 1.0, excluding themselves. Zheng-Liang Lu Java Programming 105 / 146
57 public static void main(string[] args) { 3 4 int x = (int) (Math.random() 10); // numbers int y = (int) (Math.random() 10); 6 7 System.out.println(x + " + " + y + " =?"); 8 9 Scanner in = new Scanner(System.in); 0 int z = in.nextint(); 1 2 if (z == (x + y)) 3 System.out.println("Correct."); 4 else 5 System.out.println("Wrong. The correct answer is " + (x + y ) + "."); 6 in.close(); 7 } 8... Can you extend this program to include + in the math expressions? Zheng-Liang Lu Java Programming 106 / 146
58 Exercise Find Maximum Write a program which finds the maximum value in 3 random integers whose range from 1 to 10. How many variables do we need? How to compare? How to keep the maximum value? Zheng-Liang Lu Java Programming 107 / 146
59 public static void main(string[] args) { 3 4 int x = (int) (Math.random() ); 5 int y = (int) (Math.random() ); 6 int z = (int) (Math.random() ); 7 8 System.out.println("(x, y, z) = " + "(" + x + "," + y + "," + z + ")"); 9 0 int max = x; 1 if (y > max) max = y; 2 if (z > max) max = z; 3 System.out.println("Max = " + max); 4 } 5... In this case, a scalar variable is not convenient. (Why?) Zheng-Liang Lu Java Programming 108 / 146
60 switch-case Statements A switch-case statements executes statements based on the value of a variable or an expression. 1 switch (target) { 2 case value1: 3 statements; 4 break; 5 case value2: case valuek: 9 statements; 0 break; 1 default: 2 statements; 3 } Zheng-Liang Lu Java Programming 109 / 146
61 A switch-case statements is more convenient than an if statement to simply the code for multiple discrete conditions. target must yield a value of char, byte, short, int, or String type. target must always be enclosed in parentheses. value1,..., and valuek must have the same data type as the value of target. In each case, a break statement is a must. 18 The default case, which is optional, can be used to perform actions when none of the specified cases matches target. 18 If not, there will be a fall-through behavior. Zheng-Liang Lu Java Programming 110 / 146
62 Example Write a program which picks a day of week randomly. How many discrete cases? Zheng-Liang Lu Java Programming 111 / 146
63 1 public class weekday { 2 public static void main(string[] args) { 3 int day = (int) ((Math.random() 10) % 7 + 1); 4 switch(day) { 5 case 1: 6 System.out.println("Monday"); 7 break; 8 case 2: 9 System.out.println("Tuesday"); 0 break; 1 case 3: 2 System.out.println("Wednesday"); 3 break; 4 case 4: 5 System.out.println("Thursday"); 6 break; 7 case 5: 8 System.out.println("Friday"); 9 break; 0 case 6: 1 System.out.println("Saturday"); 2 break; 3 case 7: 4 System.out.println("Sunday"); 5 break; Zheng-Liang Lu Java Programming 112 / 146
64 6 default: 7 System.out.println("Invalid weekday?"); 8 } 9 } 0 } Be aware that the arithmetic expression in Line 3 should be parenthesized. (Why?) Zheng-Liang Lu Java Programming 113 / 146
65 Conditional Expressions A conditional expression evaluates an expression based on a condition. 1 boolean expr? expr A : expr B; If the boolean expression is true, then the result is expr A; otherwise, expr B. Zheng-Liang Lu Java Programming 114 / 146
66 For example, if (num1 > num2) 3 max = num1; 4 else 5 max = num2; 6... Alternatively, one can use a conditional expression like this: y = (num1 > num2)? num1 : num2; 3... Be aware that an extreme concise expression is not always good Recall the reason why we develop so many high-level programming languages. Zheng-Liang Lu Java Programming 115 / 146
67 Formatting Console Output You can use System.out.printf () to display formatted output on the console double amount = ; 3 double interestrate = ; 4 double interest = amount interestrate; 5 System.out.printf("Interest = %4.2f", interest); 6... Zheng-Liang Lu Java Programming 116 / 146
68 By default, a floating-point value is displayed with 6 digits after the decimal point. Zheng-Liang Lu Java Programming 117 / 146
69 Example: Multiple Items Items must match the format specifiers in order, in number, and in exact type. If an item requires more spaces than the specified width, the width is automatically increased. By default, the output is right justified. You can put the minus sign (-) in the format specifier to specify that the item is left justified in the output within the specified field. Zheng-Liang Lu Java Programming 118 / 146
70 Problem Set 20 Exercise 3.1 (Roots of 2 nd -order polynomials) Write a program which solves y = ax 2 + bx + c for all x, a, b, c R using the following formula: x = b ± b 2 4ac. 2a Note that a complex root and its conjugate are allowed in general. Zheng-Liang Lu Java Programming 119 / 146
71 Exercise 3.2 (Game: scissor, rock, paper) Write a program that plays the popular scissor-rockpaper game. The program randomly generates a number 0, 1, or 2 representing scissor, rock, and paper. The program prompts the user to enter a number 0, 1, or 2 and displays a message indicating whether the user or the computer wins, loses, or draws. Zheng-Liang Lu Java Programming 120 / 146
72 Exercise 3.3 (Sort three integers) Write a program that sorts three integers. The integers are entered from the input dialogs and stored in 3 variables. For example, the input is a = 1, b = 5, c = 2. Then the program display the 3 numbers in ascending order, that is, 1 < 2 < 5. Exercise 3.4 (Compute the perimeter of a triangle) Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge. Zheng-Liang Lu Java Programming 121 / 146
73 Exercise 3.5 (Geometry: points in triangle?) Suppose a right triangle is placed in a plane as shown below. The right-angle point is placed at (0, 0), and the other two points are placed at (200, 0), and (0, 100). Write a program that prompts the user to enter a point with x- and y-coordinates and determines whether the point is inside the triangle. Exercise 3.6 (Geometry: point in a circle?) Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the circle centered at (0, 0) with radius 10. Zheng-Liang Lu Java Programming 122 / 146
74 Exercise 3.7 (Game: pick a card) Write a program that simulates picking a card from a deck of 52 cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) and suit (Clubs, Diamonds, Hearts, Spades) of the card. Exercise 3.8 (Finance: currency exchange) Write a program that prompts the user to enter the exchange rate from currency in USD to TWD. Prompt the user to enter 0 to convert from USD to TWD and 1 to convert from TWD and USD. Prompt the user to enter the amount in USD or TWD to convert it to TWD or USD, respectively. 20 See Programming Exercises in YDL, p Zheng-Liang Lu Java Programming 123 / 146
75 1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 124 / 146
76 Loops A loop can be used to make a program execute statements repeatedly without having to code the same statements. For example, a program prints Hello, Java. for 100 times. 1 System.out.println("Hello, Java."); 2 System.out.println("Hello, Java."); // Copy and paste for 100 times 5. 6 System.out.println("Hello, Java."); Zheng-Liang Lu Java Programming 125 / 146
77 1 int cnt = 0; 2 while (cnt < 100) { 3 System.out.println("Hello, Java."); 4 cnt++; 5 } This is a simple example to show the power of loops. In practice, any routine which repeats couples of times 21 can be done by folding them into a loop. 21 I d like to call them patterns. Zheng-Liang Lu Java Programming 126 / 146
78 Flow Controls (Recap) The concept of looping, which is one of elements in algorithms, is fundamental to programming. Loops provide significant computation power. Loops bring an efficient way of programming. Loops could consume a lot of time We will visit the analysis of algorithms soon. Zheng-Liang Lu Java Programming 127 / 146
79 while Loops A while loop executes statements repeatedly while the condition is true while (condition) { 3 // loop body 4 } 5... The condition is a Boolean expression which controls the execution of the body. It is evaluated each time to determine if the loop body is executed. If true, the loop body is executed. Otherwise, the entire loop terminates. Zheng-Liang Lu Java Programming 128 / 146
80 Zheng-Liang Lu Java Programming 129 / 146
81 Example Write a program which sums up all integers from 1 to 100. In math, the question can be: sum = But the form is not doable in a computer. What is?! Think in a programmer s way. Zheng-Liang Lu Java Programming 130 / 146
82 Normally, the computer executes the instructions sequentially. 23 So, one needs to decompose the math equation into several lines, like: 1 int sum = 0; 2 sum = sum + 1; 3 sum = sum + 2; sum = sum + 100; Cons: Not efficient, not general (what if sum up to 10 10?) 23 If we are talking about the parallel computing, then it is a different world. Zheng-Liang Lu Java Programming 131 / 146
83 Using a while loop, the program looks like this: int sum = 0; 3 int i = 0; 4 while (++i <= 100) 5 sum = sum + i; 6... Make sure that the condition eventually becomes false so that the loop will terminate. It is really easy to make an infinite loop while(true); 3... Zheng-Liang Lu Java Programming 132 / 146
84 Besides, replacing 100 by n determined by the user makes this program more general Scanner input = new Scanner(System.in); 3 int n = input.nextint(); 4 int sum = 0; 5 int i = 0; 6 while (++i <= n) 7 sum = sum + i; 8... In practice, the number of loop steps is unknown until the input data is given. For example, the bisection algorithm 24 provides a numerical solution to root-finding problems Zheng-Liang Lu Java Programming 133 / 146
85 Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct public static void main (String[] args) { 3 // random integer generation 4 int number1 = (int)(math.random() % 10); 5 int number2 = (int)(math.random() % 10); 6 7 Scanner input = new Scanner(Sysmte.in); 8 System.out.println(number1 + " + " + number2 + " =?"); 9 int ans = input.nextint(); 0 1 while (number1 + number2!= ans) { 2 System.out.println("Wrong answer. Try again?"); 3 ans = input.nextint(); 4 } 5 System.out.println("Congrats! You are smart!"); 6 } 7... Zheng-Liang Lu Java Programming 134 / 146
86 Exercise 25 Write a program which runs for a predetermined time, say, one minute, and terminates itself. You may use System.currentTimeMillis() to produce a time stamp. 25 Contribution by Ms. Hsu, Tzu-Hen (JB25318) on June 6, Zheng-Liang Lu Java Programming 135 / 146
87 public static void main(string[] args) { 3 Scanner input = new Scanner(System.in); 4 long t0 = System.currentTimeMillis(); 5 System.out.println("Duration? (ms) "); 6 long interval = input.nextint(); 7 input.close(); 8 while (System.currentTimeMillis() <= t0 + interval) 9 System.out.println("Running..."); 0 System.out.println("End."); 1 } 2... Zheng-Liang Lu Java Programming 136 / 146
88 Loop Design Strategies Writing a correct loop is not an easy task for novice programmers. Consider 3 steps when writing a loop: Find the pattern: Identify the statements that need to be repeated. Wrap: Wrap these statements in a loop. Set the continuation condition Not unique. Zheng-Liang Lu Java Programming 137 / 146
89 Sentinel-Controlled Loop Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value, signifies the end of the loop. Zheng-Liang Lu Java Programming 138 / 146
90 Example Write a program which sums real numbers from the input except for -1 to exit, and displays the sum Scanner in = new Scanner(System.in); 3 double sum = 0; 4 System.out.println("Enter a positive integer ( 1 to exit): "); 5 double x = in.nextdouble(); 6 while(x!= 1) { 7 sum += x; 8 System.out.println("Enter a positive integer ( 1 to exit): "); 9 x = in.nextdouble(); 0 } 1 System.out.println("Sum = " + sum); 2 in.close(); 3... Line 8 and 9 are the recurrence of Line 4 and 5?! Zheng-Liang Lu Java Programming 139 / 146
91 do-while Loops A do-while loop is the same as a while loop except that it does execute the loop body first and then checks the loop continuation condition do { 3 // loop body 4 } while (condition); // Do not miss the semicolon! 5... Note that there is a semicolon at the end the do-while loop. do-while loops are also called posttest loop, in contrast to while loops, which are pretest loops. Zheng-Liang Lu Java Programming 140 / 146
92 Zheng-Liang Lu Java Programming 141 / 146
93 Example Write a program which allows the user to enter positive integers except for -1 to exit, and displays the maximum. Zheng-Liang Lu Java Programming 142 / 146
94 Scanner in = new Scanner(System.in); 3 int max = 0, x; 4 do{ 5 System.out.println("Please enter a positive integer ( 1 to exit): "); 6 x = in.nextint(); 7 if(max < x) { 8 max = x; 9 } 0 System.out.println("Max = " + max); 1 } while(x!= 1); 2 in.close(); 3... Zheng-Liang Lu Java Programming 143 / 146
95 for Loops A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates for(init; condition; increment) { 3 // loop body 4 } 5... init: initialize a variable condition: a criteria that a loop continues increment: how the variable changes after each iteration Note that the three terms are separated by a semicolon. Zheng-Liang Lu Java Programming 144 / 146
96 Example Sum from 1 to 100 Write a program which sums from 1 to int sum = 0; 3 for (int i = 1; i <= 100; ++i) 4 sum = sum + i; 5... Compared to the while version, int sum = 0; 3 int i = 0; 4 while (++i <= 100) 5 sum = sum + i; 6... Zheng-Liang Lu Java Programming 145 / 146
97 Zheng-Liang Lu Java Programming 146 / 146
Zheng-Liang Lu Java Programming 45 / 79
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius
More informationScanner Objects. Zheng-Liang Lu Java Programming 82 / 133
Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object
More information++x vs. x++ We will use these notations very often.
++x vs. x++ The expression ++x first increments the value of x and then returns x. Instead, the expression x++ first returns the value of x and then increments itself. For example, 1... 2 int x = 1; 3
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationLogic is the anatomy of thought. John Locke ( ) This sentence is false.
Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than
More informationIEEE Floating-Point Representation 1
IEEE Floating-Point Representation 1 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted
More informationData Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87
Data Types Java is a strongly-typed 1 programming language. Every variable has a type. Also, every (mathematical) expression has a type. There are two categories of data types: primitive data types, and
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted
More information1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 41 / 68 Example Given the radius
More informationExample. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.
Example Generating random numbers Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationExample. Write a program which generates 2 random integers and asks the user to answer the math expression.
Generating random numbers Example Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationCommon Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141
Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 172 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationswitch-case Statements
switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;
More information1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207
1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 Loops A loop can be used to make a program execute statements repeatedly without having
More informationEng. Mohammed S. Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 3 Selections
More informationComputer Programming, I. Laboratory Manual. Experiment #3. Selections
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More information1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199
1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize
More informationMotivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018
Motivating Examples (1.1) Selections EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG 1 import java.util.scanner; 2 public class ComputeArea { 3 public static void main(string[] args)
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationChapter 2 ELEMENTARY PROGRAMMING
Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple
More informationComputer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2
More informationSelections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG
Selections EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes The Boolean Data Type if Statement Compound vs. Primitive Statement Common Errors
More informationEntry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process
Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will
More informationCEN 414 Java Programming
CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationTester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time
Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester
More informationElementary Programming
Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal
More informationChapter 2 Elementary Programming
Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More informationLecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value
Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to
More informationCS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University
CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Generating random numbers Obtain a random double value between 0.0 and 1.0, excluding 1.0 Math.random() Random
More informationCCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives
LIANMC03v3_0132221586.QXD 5/15/06 7:41 PM Page 67 CCHAPTER HAPTER 3 1 SELECTION STATEMENTS Objectives To declare boolean type and write Boolean expressions ( 3.2). To distinguish between conditional and
More informationChapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius
More informationChapter 3: Operators, Expressions and Type Conversion
101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To
More informationExpressions and Data Types CSC 121 Spring 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types
More informationEntry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes
Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the
More informationChapter 3 Selection Statements
Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are
More informationExercise (Revisited)
Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price?"); 4 price = input.nextint(); 5 if (price
More informationJava Programming Language. 0 A history
Java Programming Language 0 A history How java works What you ll do in Java JVM API Java Features 0Platform Independence. 0Object Oriented. 0Compiler/Interpreter 0 Good Performance 0Robust. 0Security 0
More informationIntroduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017
Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor
More informationAssoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical
More informationChapter 3. Selections
Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of
More informationThese are reserved words of the C language. For example int, float, if, else, for, while etc.
Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.
More informationJAVA OPERATORS GENERAL
JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationExpressions and Data Types CSC 121 Fall 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and
More informationControl Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003
Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an
More informationDate: Dr. Essam Halim
Assignment (1) Date: 11-2-2013 Dr. Essam Halim Part 1: Chapter 2 Elementary Programming 1 Suppose a Scanner object is created as follows: Scanner input = new Scanner(System.in); What method do you use
More informationCOMP 202 Java in one week
CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language
More informationChapter 2. Elementary Programming
Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,
More informationVariable Scope. The variable scope is the range of the program where the variable can be referenced.
Variable Scope The variable scope is the range of the program where the variable can be referenced. Variables can be declared in class level, method level, and loop level. In general, a pair of curly brackets
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationExpression statements are formed by adding a semicolon to the end of certain types of expressions.
Expression statements are formed by adding a semicolon to the end of certain types of expressions. Variable declaration statements declare variables. int width, height, area; String hello = "Hello, world!";
More informationJava Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2
Java Foundations Introduction to Program Design and Data Structures 4th Edition Lewis TEST BANK Full download at : https://testbankreal.com/download/java-foundations-introduction-toprogram-design-and-data-structures-4th-edition-lewis-test-bank/
More informationChapter 4 Introduction to Control Statements
Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?
More informationData and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence
Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public
More informationCPS122 Lecture: From Python to Java last revised January 4, Objectives:
Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.
More informationJAVA Programming Fundamentals
Chapter 4 JAVA Programming Fundamentals By: Deepak Bhinde PGT Comp.Sc. JAVA character set Character set is a set of valid characters that a language can recognize. It may be any letter, digit or any symbol
More informationComputer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #4
More informationWhat did we talk about last time? Examples switch statements
Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics
Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional
More informationChapter 2: Data and Expressions
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types
More informationCourse Outline. Introduction to java
Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.
More informationIntroduction to Java Applications
2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use
More informationCOMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few
More informationCOMP 202. Java in one week
COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language
More informationCS111: PROGRAMMING LANGUAGE II
1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics
WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationChapter 2: Data and Expressions
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data
More informationImportant Java terminology
1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as
More informationOct Decision Structures cont d
Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements
More informationComputer System and programming in C
1 Basic Data Types Integral Types Integers are stored in various sizes. They can be signed or unsigned. Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign
More informationMotivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution
Chapter 2: Elementary Programming CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations In the preceding chapter, you learned how to
More informationChapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 2 Elementary Programming 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems
More informationFull file at
Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional
More informationMore Programming Constructs -- Introduction
More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and
More informationLecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18
Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical
More informationRepetition, Looping. While Loop
Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions
More informationCONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2
CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,
More information3 The L oop Control Structure
3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement
More informationUnit 1 Lesson 4. Introduction to Control Statements
Unit 1 Lesson 4 Introduction to Control Statements Essential Question: How are control loops used to alter the execution flow of a program? Lesson 4: Introduction to Control Statements Objectives: Use
More informationBasic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java
Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection
More informationPlease answer the following questions. Do not re-code the enclosed codes if you have already completed them.
Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?
More informationProgram Control Flow
Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationProgram Control Flow
Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationbitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=
Operators in java Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in java which are given below: Unary Operator, Arithmetic
More informationJava Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University
Java Programming U Hou Lok Department of Computer Science and Information Engineering, National Taiwan University Java 272 8 19 Aug, 2016 U Hou Lok Java Programming 1 / 78 Class Information Lecturer: U
More informationOutline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.
OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce
More information