Arithmetic Compound Assignment Operators

Size: px
Start display at page:

Download "Arithmetic Compound Assignment Operators"

Transcription

1 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

2 Example int x = 1; 3 System.out.println(x); // output 1 4 x = x + 1; 5 System.out.println(x); // output 2 6 x += 2; 7 System.out.println(x); // output 4 8 x++; // equivalent to x += 1 and x = x System.out.println(x); // output Zheng-Liang Lu Java Programming 77 / 172

3 The compound assignment operators are also useful for char values. 1 For example, char s = a ; 3 System.out.println(s); // output a 4 s += 1; 5 System.out.println(s); // output b 6 s++; 7 System.out.println(s); // output c Contribution by Mr. Edward Wang (Java265) on May 1, Zheng-Liang Lu Java Programming 78 / 172

4 ++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, int x = 1; 3 int y = ++x; 4 System.out.println(y); // output 2; aka preincrement 5 System.out.println(x); // output int w = 1; 8 int z = w++; 9 System.out.println(z); // output 1; aka postincrement 10 System.out.println(w); // output We will use these notations very often. Zheng-Liang Lu Java Programming 79 / 172

5 Operator Precedence 2 2 See Table3-10 in YDL, p Zheng-Liang Lu Java Programming 80 / 172

6 Using Parentheses Parentheses are used in expressions to change the natural order of precedence among the operators. One always evaluates the expression inside of parentheses first. Zheng-Liang Lu Java Programming 81 / 172

7 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 provides some input methods, say the input received from the keyboard or the files. Java uses System.in to refer to the standard input device, by default, the keyboard. Zheng-Liang Lu Java Programming 82 / 172

8 Example: Reading Input From The Console Write a program which receives a number as input, and outputs the area of the circle. 1 import java.util.scanner; Scanner input = new Scanner(System.in); 4 System.out.println("Enter r?"); 5 // input 6 int r = input.nextint(); 7 // algorithm 8 double area = r r 3.14; 9 // output 10 System.out.println(area); 11 input.close(); Zheng-Liang Lu Java Programming 83 / 172

9 In the listing, Line 3 is to create a Scanner object by the new operator, as an agent between the keyboard and your program. Note that all objects are resided in the heap of the memory. To control this object, its memory address is then assigned to the variable input which is a variable in the stack of memory. So the variable input is a reference. We will discuss the objects and reference variables later. Zheng-Liang Lu Java Programming 84 / 172

10 Methods Provided by Scanner Objects 3 3 See Table 2-1 in YDL, p. 38. Zheng-Liang Lu Java Programming 85 / 172

11 Example: Mean and Standard Deviation Write a program which calculates the mean and the standard deviation of 3 numbers. The mean of 3 numbers is given by x = ( 3 i=1 x i Also, the resulting standard deviation is given by S = 3 i=1 (x i x) 2. 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. ) /3. Zheng-Liang Lu Java Programming 86 / 172

12 Scanner input = new Scanner(System.in); 3 System.out.println("a =?"); 4 double a = input.nextdouble(); 5 System.out.println("b =?"); 6 double b = input.nextdouble(); 7 System.out.println("c =?"); 8 double c = input.nextdouble(); 9 10 double mean = (a + b + c) / 3; 11 double std = Math.sqrt((Math.pow(a mean, 2) + 12 Math.pow(b mean, 2) + 13 Math.pow(c mean, 2)) / 3); System.out.println("mean = " + mean); 16 System.out.println("std = " + std); Zheng-Liang Lu Java Programming 87 / 172

13 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 / 172

14 Flow Controls The basic algorithm (and program) is constituted by the following operations: Sequential statements: execute instructions in order. Selection: first check if the predetermined condition is satisfied, then execute the corresponding instruction. Repetition: repeat the execution of some instructions until the criterion fails. Zheng-Liang Lu Java Programming 89 / 172

15 Note that they are involved with each other generally. For example, recall how to find the maximum in the input list? Zheng-Liang Lu Java Programming 90 / 172

16 Selections One-way if statements Two-way if-else statements Nested if statements Multiway if-else if-else statements switch-case statements Conditional operators Zheng-Liang Lu Java Programming 91 / 172

17 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 92 / 172

