Control Flow Practice Problems Mr. Fahrenbacher AP Computer Science A

Size: px
Start display at page:

Download "Control Flow Practice Problems Mr. Fahrenbacher AP Computer Science A"

Transcription

1 Control Flow Practice Problems Mr. Fahrenbacher AP Computer Science A This problem set has four sections. After each section is the answer key. This problem set is NOT exhaustive, but it is too long. Find interesting questions that you want to practice and work on those. Questions Section I if/else 1. Translate each of the following English statements into logical tests that could be used in an if/else statement. Write the appropriate if statement with your logical test. Assume that three int variables, x, y,and z,have been declared. a. z is odd. b. z is not greater than y s square root. c. y is positive. d. Either x or y is even, and the other is odd. e. y is a multiple of z. f. z is not zero. g. y is greater in magnitude than z. h. x and z are of opposite signs. i. y is a nonnegative one-digit number. j. z is nonnegative. k. x is even. l. x is closer in value to y than z is. 2. Given the variable declarations int x = 4; int y = 3; int z = 4; what are the results of the following relational expressions? a. x == 4 b. x == y c. x == z d. y == z e. x + y > 0 f. x z!= 0 g. y * y <= z h. y / y == 1 i. x * (y + 2) > y - (y + z) * 2 3. Consider the following method:

2 3. Consider the following method: public static void ifelsemystery1(int x, int y) { int z = 4; if (z <= x) { z = x + 1; else { z = z + 9; if (z <= y) { y++; System.out.println(z + " " + y); What output is produced for each of the following calls? a. ifelsemystery1(3, 20); b. ifelsemystery1(4, 5); c. ifelsemystery1(5, 5); d. ifelsemystery1(6, 10); 4. Consider the following method: public static void ifelsemystery2(int a, int b) { if (a * 2 < b) { a = a * 3; else if (a > b) { b = b + 3; if (b < a) { b++; else { a ; System.out.println(a + " " + b); 5. What output is produced for each of the following calls? a. ifelsemystery2(10, 2); b. ifelsemystery2(3, 8); c. ifelsemystery2(4, 4); d. ifelsemystery2(10, 30);

3 5. Write Java code to read an integer from the user, then print even if that number is an even number or odd otherwise. You may assume that the user types a valid integer. 6. The following code contains a logic error: 7. Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextint(); if (number % 2 == 0) { if (number % 3 == 0) { System.out.println("Divisible by 6."); else { System.out.println("Odd."); Examine the code and describe a case in which the code would print something that is untrue about the number that was entered. Explain why. Then correct the logic error in the code. 8. The following code is poorly structured: int sum = 1000; Scanner console = new Scanner(System.in); System.out.print("Is your money multiplied 1 or 2 times? "); 9. int times = console.nextint(); if (times == 1) { System.out.print("And how much are you contributing? "); int donation = console.nextint(); sum = sum + donation; count1++; total = total + donation; if (times == 2) { System.out.print("And how much are you contributing? "); int donation = console.nextint(); sum = sum + 2 * donation; count2++; total = total + donation; Rewrite it so that it has a better structure and avoids redundancy. To simplify things, you may assume that the user always types 1 or 2. (How would the code need to be modified to handle any number that the user might type?)

4 9. The following code is poorly structured: 10. Scanner console = new Scanner(System.in); System.out.print("How much will John be spending? "); double amount = console.nextdouble(); System.out.println(); int numbills1 = (int) (amount / 20.0); if (numbills1 * 20.0 < amount) { numbills1++; System.out.print("How much will Jane be spending? "); amount = console.nextdouble(); System.out.println(); int numbills2 = (int) (amount / 20.0); if (numbills2 * 20.0 < amount) { numbills2++; System.out.println("John needs " + numbills1 + " bills"); System.out.println("Jane needs " + numbills2 + " bills"); Rewrite it so that it has a better structure and avoids redundancy. You may wish to introduce a method to help capture redundant code. 12. What is wrong with the following code, which attempts to add all numbers from 1 to a given maximum? Describe how to fix the code. public static int sumto(int n) { for (int i = 1; i <= n; i++) { int sum = 0; sum += i; return sum; 13. What is wrong with the following code, which attempts to return the number of factors of a given integer n? Describe how to fix the code. public static int countfactors(int n) { for (int i = 1; i <= n; i++) { if (n % i == 0) { // factor return i;

5 14. Write code to produce a cumulative product by multiplying together many numbers that are read from the console. 15. The following expression should equal 6.8,but in Java it does not. Why not? The following code was intended to print a message, but it actually produces no output. Describe how to fix the code to print the expected message. double gpa = 3.2; if (gpa * 3 == 9.6) { System.out.println("You earned enough credits."); 22. Consider a method printtriangletype that accepts three integer arguments representing the lengths of the sides of a triangle and prints the type of triangle that these sides form. The three types are equilateral, isosceles, and scalene. An equilateral triangle has three sides of the same length, an isosceles triangle has two sides that are the same length, and a scalene triangle has three sides of different lengths. However, certain integer values (or combinations of values) would be illegal and could not represent the sides of an actual triangle. What are these values? How would you describe the precondition(s) of the printtriangletype method? 23. Consider a method getgrade that accepts an integer representing a student s grade percentage in a course and returns that student s numerical course grade. The grade can be between 0.0 (failing) and 4.0 (perfect). What are the preconditions of such a method? 24. The following method attempts to return the median (middle) of three integer values, but it contains logic errors. In what cases does the method return an incorrect result? How can the code be fixed? public static int medianof3(int n1, int n2, int n3) { if (n1 < n2) { if (n2 < n3) { else { else { return n2; return n3; if (n1 < n3) { else { return n1; return n3; 2

6 26. Consider the following Java method, which is written incorrectly: // This method should return how many of its three // arguments are odd numbers. public static void printnumodd(int n1, int n2, int n3) { int count = 0; if (n1 % 2!= 0) { count++; else if (n2 % 2!= 0) { count++; else if (n3 % 2!= 0) { count++; System.out.println(count + " of the 3 numbers are odd."); Under what cases will the method print the correct answer, and when will it print an incorrect answer? What should be changed to fix the code? Can you think of a way to write the code correctly without any if/else statements? Answers Section I 1. (a) z % 2!= 0 (b) z <= Math.sqrt(y) (c) y > 0 (d) x % 2!= y % 2 (e) y % z == 0 (f) z!= 0 (g) Math.abs(y) > Math.abs(z) (h) (x >= 0) == (z < 0) (i) y % 10 == y (j) z >= 0 (k) x % 2 == 0 (l) Math.abs(x y) < Math.abs(z y)

7 2. (a) true (b) false (c) true (d) false (e) true (f) false (g) false (h) true (i) true 3. (a) (b) 5 6 (c) 6 5 (d) (a) 10 6 (b) 9 9 (c) 3 4 (d) Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextint(); if (number % 2 == 0) { System.out.println("even"); else { System.out.println("odd"); 6. The code incorrectly prints that even numbers not divisible by 3 are odd, because the else statement matches the most closely nested if statement (number % 3 == 0), not the outer if statement. The following change corrects the problem. Note the braces around the outer if statement: if (number % 2 == 0) { if (number % 3 == 0) { System.out.println("Divisible by 6."); else { System.out.println("Odd.");

8 8. int sum = 1000; Scanner console = new Scanner(System.in); System.out.print( "Is your money multiplied 1 or 2 times? "); int times = console.nextint(); System.out.print("And how much are you contributing? "); int donation = console.nextint(); sum += times * donation; total += donation; if (times == 1) { count1++; else if (times == 2) { count2++; If the user could type any number, the code might need additional if statements to increment the proper count variable. If the user could type anything, even a noninteger, the code might need to use the hasnextint method of the Scanner (seen in Chapter 5) to ensure that it has received valid input before it proceeds. 9. // Prompts for two people's money and reports // how many $20 bills the person would need. import java.util.*; public class Bills { public static void main(string[] args) { Scanner console = new Scanner(System.in); int numbills1 = getbills(console, "John"); int numbills2 = getbills(console, "Jane"); System.out.println("John needs " + numbills1 + " bills"); System.out.println("Jane needs " + numbills2 + " bills"); public static int getbills(scanner console, String name) { System.out.print("How much will " + name + " be spending? "); double amount = console.nextdouble(); System.out.println(); int numbills = (int) (amount/20.0); if (numbills * 20.0 < amount) { numbills++; return numbills;

9 12. The sum variable needs to be declared outside the for loop. The following code fixes the problem: public static int sumto(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; return sum; 13. The method will not compile. It should count the factors using a cumulative sum; it should not return inside the loop when it finds each factor. Instead, it should declare a counter outside the loop that is incremented as each factor is seen. The following code fixes the problem: public static int countfactors(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { count++; return count; 14. Scanner console = new Scanner(System.in); System.out.print("How many numbers? "); int count = console.nextint(); int product = 1; for (int i = 1; i <= count; i++) { System.out.print("Next number --> "); int num = console.nextint(); product *= num; System.out.println("Product = " + product); 15. The expression equals because the limited precision of the double type led to a roundoff error. 16. The expression gpa * 3 equals because of a roundoff error. To fix this, test that the value is close to 9.6 rather than exactly equal to it: double gpa = 3.2; if (Math.abs(gpa * 3 9.6) < 0.1) { System.out.println("You earned enough credits.");

10 22. public static void printtriangletype(int s1, int s2, int s3) { if (s1 == s2 && s2 == s3) { System.out.println("equilateral"); else if (s1 == s2 s1 == s3 s2 == s3) { System.out.println("isosceles"); else { System.out.println("scalene"); Invalid values include negative numbers for a side s length and a number for any one side length that is greater than the sum of the other two side lengths, because this cannot be a valid triangle. The precondition of the printtriangletype method is that the side lengths must constitute a valid triangle. 23. The preconditions of this method are that the grade parameter s value is between 0 and The code fails when n3 is the smallest of the three numbers; for example, when the parameters values are (4, 7, 2), the code should return 4 but instead returns 2. The method could be correctly written as follows: public static int medianof3(int n1, int n2, int n3) { if (n1 < n2 && n1 < n3) { if (n2 < n3) { return n2; else { return n3; else if (n2 < n1 && n2 < n3) { if (n1 < n3) { return n1; else { return n3; else { // (n3 < n1 && n3 < n2) if (n1 < n2) { return n1; else { return n2; Alternatively, here is a shorter version: public static int medianof3(int n1, int n2, int n3) { return Math.max(Math.max(Math.min(n1, n2), Math.min(n2, n3)), Math.min(n1, n3));

11 26. The code fails when more than one number is odd, because it uses else if rather than if. The tests should not be nested because they are not mutually exclusive; more than one number could be odd. The following code fixes the problem: public static void printnumodd(int n1, int n2, int n3) { int count = 0; if (n1 % 2!= 0) { count++; if (n2 % 2!= 0) { count++; if (n3 % 2!= 0) { count++; System.out.println(count + " of the 3 numbers are odd."); The following version without if statements also works: public static void printnumodd(int n1, int n2, int n3) { int count = n1 % 2 + n2 % 2 + n3 % 2; System.out.println(count + " of the 3 numbers are odd."); Questions Section II 14. Assume that you have a variable called count that will take on the values 1, 2, 3, 4, and so on. You are going to formulate expressions in terms of count that will yield different sequences. For example, to get the sequence 2, 4, 6, 8, 10, 12,..., you would use the expression (2 * count). Fill in the following table, indicating an expression that will generate each sequence. Sequence Expression a. 2, 4, 6, 8, 10, 12,... b. 4, 19, 34, 49, 64, 79,... c. 30, 20, 10, 0, 10, 20,... d. 7, 3, 1, 5, 9, 13,... e. 97, 94, 91, 88, 85, 82,....

12 15. Complete the code for the following for loop: for (int i = 1; i <= 6; i++) { // your code here so that it prints the following numbers, one per line: What is the output of the following oddstuff method? public static void oddstuff() { int number = 4; for (int count = 1; count <= number; count++) { System.out.println(number); number = number / 2; 17. What is the output of the following loop? int total = 25; for (int number = 1; number <= (total / 2); number++) { total = total number; System.out.println(total + " " + number); 18. What is the output of the following loop? System.out.println("+---+"); for (int i = 1; i <= 3; i++) { System.out.println("\\ /"); System.out.println("/ \\"); System.out.println("+---+"); 20. What is the output of the following loop? System.out.print("T-minus "); for (int i = 5; i >= 1; i ) { System.out.print(i + ", "); System.out.println("Blastoff!"); Answers Section II

13 14. (a) 2 * count (b) 15 * count 11 (c) 10 * count + 40 (d) 4 * count 11 (e) 3 * count for (int i = 1; i <= 6; i++) { // your code here System.out.println(18 * i 22); \ / / \ \ / / \ \ / / \ T-minus 5, 4, 3, 2, 1, Blastoff! Questions Section III 1. What output is produced by the following program? 1 public class Odds { 2 public static void main(string[] args) { 3 printodds(3); 4 printodds(17 / 2); 5 6 int x = 25; 7 printodds(37 x + 1); public static void printodds(int n) { 11 for (int i = 1; i <= n; i++) { 12 int odd = 2 * i 1; 13 System.out.print(odd + " "); System.out.println(); 16 17

14 2. What is the output of the following program? 1 public class Weird { 2 public static void main(string[] args) { 3 int number = 8; 4 halfthefun(11); 5 halfthefun( * 8); 6 halfthefun(number); 7 System.out.println("number = " + number); public static void halfthefun(int number) { 11 number = number / 2; 12 for (int count = 1; count <= number; count++) { 13 System.out.print(count + " "); System.out.println(); What is the output of the following program? 1 public class MysteryNumbers { 2 public static void main(string[] args) { 3 String one = "two"; 4 String two = "three"; 5 String three = "1"; 6 int number = 20; 7 8 sentence(one, two, 3); 9 sentence(two, three, 14); 10 sentence(three, three, number + 1); 11 sentence(three, two, 1); 12 sentence("eight", three, number / 2); public static void sentence(string three, String one, int number) { 16 System.out.println(one + " times " + three + " = " + (number * 2)); 17 18

15 4. What output is produced by the following program? 1 public class MysteryWho { 2 public static void main(string[] args) { 3 String whom = "her"; 4 String who = "him"; 5 String it = "who"; 6 String he = "it"; 7 String she = "whom"; 8 9 sentence(he, she, it); 10 sentence(she, he, who); 11 sentence(who, she, who); 12 sentence(it, "stu", "boo"); 13 sentence(it, whom, who); public static void sentence(string she, String who, String whom) { 17 System.out.println(who + " and " + whom + " like " + she); What output is produced by the following program? 1 public class MysteryTouch { 2 public static void main(string[] args) { 3 String head = "shoulders"; 4 String knees = "toes"; 5 String elbow = "head"; 6 String eye = "eyes and ears"; 7 String ear = "eye"; 8 9 touch(ear, elbow); 10 touch(elbow, ear); 11 touch(head, "elbow"); 12 touch(eye, eye); 13 touch(knees, "Toes"); 14 touch(head, "knees " + knees); public static void touch(string elbow, String ear) { 18 System.out.println("touch your " + elbow + " to your " + ear); 19 20

16 6. What output is produced by the following program? 1 public class MysterySoda { 2 public static void main(string[] args) { 3 String soda = "coke"; 4 String pop = "pepsi"; 5 String coke = "pop"; 6 String pepsi = "soda"; 7 String say = pop; 8 9 carbonated(coke, soda, pop); 10 carbonated(pop, pepsi, pepsi); 11 carbonated("pop", pop, "koolaid"); 12 carbonated(say, "say", pop); public static void carbonated(string coke, String soda, String pop) { 15 System.out.println("say " + soda + " not " + pop + " or " + coke); Write a method called printstrings that accepts a String and a number of repetitions as parameters and prints that String the given number of times with a space after each time. For example, the call printstrings("abc", 5); will print the following output: abc abc abc abc abc 9. What is wrong with the following program? 1 public class Temperature { 2 public static void main(string[] args) { 3 double tempf = 98.6; 4 double tempc = 0.0; 5 ftoc(tempf, tempc); 6 System.out.println("Body temp in C is: " + tempc); // converts Fahrenheit temperatures to Celsius 10 public static void ftoc(double tempf, double tempc) { 11 tempc = (tempf 32) * 5 / 9; 12 13

17 11. What output is produced by the following program? 1 public class MysteryReturn { 2 public static void main(string[] args) { 3 int x = 1, y = 2, z = 3; 4 z = mystery(x, z, y); 5 System.out.println(x + " " + y + " " + z); 6 x = mystery(z, z, x); 7 System.out.println(x + " " + y + " " + z); 8 y = mystery(y, y, z); 9 System.out.println(x + " " + y + " " + z); public static int mystery(int z, int x, int y) { 13 z ; 14 x = 2 * y + z; 15 y = x 1; 16 System.out.println(y + " " + z); 17 return x; Write a method called that takes three integers as parameters and returns 12. Write a method called min that takes three integers as parameters and returns the smallest of the three values; for example, a call of min(3, 2, 7) would return 2, and a call of min(19, 27, 6) would return 6. Use Math.min to write your solution. 13. Write a method called countquarters that takes an int representing a number of cents as a parameter and returns the number of quarter coins represented by that many cents. Don t count any whole dollars, because those would be dispensed as dollar bills. For example, countquarters(64) would return 2, because 64 cents is equivalent to 2 quarters with 14 cents left over. A call of countquarters(1278) would return 3, because after the 12 dollars are taken out, 3 quarters remain in the 78 cents that are left. Answer Section III number = 8

18 3. three times two = 6 1 times three = 28 1 times 1 = 42 three times 1 = 2 1 times eight = whom and who like it it and him like whom whom and him like him stu and boo like who her and him like who 5. touch your eye to your head touch your head to your eye touch your shoulders to your elbow touch your eyes and ears to your eyes and ears touch your toes to your Toes touch your shoulders to your knees toes 6. say coke not pepsi or pop say soda not soda or pepsi say pepsi not koolaid or pop say say not pepsi or pepsi 7. public static void printstrings(string s, int n) { for (int i = 1; i <= n; i++) { System.out.print(s + " "); System.out.println(); 8. is an overloaded method. 9. The program changes the value of its tempc parameter, but this doesn t affect the variable tempc in main. The (incorrect) output is: Body temp in C is: public static int min(int n1, int n2, int n3) { return Math.min(n1, Math.min(n2, n3)); 13. public static int countquarters(int cents) { return cents % 100 / 25;

19 Questions Section IV 1. For each of the following while loops, state how many times the loop will execute its body. Remember that zero, infinity, and unknown are legal answers. Also, what is the output of the code in each case? a. int x = 1; while (x < 100) { System.out.print(x + " "); x += 10; b. int max = 10; while (max < 10) { System.out.println("count down: " + max); max ; c. int x = 250; while (x % 3!= 0) { System.out.println(x); d. int x = 2; while (x < 200) { System.out.print(x + " "); x *= x; e. String word = "a"; while (word.length() < 10) { word = "b" + word + "b"; System.out.println(word); f. int x = 100; while (x > 0) { System.out.println(x / 10); x = x / 2; 2. Convert each of the following for loops into an equivalent while loop: a. for (int n = 1; n <= max; n++) { System.out.println(n); b. int total = 25; for (int number = 1; number <= (total / 2); number++) { total = total number; System.out.println(total + " " + number); d. c. int number = 4; for (int count = 1; count <= number; count++) { System.out.println(number); number = number / 2; 3. Consider the following method:

20 3. Consider the following method: public static void mystery(int x) { int y = 1; int z = 0; while (2 * y <= x) { y = y * 2; z++; System.out.println(y + " " + z); For each of the following calls, indicate the output that the preceding method produces: mystery(1); mystery(6); mystery(19); mystery(39); mystery(74); 4. Consider the following method: public static void mystery(int x) { int y = 0; while (x % 2 == 0) { y++; x = x / 2; System.out.println(x + " " + y); For each of the following calls, indicate the output that the preceding method produces: mystery(19); mystery(42); mystery(48); mystery(40); mystery(64); 10. Write a method called zerodigits that accepts an integer parameter and returns the number of digits in the number that have the value 0. For example, the call zerodigits( ) should return 2, and zerodigits(743) should return 0. The call zerodigits(0) should return 1. (We suggest you use a do/while loop in your solution.) Write a sentinel loop that repeatedly prompts the user to enter a number and, once the number 1 is typed, displays the maximum and minimum numbers that the user entered. Here is a sample dialogue: Type a number (or 1 to stop): 5 Type a number (or 1 to stop): 2 Type a number (or 1 to stop): 17 Type a number (or 1 to stop): 8 Type a number (or 1 to stop): 1 Maximum was 17 Minimum was 2 If 1 is the first number typed, no maximum or minimum should be printed. In this case, the dialogue would look like this: Type a number (or 1 to stop): 1

21 14. Consider the following variable declarations: int x = 27; int y = 1; int z = 32; boolean b = false; What is the value of each of the following Boolean expressions? a.!b b. b true c. (x > y) && (y > z) d. (x == y) (x <= z) e.!(x % 2 == 0) f. (x % 2!= 0) && b g. b &&!b h. b!b i. (x < y) == b j.!(x / 2 == 13) b (z * 3 == 96) k. (z < x) == false l.!((x > 0) && (y < 0)) 16. The following code attempts to examine a number and return whether that number is prime (i.e., has no factors other than 1 and itself). A flag named prime is used. However, the Boolean logic is not implemented correctly, so the method does not always return the correct answer. In what cases does the method report an incorrect answer? How can the code be changed so that it will always return a correct result? public static boolean isprime(int n) { boolean prime = true; for (int i = 2; i < n; i++) { if (n % i = = 0) { prime = false; else { prime = true; return prime; 19. Using Boolean Zen, write an improved version of the following method, which returns whether the given number of cents would require any pennies (as opposed to being an amount that could be made exactly using coins other than pennies): public static boolean haspennies(int cents) { boolean nickelsonly = (cents % 5 == 0); if (nickelsonly == true) { return false; else { return true;

22 20. Consider the following method: public static int mystery(int x, int y) { while (x!= 0 && y!= 0) { if (x < y) { y = x; else { x = y; return x + y; For each of the following calls, indicate the value that is returned: mystery(3, 3) mystery(5, 3) mystery(2, 6) mystery(12, 18) mystery(30, 75) 21. The following code is a slightly modified version of actual code that was in the Microsoft Zune music player in The code attempts to calculate today s date by determining how many years and days have passed since Assume the existence of methods for getting the total number of days since 1980 and for determining whether a given year is a leap year: int days = gettotaldayssince1980(); year = 1980; while (days > 365) { // subtract out years if (isleapyear(year)) { if (days > 366) { else { days = 366; year += 1; days = 365; year += 1; Thousands of Zune players locked up on January 1, 2009, the first day after the end of a leap year since the Zune was released. (Microsoft quickly released a patch to fix the problem.) What is the problem with the preceding code, and in what cases will it exhibit incorrect behavior? How can it be fixed? 22. Consider the following variable declarations: int x = 27; int y = 1; int z = 32; boolean b = false; Write a new Boolean expression that is the negation of each of the following Boolean expressions. Use De Morgan s laws rather than simply writing a! at the beginning of each entire expression. a. b b. (x > y) && (y > z) c. (x == y) (x <= z)

23 d. (x % 2!= 0) && b e. (x / 2 == 13) b (z * 3 == 96) f. (z < x) && (z > y x >= y) Section 5.4: User Errors Answers Section IV 1. (a) Executes body 10 times. Output is (b) Executes body 0 times. No output. (c) Loops infinitely. Output is (d) Executes body 3 times. Output is (e) Executes body 5 times. Output is bbbbbabbbbb (f) Executes body 7 times. Output is (a) int n = 1; while (n <= max) { System.out.println(n); n++; (b) int total = 25; int number = 1; while (number <= (total / 2)) { total = total number; System.out.println(total + " " + number); number++; (c) int i = 1;

24 (d) int number = 4; int count = 1; while (count <= number) { System.out.println(number); number = number / 2; count++; Method call Output mystery(1); 1 0 mystery(6); 4 2 mystery(19); 16 4 mystery(39); 32 5 mystery(74); Method call Output mystery(19); 19 0 mystery(42); 21 1 mystery(48); 3 4 mystery(40); 5 3 mystery(64); ! public static int zerodigits(int number) { if(number == 0) { return 1; int count = 0; while(number > 0) { if(number % 10 == 0) { count++; number /= 10; return count;

25 13. int SENTINEL = -1; System.out.print("Type a number (or " + SENTINEL + " to stop): "); Scanner console = new Scanner(System.in); int input = console.nextint(); int min = input; int max = input; while (input!= SENTINEL) { if (input < min) { min = input; else if (input > max) { max = input; System.out.print("Type a number (or " + SENTINEL + " to stop): "); input = console.nextint(); if (min!= SENTINEL) { System.out.println("Maximum was " + max); System.out.println("Minimum was " + min); 14. (a) true (b) true (c) false (d) true (e) true (f) false (g) false (h) true (i) true (j) true (k) true (l) false 16. In this code the boolean flag isn t being used properly, because if the code finds a factor of the number, prime will be set to false, but on the next pass through the loop, if the next number isn t a factor, prime will be reset to true again. The following code fixes the problem: public static boolean isprime(int n) { boolean prime = true; for (int i = 2; i < n; i++) { if (n % i == 0) { prime = false; return prime;

26 19. public static boolean haspennies(int cents) { return cents % 5!= 0; 20. Method call Value returned mystery(3, 3) 3 mystery(5, 3) 1 mystery(2, 6) 2 mystery(12, 18) 6 mystery(30, 75) The code will get stuck in an infinite loop when the current date is the end of a leap year. On December 31 the days value will be 366, so code enters the if (isleapyear) statement but does not enter the if (days > 366) statement. So the loop does not subtract any days and never terminates. The code can be fixed by adding a break statement to the loop (see Appendix D): int days = gettotaldayssince1980(); year = 1980; while (days > 365) { // subtract out years if (isleapyear(year)) { if (days > 366) { days -= 366; year += 1; else { // break; // new code here // else { days -= 365; year += 1; 22. (a)!b (b) (x <= y) (y <= z) (c) (x!= y) && (x > z) (d) (x % 2 == 0)!b (e) (x / 2!= 13) &&!b && (z * 3!= 96) (f) (z >= x) (z <= y && x < y) 23.

Building Java Programs

Building Java Programs Building Java Programs Chapter 4: Conditional Execution 1 loop techniques cumulative sum fencepost loops conditional execution Chapter outline the if statement and the if/else statement relational expressions

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises: #7 videos: Ch. 4 #2-4 The if/else statement Executes one block if a test is true,

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

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises: #7 videos: Ch. 4 #2-4 Loops with if/else if/else statements can be used with

More information

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

! definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. ! We often use language like Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

More information

Midterm Review Session

Midterm Review Session Midterm Review Session Programming Problems For more practice: http://webster.cs.washington.edu:8080/practiceit/ Copyright 2009 by Pearson Education Midterm Logistics Bring your UW Student ID card!! Will

More information

AP Computer Science. if/else, return values. Copyright 2010 by Pearson Education

AP Computer Science. if/else, return values. Copyright 2010 by Pearson Education AP Computer Science if/else, return values The if statement Executes a block of statements only if a test is true statement;... statement; Example: double gpa = console.nextdouble(); if (gpa >= 2.0) {

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming (Spring 2012) Lecture #8: More on Conditional & Loop Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements:

More information

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators Flow of Control of Program Statements CS 112 Introduction to Programming (Spring 2012) q Java provides two types of program flow of control statements: decision statements, or conditional statements: decide

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com

More information

Primitive data, expressions, and variables

Primitive data, expressions, and variables How the computer sees the world Primitive data, expressions, and variables Readings:.. Internally, the computer stores everything in terms of s and 0 s Example: h 0000 "hi" 0000000 0 0000 How can the computer

More information

Topic 12 more if/else, cumulative algorithms, printf

Topic 12 more if/else, cumulative algorithms, printf Topic 12 more if/else, cumulative algorithms, printf "We flew down weekly to meet with IBM, but they thought the way to measure software was the amount of code we wrote, when really the better the software,

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1 self-check: Ch. 4 #2; Ch. 5 # 1-10 exercises: Ch. 4 #2, 4, 5, 8; Ch. 5 # 1-2 Copyright 2009

More information

1. An operation in which an overall value is computed incrementally, often using a loop.

1. An operation in which an overall value is computed incrementally, often using a loop. Practice Exam 2 Part I: Vocabulary (10 points) Write the terms defined by the statements below. 1. An operation in which an overall value is computed incrementally, often using a loop. 2. The < (less than)

More information

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,

More information

Repetition with for loops

Repetition with for loops Repetition with for loops So far, when we wanted to perform a task multiple times, we have written redundant code: System.out.println( Building Java Programs ); // print 5 blank lines System.out.println(

More information

AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else; Cumulative sum; reading: 4.2, 4.4-4.5 2 Advanced if/else reading: 4.4-4.5 Factoring if/else code factoring: Extracting common/redundant code.

More information

Type boolean. Building Java Programs. Recap: Type boolean. "Short-circuit" evaluation. De Morgan's Law. Boolean practice questions.

Type boolean. Building Java Programs. Recap: Type boolean. Short-circuit evaluation. De Morgan's Law. Boolean practice questions. Building Java Programs Chapter 5 Lecture 5-4: More boolean, Assertions, do/while loops Type boolean reading: 5.3 reading: 5.3, 5.4, 5.1 1 Recap: Type boolean boolean: A logical type whose values are true

More information

Topic 12 more if/else, cumulative algorithms, printf

Topic 12 more if/else, cumulative algorithms, printf Topic 12 more if/else, cumulative algorithms, printf "We flew down weekly to meet with IBM, but they thought the way to measure software was the amount of code we wrote, when really the better the software,

More information

NoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file.

NoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file. CSC116 Practice Exam 2 - KEY Part I: Vocabulary (10 points) Write the terms defined by the statements below. Cumulative Algorithm 1. An operation in which an overall value is computed incrementally, often

More information

Chapter 4: Control Structures I

Chapter 4: Control Structures I Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore

More information

Building Java Programs Chapter 2

Building Java Programs Chapter 2 Building Java Programs Chapter 2 Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. Data types type: A category or set of data values. Constrains the operations that can

More information

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks: كلية الحاسبات وتقنية المعلوما Exam 2 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: November 22, 2015 Student Name: Student ID: Total Marks: 40 Obtained Marks: Instructions: Do not open this

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 2: Primitive Data and Definite Loops These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2007. They may not be rehosted, sold, or modified without expressed

More information

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp! Garfield AP CS User Input, If/Else Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp! Warmup Write a method add10 that takes one integer parameter. Your method should return

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Program Analysis Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q PS5 Walkthrough Thursday

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

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1, 4.5 2 Interactive Programs with Scanner reading: 3.3-3.4 Interactive programs We have written programs that print console

More information

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw. Building Java Programs Chapter 2 bug Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. 2 An Insect Software Flaw 3 4 Bug, Kentucky Bug Eyed 5 Cheesy Movie 6 Punch Buggy

More information

Building Java Programs Chapter 2

Building Java Programs Chapter 2 Building Java Programs Chapter 2 Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. bug 2 An Insect 3 Software Flaw 4 Bug, Kentucky 5 Bug Eyed 6 Cheesy Movie 7 Punch Buggy

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

CSE 142, Autumn 2011 Midterm Exam: Friday, November 4, 2011

CSE 142, Autumn 2011 Midterm Exam: Friday, November 4, 2011 CSE 142, Autumn 2011 Midterm Exam: Friday, November 4, 2011 Name: Section: Student ID #: TA: You have 50 minutes to complete this exam. You may receive a deduction if you keep working after the instructor

More information

Returns & if/else. Parameters and Objects

Returns & if/else. Parameters and Objects Returns & if/else Parameters and Objects Subset of the Supplement Lesson slides from: Building Java Programs, Chapter 3 & 4 by Stuart Reges and Marty Stepp (http://www.buildingjavaprograms.com/ ) & thanks

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 Variables reading: 2.2 self-check: 1-15 exercises: 1-4 videos: Ch. 2 #2 2 Receipt example What's bad about the

More information

CS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost.

CS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost. CS 112 Introduction to Programming CS112@Yale Loop Patterns: Fencepost Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu http://www.ultimateecards.com/image/772-jan-29-national-puzzle-day-card

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) 1 Short Answer (10 Points Each) 1. Write a for loop that will calculate a factorial. Assume that the value n has been input by the user and have the loop create n! and store it in the variable fact. Recall

More information

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam Page 0 German University in Cairo April 6, 2017 Media Engineering and Technology Faculty Prof. Dr. Slim Abdennadher CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam Bar Code

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming (Spring 2012) Lecture #7: Variable Scope, Constants, and Loops Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112

More information

Advanced if/else & Cumulative Sum

Advanced if/else & Cumulative Sum Advanced if/else & Cumulative Sum Subset of the Supplement Lesson slides from: Building Java Programs, Chapter 4 by Stuart Reges and Marty Stepp (http://www.buildingjavaprograms.com/ ) Questions to consider

More information

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Building Java Programs. Chapter 2: Primitive Data and Definite Loops Building Java Programs Chapter 2: Primitive Data and Definite Loops Copyright 2008 2006 by Pearson Education 1 Lecture outline data concepts Primitive types: int, double, char (for now) Expressions: operators,

More information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Arrays Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Can we solve this problem? Consider the following program

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

CSE 142, Autumn 2010 Midterm Exam, Friday, November 5, 2010

CSE 142, Autumn 2010 Midterm Exam, Friday, November 5, 2010 CSE 142, Autumn 2010 Midterm Exam, Friday, November 5, 2010 Name: Section: TA: Student ID #: You have 50 minutes to complete this exam. You may receive a deduction if you keep working after the instructor

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 Randomness Lack of predictability: don't know what's coming next Random process: outcomes do not

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

assertion: A statement that is either true or false.

assertion: A statement that is either true or false. Logical assertions assertion: A statement that is either true or false. Examples: Java was created in 1995. The sky is purple. 23 is a prime number. 10 is greater than 20. x divided by 2 equals 7. (depends

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Chapter 2. Elementary Programming

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

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

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

1.3 Conditionals and Loops

1.3 Conditionals and Loops 1 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops to infinity and beyond Math primitive data types

More information

Final. Your Name CS Fall 2014 December 13, points total Your Instructor and Section

Final. Your Name CS Fall 2014 December 13, points total Your Instructor and Section Final Your Name CS 1063 - Fall 2014 December 13, 2014 100 points total Your Instructor and Section I. (10 points, 1 point each) Match each of the terms on the left by choosing the upper case letter of

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Lecture 6: While Loops and the Math Class

Lecture 6: While Loops and the Math Class Lecture 6: While Loops and the Math Class Building Java Programs: A Back to Basic Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. while loops 2 Categories of loops

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

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Iteration statements - Loops

Iteration statements - Loops Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or

More information

Topic 5 for loops and nested loops

Topic 5 for loops and nested loops Topic 5 for loops and nested loops Always to see the general in the particular is the very foundation of genius. -Arthur Schopenhauer Based on slides by Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/

More information

Repetition. Chapter 6

Repetition. Chapter 6 Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 7 Arrays reading: 7.1 2 Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp:

More information

Repetition. Chapter 6

Repetition. Chapter 6 Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

More information

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam Seat Number Name CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam This is a closed book exam. Answer all of the questions on the question paper in the space provided. If

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 1 2 Repetition with for loops So far, repeating a statement is redundant: System.out.println("Homer says:"); System.out.println("I

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 1 Repetition with for loops So far, repeating a statement is redundant: System.out.println("Homer says:"); System.out.println("I

More information

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin

More information

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website: Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

More information

CSE 142, Summer 2013 Midterm Exam, Friday, July 26, 2013

CSE 142, Summer 2013 Midterm Exam, Friday, July 26, 2013 CSE 142, Summer 2013 Midterm Exam, Friday, July 26, 2013 Name: Section: TA: Student ID #: You have 60 minutes to complete this exam. You may receive a deduction if you keep working after the instructor

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

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

Building Java Programs Chapter 4

Building Java Programs Chapter 4 Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson 2013. All rights reserved. The if statement Executes a block of statements only if a test is true if (test) { statement;...

More information

CIS March 1, 2018

CIS March 1, 2018 CIS 1068 March 1, 2018 Administrative Stuff Assignment 6 Today s office hours rescheduled: 12:30-1:50 or appointment, or drop by Last Time more on JUnit and what should be done in Assignment 6 Random sentinel

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: Assertions reading: 5.5 1 Punchline to a longer comic: http://www.smbc-comics.com/index.php?db=comics&id=2362#comic 2 Logical assertions assertion: A statement

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 5.2 1 2 A deceptive problem... Write a method printletters that prints each letter from a word

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Full file at

Full file at Chapter 1 1. a. False; b. False; c. True; d. False; e. False; f; True; g. True; h. False; i. False; j. True; k. False; l. True. 2. Keyboard and mouse. 3. Monitor and printer. 4. Because programs and data

More information

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python + Condition Controlled Loops Introduction to Programming - Python + Repetition Structures n Programmers commonly find that they need to write code that performs the same task over and over again + Example:

More information

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: 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 information

Chapter 7. Iteration. 7.1 Multiple assignment

Chapter 7. Iteration. 7.1 Multiple assignment Chapter 7 Iteration 7.1 Multiple assignment You can make more than one assignment to the same variable; effect is to replace the old value with the new. int bob = 5; System.out.print(bob); bob = 7; System.out.println(bob);

More information

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements

More information

Question: Total Points: Score:

Question: Total Points: Score: CS 170 Exam 1 Section 001 Fall 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

More information

CSE142 Sample Midterm Spring Name UW NetId (e.g. whitab) Section (e.g., AA) TA

CSE142 Sample Midterm Spring Name UW NetId (e.g. whitab) Section (e.g., AA) TA CSE142 Sample Midterm Spring 2018 Name UW NetId (e.g. whitab) Section (e.g., AA) TA This exam is divided into nine questions with the following points: # Problem Area Points Score ---------------------------------------------

More information

CSS 161 Fundamentals of Compu3ng. Flow control (2) October 10, Instructor: Uma Murthy

CSS 161 Fundamentals of Compu3ng. Flow control (2) October 10, Instructor: Uma Murthy CSS 161 Fundamentals of Compu3ng Flow control (2) October 10, 2012 Instructor: Uma Murthy Outline Reminders: HW 2 due Monday Today: Errata Review condi3onals Boolean expressions (3.2) Loops (3.3) CSS 161:

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

Topic 14 while loops and loop patterns

Topic 14 while loops and loop patterns Topic 14 while loops and loop patterns "Given enough eyeballs, all bugs are shallow (e.g., given a large enough beta-tester and co-developer base, almost every problem will be characterized quickly and

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: Control structures. Repetition

Chapter 4: Control structures. Repetition Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

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

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Computer Programming, I. Laboratory Manual. Experiment #6. Loops 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 #6

More information