18 if (condition) { 3 // selection body 4 } 5... 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 and skip the whole selection body. Note that the braces can be omitted if the block contains only single statement. Zheng-Liang Lu Java Programming 93 / 172

19 Example Write a program which receives a nonnegative number as input for the radius of a circle, and determines the area of the circle double area; 3 if (r > 0) { 4 area = r r 3.14; 5 System.out.println(area); 6 } 7... However, the world is not well-defined. Zheng-Liang Lu Java Programming 94 / 172

20 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 if (condition) { 3 // body for the true case 4 } else { 5 // body for the false case 6 } 7... Zheng-Liang Lu Java Programming 95 / 172

21 Zheng-Liang Lu Java Programming 96 / 172

22 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, output Not a circle double area; 3 if (r > 0) { 4 area = r r 3.14; 5 System.out.println(area); 6 } else { 7 System.out.println("Not a circle."); 8 } 9 input.close(); 10 } Zheng-Liang Lu Java Programming 97 / 172

23 Nested if Statements For example, if (score >= 90) 3 System.out.println("A"); 4 else { 5 if (score >= 80) 6 System.out.println("B"); 7 else { 8 if (score >= 70) 9 System.out.println("C"); 10 else { 11 if (score >= 60) 12 System.out.println("D"); 13 else 14 System.out.println("F"); 15 } 16 } 17 } Zheng-Liang Lu Java Programming 98 / 172

24 Multi-Way if-else Let s redo the previous problem if (score >= 90) 3 System.out.println("A"); 4 else if (score >= 80) 5 System.out.println("B"); 6 else if (score >= 70) 7 System.out.println("C"); 8 else if (score >= 60) 9 System.out.println("D"); 10 else 11 System.out.println("F"); An if-elseif-else statement is a preferred format for multiple alternatives, in order to avoid deep indentation and make the program easy to read. Zheng-Liang Lu Java Programming 99 / 172

25 The order of conditions may be relevant. (Why?) if (score >= 90 && score <= 100) 3 else if (score >= 80 && score < 90) else 6... The performance may degrade due to the order of conditions. (Why?) Zheng-Liang Lu Java Programming 100 / 172

26 Common 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 / 172

27 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 =? 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. 4 4 You may see PRNG in Zheng-Liang Lu Java Programming 102 / 172

28 int x = (int) (Math.random() 10); // integers int y = (int) (Math.random() 10); 4 int answer = x + y; 5 6 System.out.println(x + " + " + y + " =?"); 7 8 Scanner input = new Scanner(System.in); 9 int z = input.nextint(); if (z == answer) 12 System.out.println("Correct."); 13 else 14 System.out.println("Wrong. Answer: " + answer); 15 input.close(); Can you extend this program for all arithmetic expressions (i.e., + )? Zheng-Liang Lu Java Programming 103 / 172

29 Exploring the unknown requires tolerating uncertainty. Brian Greene I can live with doubt, and uncertainty, and not knowing. I think it is much more interesting to live not knowing than have answers which might be wrong. Richard Feynman Zheng-Liang Lu Java Programming 104 / 172

30 Exercise Find Max Write a program which determines the maximum value in 3 random integers whose range from 0 to 99. How many variables do we need? How to compare? How to keep the maximum value? Zheng-Liang Lu Java Programming 105 / 172

31 int x = (int) (Math.random() 100); 3 int y = (int) (Math.random() 100); 4 int z = (int) (Math.random() 100); 5 6 int max = x; 7 if (y > max) max = y; 8 if (z > max) max = z; 9 System.out.println("max = " + max); In this case, a scalar variable is not convenient. (Why?) So we need arrays and loops. Zheng-Liang Lu Java Programming 106 / 172

32 switch-case Statements A switch-case structure takes actions depending on the target variable switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: case vk: 10 // statements 11 break; 12 default: 13 // statements 14 } Zheng-Liang Lu Java Programming 107 / 172

33 A switch-case statement is more convenient than an if statement for multiple discrete conditions. The variable target, always enclosed in parentheses, must yield a value of char, byte, short, int, or String type. The value v 1,..., and v k must have the same data type as the variable target. In each case, a break statement is a must. 5 break is used to break a construct! The default case, which is optional, can be used to perform actions when none of the specified cases matches target. Counterpart to else statements. 5 If not, there will be a fall-through behavior. Zheng-Liang Lu Java Programming 108 / 172

34 Example // RED: 0 3 // YELLOW: 1 4 // GREEN: 2 5 int trafficlight = (int) (Math.random() 3); 6 switch (trafficlight) { 7 case 0: 8 System.out.println("Stop!!!"); 9 break; 10 case 1: 11 System.out.println("Slow down!!"); 12 break; 13 case 2: 14 System.out.println("Go!"); 15 } Zheng-Liang Lu Java Programming 109 / 172

35 Conditional Operators A conditional expression evaluates an expression based on the specified condition and returns a value accordingly somevar = booleanexpr? expra : exprb; 3... This is the only ternary operator in Java. If the boolean expression is evaluated true, then return expr A; otherwise, expr B. Zheng-Liang Lu Java Programming 110 / 172

36 For example, if (num1 > num2) 3 max = num1; 4 else 5 max = num2; 6... Alternatively, one can use a conditional expression like this: max = (num1 > num2)? num1 : num2; 3... Zheng-Liang Lu Java Programming 111 / 172

37 1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 // keywords: 8 while, do, for, break, continue Zheng-Liang Lu Java Programming 112 / 172

38 Loops 6 A loop can be used to make a program execute statements repeatedly without having to code the same statements. For example, output Hello, Java. for 100 times System.out.println("Hello, Java."); 3 System.out.println("Hello, Java."); // copy and paste for 100 times 6. 7 System.out.println("Hello, Java."); You may try https: // Zheng-Liang Lu Java Programming 113 / 172

39 int cnt = 0; 3 while (cnt < 100) { 4 System.out.println("Hello, Java."); 5 cnt++; 6 } 7... This is a toy example to show the power of loops. In practice, any routine which repeats couples of times 7 can be done by folding them into a loop. 7 I prefer to call these routines patterns. Zheng-Liang Lu Java Programming 114 / 172

40 成也迴圈, 敗也迴圈 Loops provide substantial computational power. Loops bring an efficient way of programming. Loops could consume a lot of time. 8 8 We will introduce the analysis of algorithms soon. Zheng-Liang Lu Java Programming 115 / 172

41 while Loops A while loop executes statements repeatedly while the condition is true while (condition) { 3 // loop body 4 } 5... The condition should be a boolean expression which determines whether or not the execution of the body occurs. If true, the loop body is executed and check the condition again. Otherwise, the entire loop terminates. Zheng-Liang Lu Java Programming 116 / 172

42 Zheng-Liang Lu Java Programming 117 / 172

43 Example Write a program which sums up all integers from 1 to 100. In math, the question can be written as: sum = But this form is not doable in the machine. 9 9 We need to develop computational thinking. Read or Zheng-Liang Lu Java Programming 118 / 172

44 Normally, the machine executes the instructions sequentially. So one needs to decompose the math equation into several steps, like: int sum = 0; 3 sum = sum + 1; 4 sum = sum + 2; sum = sum + 100; 9... It is obvious that many similar statements can be found. Zheng-Liang Lu Java Programming 119 / 172

45 Using a while loop, the program can be rearranged as follows: int sum = 0; 3 int i = 1; 4 while (i <= 100) { 5 sum = sum + i; 6 ++i; 7 } 8... You should guarantee that the loop will terminate as expected. In practice, the number of loop steps (iterations) is unknown until the input data is given. Zheng-Liang Lu Java Programming 120 / 172

46 Malfunctioned Loops It is really easy to make an infinite loop while (true); 3... The common errors of the loops are: never start never stop not complete exceed the expected number of iterations Zheng-Liang Lu Java Programming 121 / 172

47 Example Write a program which asks the sum of two random integers and lets the user repeatedly enter a new answer until correct Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random() 10); 4 int y = (int) (Math.random() 10); 5 int ans = x + y; 6 7 System.out.println(x + " + " + y + " =? "); 8 int z = input.nextint(); 9 10 while (z!= ans) { 11 System.out.println("Try again? "); 12 z = input.nextint(); 13 } 14 System.out.println("Correct."); 15 input.close(); Zheng-Liang Lu Java Programming 122 / 172

48 Loop Design Strategy 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 by loops: put these statements in the loop. Set the continuation condition: translate the criterion from the real world problem into computational conditions Not unique. Zheng-Liang Lu Java Programming 123 / 172

49 Sentinel-Controlled Loops 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. For example, the operating systems and the GUI apps. Zheng-Liang Lu Java Programming 124 / 172

50 Example: Cashier Problem Write a program which sums over positive integers from consecutive inputs and then outputs the sum when the input is nonpositive int total = 0, price = 0; 3 Scanner input = new Scanner(System.in); 4 5 System.out.println("Enter price?"); 6 price = input.nextint(); 7 while (price > 0) { 8 total += price; 9 System.out.println("Enter price?"); 10 price = input.nextint(); 11 // These two lines above repeat Line 5 and 6?! 12 } System.out.println("Total = " + total); 15 input.close(); Zheng-Liang Lu Java Programming 125 / 172

51 do-while Loops A do-while loop is similar to 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 of the do-while loop. The do-while loops are also called posttest loops, in contrast to while loops, which are pretest loops. Zheng-Liang Lu Java Programming 126 / 172

52 Zheng-Liang Lu Java Programming 127 / 172

53 Example (Revisted) Write a program which sums over positive integers from consecutive inputs and then outputs the sum when the input is nonpositive int total = 0, price = 0; 3 Scanner input = new Scanner(System.in); 4 5 do { 6 total += price; 7 System.out.println("Enter price?"); 8 price = input.nextint(); 9 } while (price > 0); System.out.println("Total = " + total); 12 input.close(); Zheng-Liang Lu Java Programming 128 / 172

54 for Loops A for loop generally uses a variable to control how many times the loop body is executed for (init action; condition; increment) { 3 // loop body 4 } 5... init-action: declare and initialize a variable condition: set a criterion for loop continuation increment: how the variable changes after each iteration Note that these terms are separated by semicolons. Zheng-Liang Lu Java Programming 129 / 172

55 Sum from 1 to 100 Example 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 = 1; 4 while (i <= 100) { 5 sum = sum + i; 6 ++i; 7 } 8... Zheng-Liang Lu Java Programming 130 / 172

56 Zheng-Liang Lu Java Programming 131 / 172

57 Example: Selection Resided in Loop Display all even numbers Write a program which displays all even numbers smaller than 100. An even number is an integer of the form x = 2k, where k is an integer. Zheng-Liang Lu Java Programming 132 / 172

58 You may use the modular operator (%) for (int i = 1; i <= 100; i++) { 3 if (i % 2 == 0) System.out.println(i); 4 } 5... Also consider this alternative: for (int i = 2; i <= 100; i += 2) { 3 System.out.println(i); 4 } 5... How about odd numbers? Zheng-Liang Lu Java Programming 133 / 172

59 Numerical Example: Monte Carlo Simulation 11 Let m be the number of sample points falling in the region of the quarter circle shown in the next page, n be the total number of sample points. Use rand to generate a value between 0 and 1 (exclusive). Write a program which estimates π by ˆπ = 4 m n. Note that ˆπ π as n by the law of large numbers (LLN). 11 See Zheng-Liang Lu Java Programming 134 / 172

60 Zheng-Liang Lu Java Programming 135 / 172

61 Numerical Example: Bisection Method for Root-Finding 13 Assume that f (x) = x 3 x 2. Consider to find a root between [a, b] = [1, 2] as initial guess. 12 Write a program which calculates the approximate root ˆr under this requirement by using the bisection method. In particular, you may set an error tolerance, say ɛ = 1e 9, to strike a balance between efficiency and accuracy. 12 For most of numerical algorithms, say Newton s method, an initial guess is a must. Even more, the solution is severely sensitive to the initial guess for some cases. 13 See Zheng-Liang Lu Java Programming 136 / 172

62 method#/media/file:bisection method.svg Zheng-Liang Lu Java Programming 137 / 172

63 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: the loop skips this iteration right after a continue statement is executed. In practice, jump statements in loops should be conditioned. Zheng-Liang Lu Java Programming 138 / 172

64 Example: Primality Test Write a program which determines if the input integer is a prime number. Let x > 1 be any natural number. Then x is said to be a prime number if x has no positive divisors other than 1 and itself. It is then straightforward to check if it is prime by dividing x by all natural numbers smaller than x. For speedup, you can divide x by only numbers smaller than x. (Why?) Zheng-Liang Lu Java Programming 139 / 172

65 Scanner input = new Scanner(System.in); 3 System.out.println("Enter x > 2?"); 4 int x = input.nextint(); 5 boolean isprime = true; 6 input.close(); 7 8 double upperbd = Math.sqrt(x); 9 for (int y = 2; y < upperbd; y++) { 10 if (x % y == 0) { 11 isprime = false; 12 break; 13 } 14 } if (isprime) { 17 System.out.println("Prime"); 18 } else { 19 System.out.println("Composite"); 20 } Zheng-Liang Lu Java Programming 140 / 172

66 Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement while (true) { 3 System.out.println("Enter price?"); 4 price = input.nextint(); 5 if (price <= 0) break; 6 total += price; 7 } 8 System.out.println("Total = " + total); 9... Zheng-Liang Lu Java Programming 141 / 172

67 Another Example: Compounding Write a program which determines the holding years for an investment doubling its value. Let balance be the current amount, goal be the goal of this investment, and r be the annual interest rate. Then this investment should take at least n years so that the balance of the investment can double its value. Recall that the compounding formula is given by balance = balance (1 + r/100). Zheng-Liang Lu Java Programming 142 / 172

68 int r = 18; // 18% 3 int balance = 100; 4 int goal = 200; 5 6 int years = 0; 7 while (balance <= goal) { 8 balance = (1 + r / 100.0); 9 years++; 10 } System.out.println("Balance = " + balance); 13 System.out.println("Years = " + years); Zheng-Liang Lu Java Programming 143 / 172

69 int years = 0; // should be declared here; scope issue 3 for (; balance <= goal; years++) { 4 balance = (1 + r / 100.0); 5 } int years = 1; // check this initial value 3 for (; true; years++) { 4 balance = (1 + r / 100.0); 5 if (balance > goal) break; 6 } 7... A for loop can be an infinite loop by setting true or simply leaving empty in the condition statement. An infinite for loop with an if-break statement is equivalent to a normal while loop. Zheng-Liang Lu Java Programming 144 / 172

70 Equivalence: while and for Loops (Concluded) In general, a for loop may be used if the number of repetitions is known in advance. If not, a while loop is preferred. Zheng-Liang Lu Java Programming 145 / 172

71 Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew. Zheng-Liang Lu Java Programming 146 / 172

72 Example Multiplication table Write a program which displays the multiplication table. Zheng-Liang Lu Java Programming 147 / 172

73 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 148 / 172

74 By default, a floating-point value is displayed with 6 digits after the decimal point. Zheng-Liang Lu Java Programming 149 / 172

75 Multiple Items to Print 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 may try the plus sign (+), the minus sign (-), and 0 in the middle of format specifiers. Say % + 8.2f, % 8.2f, and %08.2f. Zheng-Liang Lu Java Programming 150 / 172

76 public static void main(string[] args) { 3 for (int i = 1; i <= 9; ++i) { 4 for (int j = 1; j <= 9; ++j) { 5 System.out.printf("%3d", i j); 6 } 7 System.out.println(); 8 } 9 } Zheng-Liang Lu Java Programming 151 / 172

77 Exercise: Coupled Loops Zheng-Liang Lu Java Programming 152 / 172

78 1 public class PrintStarsDemo { 2 public static void main(string[] args) { 3 // case (a) 4 for (int i = 1; i <= 5; i++) { 5 for (int j = 1; j <= i; j++) { 6 System.out.printf(" "); 7 } 8 System.out.println(); 9 } // case (b), (c), (d) 12 // your work here 13 } 14 } Zheng-Liang Lu Java Programming 153 / 172

79 Analysis of Algorithms First, there may exist some algorithms for the same problem. Then we compare these algorithms. The first question is, Which one is more efficient? (Why?) We focus on the growth rate of the running time or space requirement as a function of the input size n, denoted by f (n). Zheng-Liang Lu Java Programming 154 / 172

80 O-notation 14 In math, O-notation describes the limiting behavior of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions. f (n) O(g(n)) as n if and only if there is a constant c > 0 and a real number n 0 such that f (n) c g(n) n n 0. (1) Note that O(g(n)) is a set featured by some simple function g(n). Hence f (n) O(g(n)) is equivalent to say that f (n) is one instance of O(g(n)). 14 See any textbook for data structures and algorithms or Zheng-Liang Lu Java Programming 155 / 172

81 For example, 8n 2 3n + 4 O(n 2 ). We could say that 8n 2 3n + 4 O(n 3 ) and 8n 2 3n + 4 / O(n). Zheng-Liang Lu Java Programming 156 / 172

82 Common Fundamental Functions See Table 4.1 and Figure 4.2 in Goodrich and etc, p Zheng-Liang Lu Java Programming 157 / 172

83 We use O-notation to describe the asymptotic 16 upper bound of complexity of the algorithm. So O-notation is widely used to classify algorithms by how they respond to changes in its input size. 17 Time complexity Space complexity Note that we often make a trade-off between time and space. Unlike time, we can reuse memory. 16 The asymptotic sense is that the input size n grows toward infinity. 17 Actually, there are Θ, θ, o, Ω, and ω which are used to classify algorithms. Zheng-Liang Lu Java Programming 158 / 172

84 References Zheng-Liang Lu Java Programming 159 / 172

85 1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 160 / 172

86 Arrays An array stores a large collection of data which is of the same type // assume the size variable exists above 3 T[] A = new T[size]; 4 // this creates an array of T type, referenced by A 5... T can be any data type. This statement comprises two parts: Declaring a reference Creating an array Zheng-Liang Lu Java Programming 161 / 172

87 Variable Declaration for Arrays In the left-hand side, it is a declaration for an array variable, which does not allocate real space for the array. In reality, this variable occupies only a certain space for the reference to an array. 18 If a reference variable does not refer to an array, the value of the variable is null. 19 In this case, you cannot assign elements to this array variable unless the array object has already been created. 18 Recall the stack and the heap in the memory layout. 19 Moreover, this holds for any reference variable. For example, the Scanner type. Zheng-Liang Lu Java Programming 162 / 172

88 Creating A Real Array All arrays of Java are objects. As seen before, the new operator returns the memory address of that object. Recall that the type of reference variables must be compatible to that of the array object. The variable size must be a positive integer for the number of elements. Note that the size of an array cannot be changed after the array is created Alternatively, you may try the class ArrayList, which is more useful in practice. Zheng-Liang Lu Java Programming 163 / 172

89 Array in Memory 1 int[] A = new int[3]; The array is allocated contiguously in the memory. All arrays are zero-based indexing. 21 (Why?) So we have A[0], A[1], and A[2]. 21 Same in C, C++, python, Javascript, and more. Zheng-Liang Lu Java Programming 164 / 172

90 Array Initializer The elements of arrays are initialized once created. By default, every element is assigned as follows: 0 for all numeric primitive data types \u0000 for char type false for boolean type An array can also be initialized by enumerating all the elements without using the new operator. For example, 1 int[] A = {1, 2, 3}; Zheng-Liang Lu Java Programming 165 / 172

91 Processing Arrays When processing array elements, we often use for loops. Recall that arrays are objects. They have an attribute called length which records the size of the arrays. For example, use A.length to get the size of A. Since the size of the array is known, it is natural to use a for loop to manipulate with the array. Zheng-Liang Lu Java Programming 166 / 172

92 Many Examples Initialization of arrays by a Scanner object // let x be an integer array with a certain size 3 for (int i = 0; i < A.length; ++i) { 4 A[i] = input.nextint(); 5 } 6... Initialization of arrays by random numbers for (int i = 0; i < A.length; ++i) { 3 A[i] = (int) (Math.random() 10); 4 } 5... Zheng-Liang Lu Java Programming 167 / 172

93 Display of array elements for (int i = 0; i < A.length; ++i) { 3 System.out.printf("%3d", A[i]); 4 } 5... Sum of array elements int sum = 0; 3 for (int i = 0; i < A.length; ++i) { 4 sum += A[i]; 5 } 6... Zheng-Liang Lu Java Programming 168 / 172

94 Extreme values in the array int max = A[0]; 3 int min = A[0]; 4 for (int i = 1; i < A.length; ++i) { 5 if (max < A[i]) max = A[i]; 6 if (min > A[i]) min = A[i]; 7 } 8... How about the location of the extreme values? Can you find the 2nd max of A? Can you keep the first k max of A? Zheng-Liang Lu Java Programming 169 / 172

95 Shuffling over array elements for (int i = 0; i < A.length; ++i) { 3 // choose j randomly 4 int j = (int) (Math.random() A.length); 5 // swap 6 int tmp = A[i]; 7 A[i] = A[j]; 8 A[j] = tmp; 9 } How to swap values of two variables without tmp? However, this naive algorithm is biased See Zheng-Liang Lu Java Programming 170 / 172

96 Exercise Deck of Cards Write a program which picks first 5 cards at random from a deck of 52 cards. 4 suits: Spade, Heart, Diamond, Club 13 ranks: 3,..., 10, J, Q, K, A, 2 Label 52 cards by 0, 1,, 51 Shuffle the numbers Deal the first 5 cards Zheng-Liang Lu Java Programming 171 / 172

97 String[] suits = {"Spade", "Heart", "Diamond", "Club"}; 3 String[] ranks = {"3", "4", "5", "6", "7", 4 "8", "9", "10", "J", "Q", "K", 5 "A", "2"}; 6 7 int size = 52; 8 int[] deck = new int[size]; 9 for (int i = 0; i < deck.length; i++) 10 deck[i] = i; // shuffle over deck; correct version 13 for (int i = 0; i < size 1; i++) { 14 int j = (int) (Math.random() (size i)) + i; 15 int z = deck[i]; 16 deck[i] = deck[j]; 17 deck[j] = z; 18 } for (int i = 0; i < 5; i++) { 21 String suit = suits[deck[i] / 13]; 22 String rank = ranks[deck[i] % 13]; 23 System.out.printf("% 3s%8s\n", rank, suit); 24 } Zheng-Liang Lu Java Programming 172 / 172

Arithmetic Compound Assignment Operators

Arithmetic 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 information

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Scanner 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

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Logic 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 information

Common 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 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 information

1 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 // 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 information

++x vs. x++ We will use these notations very often.

++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 information

1 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 // 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 information

Jump 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. 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 information

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Example. 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 information

switch-case Statements

switch-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 information

Jump 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. 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 information

Example. 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. 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 information

Example: Monte Carlo Simulation 1

Example: 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 information

Example. 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. 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 information

IEEE Floating-Point Representation 1

IEEE 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 information

Exercise (Revisited)

Exercise (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 information

Nested Loops. A loop can be nested inside another loop.

Nested Loops. A loop can be nested inside another loop. Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started

More information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Data 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 information

Values in 2 s Complement

Values in 2 s Complement 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,

More information

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

1 class Lecture5 { 2 3 Arrays 4. Zheng-Liang Lu Java Programming 136 / 174 1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 136 / 174 Arrays An array stores a large collection of data which is of the same type. 2 // assume the size variable exists above 3

More information

1 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 / 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

Variable 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. 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 information

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1 Shuffling over array elements 1... 2 for (int i = 0; i < A.length; ++i) { 3 // choose j randomly 4 int j = (int) (Math.random() A.length); 5 // swap 6 int tmp = A[i]; 7 A[i] = A[j]; 8 A[j] = tmp; 9 } 10...

More information

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Motivating 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 information

Selections. 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 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

1 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 / 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 information

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for and while Primitive

More information

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Computer 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 information

Example. Password generator

Example. Password generator Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that

More information

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes Motivation of Loops Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG We may want to repeat the similar action(s) for a (bounded) number of times. e.g., Print the Hello World message

More information

1 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 / 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 information

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

Chapter 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. 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 information

Elementary Programming

Elementary 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 information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

Zheng-Liang Lu Java Programming 45 / 79

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 information

Chapter 3. Selections

Chapter 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 information

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Loops EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester 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 information

Eng. Mohammed S. Abdualal

Eng. 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer 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 information

Selec%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 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 information

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;

More information

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes Motivation of Loops Loops EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG We may want to repeat the similar action(s) for a (bounded) number of times. e.g., Print

More information

Selec%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 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 information

Selections. Zheng-Liang Lu 91 / 120

Selections. Zheng-Liang Lu 91 / 120 Selections ˆ Selection enables us to write programs that make decisions on. ˆ Selection structures contain one or more of the if, else, and elseif statements. ˆ The end statement denotes the end of selection

More information

Program Control Flow

Program 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 information

Program Control Flow

Program 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 information

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

More information

Java 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 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 information

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry 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 information

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1 Name SOLUTION Page Points Score 2 15 3 8 4 18 5 10 6 7 7 7 8 14 9 11 10 10 Total 100 1 P age 1. Program Traces (41 points, 50 minutes)

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 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 information

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction 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 information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. 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 information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: 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 information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Please 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 information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Pace University. Fundamental Concepts of CS121 1

Pace 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 information

3 The L oop Control Structure

3 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 information

Repetition, Looping. While Loop

Repetition, 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 information

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.

More information

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

CCHAPTER 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 information

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

More information

Java 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 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 information

Programming with Java

Programming 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 information

Introduction to Java Applications

Introduction 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 information

CompSci 125 Lecture 11

CompSci 125 Lecture 11 CompSci 125 Lecture 11 switch case The? conditional operator do while for Announcements hw5 Due 10/4 p2 Due 10/5 switch case! The switch case Statement Consider a simple four-function calculator 16 buttons:

More information

Chapter 3 Selection Statements

Chapter 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 information

Date: Dr. Essam Halim

Date: 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 information

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Entry 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 information

Exercise: Sorting 1. ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order).

Exercise: Sorting 1. ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order). Exercise: Sorting 1 ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order). ˆ For example, A = [5, 4, 1, 2, 3]. ˆ Then the sorted array is [1, 2, 3, 4, 5]. ˆ You

More information

Computer Programming I - Unit 5 Lecture page 1 of 14

Computer Programming I - Unit 5 Lecture page 1 of 14 page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements

More information

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables Java Program Structure // comments about the class public class MyProgram { Java Review class header class body Comments can be placed almost anywhere This class is written in a file named: MyProgram.java

More information

More on control structures

More on control structures Lecture slides for: Chapter 5 More on control structures 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 information

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Exercise Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Zheng-Liang Lu Java Programming 197 / 227 1... 2 int[] hist = new int[5]; 3 //

More information

Basic 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 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 information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements WIT COMP1000 Simple Control Flow: if-else statements Control Flow Control flow is the order in which program statements are executed So far, all of our programs have been executed straight-through from

More information

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

L o o p s. for(initializing expression; control expression; step expression) { one or more statements } L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

More information

DM503 Programming B. Peter Schneider-Kamp.

DM503 Programming B. Peter Schneider-Kamp. DM503 Programming B Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm503/! VARIABLES, EXPRESSIONS & STATEMENTS 2 Values and Types Values = basic data objects 42 23.0 "Hello!" Types

More information

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times Iteration: Intro Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times 2. Posttest Condition follows body Iterates 1+ times 1 Iteration: While Loops Pretest loop Most general loop construct

More information

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6 Repetition Statements Animated Version required for reproduction or display. Chapter 6-1 Objectives After you have read and studied this chapter, you should be able to Implement repetition control

More information

Chapter 4 Introduction to Control Statements

Chapter 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 information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

Expression 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. 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 information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

More information

3chapter C ONTROL S TATEMENTS. Objectives

3chapter C ONTROL S TATEMENTS. Objectives 3chapter C ONTROL S TATEMENTS Objectives To understand the flow of control in selection and loop statements ( 3.2 3.7). To use Boolean expressions to control selection statements and loop statements (

More information

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a

More information

CS111: PROGRAMMING LANGUAGE II

CS111: 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 information

Module 7: Arrays (Single Dimensional)

Module 7: Arrays (Single Dimensional) Module 7: Arrays (Single Dimensional) Objectives To describe why arrays are necessary in programming ( 7.1). To declare array reference variables and create arrays ( 7.2.1 7.2.2). To obtain array size

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

More information

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz) SOFTWARE DEVELOPMENT 1 Control Structures 2018W (Institute of Pervasive Computing, JKU Linz) WHAT IS CONTROL FLOW? The control flow determines the order in which instructions are executed. Default: from

More information

Programming Basics. Digital Urban Visualization. People as Flows. ia

Programming Basics.  Digital Urban Visualization. People as Flows. ia Programming Basics Digital Urban Visualization. People as Flows. 28.09.2015 ia zuend@arch.ethz.ch treyer@arch.ethz.ch Programming? Programming is the interaction between the programmer and the computer.

More information

In this chapter, you will:

In this chapter, you will: Java Programming: Guided Learning with Early Objects Chapter 4 Control Structures I: Selection In this chapter, you will: Make decisions with the if and if else structures Use compound statements in an

More information