APCS: Unit 2

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What are the logical operators in Java?

&&, ||, !

True or false? (a) break can be used in while and for loops but not in do-while loops (except in switch statements). (b) If break is used inside a body of a loop (not in a switch), it must be inside an if-else statement. (c) In nested loops, break in any of them passes control to the first statement after the outermost loop.

(a) F (b) T (c) F

The following method calculates 1^2 + 2^2 + .... n^2 : public int addSquares(int n) { int sum = 0; < missing code > return sum; } True or false? The following can replace < missing code >: (a) for (int k = 1; k <= n; k++) sum += k * k; (b) int x = 1; for (int k = 1; k <= n; k++) { sum += x; x += 2 * k; } (c) if (n > 0) sum = addSquares(n - 1) + n * n;2

(a) T (b) F (c) T

True or false? (a) Any for loop can be replaced by an equivalent while loop. (b) A program with a bug can go into an infinite loop and stay there until the user manually aborts it using operating system's commands. (c) A while loop must always have at least one if statement in it.

(a) T (b) T (c) F

True or false? (a != 0) && (((b * b) - (4 * a * c)) >= 0) is equivalent to: (a) a != 0 && b * b - 4 * a * c >= 0 (b) (a != 0) && (b * b - 4 * a * c) >= 0 (c) (a != 0) && (b * b - 4 * a * c >= 0)

(a) T (b) T (c) T

True or false? The following version of printNums's code compiles with no errors and prints 1 3 7 15 31 when called with n = 5: (a) public void printNums(int n) { int p = 1; for (int k = 1; k <= 5; k++) { System.out.print(p + " "); p = 2*p + 1; } } (b) public void printNums(int n) { for (int k = 1; k <= 31; k = 2*k + 1) System.out.print(k + " "); } (c) public void printNums(int n) { if (n > 1) printNums(n - 1); int p = 1; while (n > 1) { p = 2*p + 1; n--; } System.out.print(p + " "); }

(a) T (b) T (c) T

True or false? (a) The result of a relational operator has the boolean type. (b)Logical operators apply only to Boolean variables or expressions. (c) true and false are Java reserved words. (d) a || b is true if and only if either a is true or b is true, but not both. (e) In the if statement, the condition can be any arithmetic expression with an integer value.

(a) T (b) T (c) T (d) F (e) F

What's the output of the following: for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { System.out.print("*"); } System.out.println(); // to end the line }

********** ********** ********** ********** **********

What's a while loop?

- A while statement executes a block of code repeatedly - A condition controls how often the loop is executed - while (condition) - statement - Most commonly, the statement is a block statement (set of statements delimited by { })

What is the order of operations in Java?

- Unary operations (including !) have higher precedence than binary operations. - Binary arithmetic operators (+,*,...) have higher rank than all relational operators (>,<,..) -In the absences of parenthesis, binary operators of the same rank are performed from left to right -Unary operators from right to left -Arithmetic and relational operators have higher rank than the binary logical operators (&&, ||) -When && and || are combined in one logicial expression, && has higher rank than || -Parenthesis good idea in this case for clarity, but not necessary Another way to put it: ! -(unary) ++ -- (cast) * / % + - < <= > >= == != && ||

Are braces always required?

-Braces are optional when the body of the loop(s) is one statement -However, many programmers prefer to always use braces in loops, especially in nested loops.

Disruptions that alters the flow of code:

-Method Calls (we will discuss later) -Iterative Statements (loops) (we will discuss later) -Conditional Statements (If & If-else) -Switch Statements (we will discuss later) -Exceptions (we will discuss later)

What is a for loop, and when should you use it?

-Use a for loop when a variable runs from a starting value to an ending value with a constant increment or decrement -For is a shorthand that combines in one statement initialization, condition, and change ex: for ( initialization; condition; change ) { statement1; statement2; ... statementN; }

When is a switch statement used?

-Used when a program must take one of several actions depending on the value of some variable expression. -If you are handling 2 or 3 situtations....if-else-if is fine. -More than that, switch statements are more efficient to replace long if-else statements

What are the 8 primitive data types in Java?

-int -double -char -boolean -byte -short -long -float

What's the output? for (int line = 1; line <= 5; line++) { for (int j = 1; j <= (-1*line+5); j++) { System.out.print("."); } System.out.println(line); }

....1 ...2 ..3 .4 5

While loop: 1) Initialization: 2) Testing: 3) Change:

1) The variables tested in the condition must be initialized to some values. If the condition is false at the outset, the loop is never entered. 2) The condition is tested before each iteration. If false, the program continues with the first statement after the loop. 3) At least one of the variables tested in the condition must change within the body of the loop.

Which is the declaration / initialization / assignment? 1 ) boolean testResult = false; 2) flag = true; 3) boolean flag;

1) initialization 2) assignment 3) declaration

What is the output: 9 + 16 / 3 * 7 % 8 - 5

7

What are the relational operators in Java?

<, >, <=, >=, ==, !=

Consider the following code fragment: int count = 0; double x = <someValue> ; while (count < 100 && (x * x * x - a) > 0.01) { x = (1.0 / 3.0) * (2 * x + a / (x * x)); count++; } Which of the following conditions must be true after this code has been successfully executed? A. count >= 100 B. count >= 100 || (x * x * x - a) <= 0.01 C. count >= 100 && (x * x *x - a) <= 0.01 D. count < 100 && (x * x * x - a) > 0.01

B

Consider the following method: public int divide(int n, int p) { do { n /= p; } while (n % p == 0); return n; } What is returned by divide(44, 5)? A. 44 B. 8 C. 3 D. 0

B

What is the result when the following code segment is compiled and executed? int n = 65; // Line 1 for (int p = 2; p < n; p++) // Line 2 if (n % p == 0) // Line 3 break; // Line 4 System.out.println(n / p); // Line 5 A. Syntax error on line 3 B. Syntax error on line 5 C. Compiles with no errors; displays 5 D. Compiles with no errors; displays 13

B

Which of the following is NOT a logical operator? A. ! B. == C. && D. ||

B

What is the value of d after the following statement is executed? int d; for (d = 1; d < 567; d *= 10); A. 1 B. 10 C. 1000 D. Unpredictable

C

What is the value of x after the following code is executed? int x = 1; switch(x) { case 1: x++; break; case 2: x += 2; break; default: x = 0; break; } A. 0 B. 1 C. 2 D. 4

C

Which of the following expressions is equivalent to !(x >= 2.5 || y < 3) A. x >= 2.5 && y < 3 B. x <= 2.5 || y > 3 C. x < 2.5 && y >= 3 D. x > 2.5 || y >= 3

C

Which of the following is NOT a relational operator? A. >= B. <= C. /= D. !=

C

Which of the following operators does not apply to boolean variables? A. || B. == C. >= D. !=

C

In for (int k = 0; k < limit; k++) { ... } why is it not a good idea to increment or otherwise change k in the body of the loop? A. Because the compiler would generate a "variable k may be not defined" warning B. Because the compiler would generate a "concurrent modification" error C. Because k may exceed limit in the middle of an iteration, and then the program will throw an exception D. Because such code may be hard to follow and may lead to bugs

D

What is displayed after the following code fragment is executed? int n = 4; int fact = 1; for (int k = n; k >= 1; k++) fact *= k; System.out.println(n + "! = " + fact); A. 4! = 0 B. 4! = 1 C. 4! = 24 D. Nothing: the program hangs for quite a while

D

What is the output of the following code segment? int m = 1, n = 1; for (m = 2; m <= 10; m++) for (n = 1; n <= m; n++) if (n * n == m) break; System.out.println(m + " " + n); A. 1 1 B. 4 2 C. 9 3 D. 11 11

D

What is a do loop & provide an example where you force the user to enter a value less than 100:

Executes the body of a loop at least once and performs the loop test after the body is executed. int value; do { System.out.print("Enter an integer < 100: "); value = in.nextInt(); } while (value >= 100);

What's Math.random()? (provide an example of it as well)

In the Math class, there is a method called random(). This method returns a double between 0 and 1.0 (which can include 0 but not include 1.0). If you want to get a random integer between 0 and 19, you would multiply this double by 20 and cast it to an int: int randInt = (int)( Math.random() * 20 ); //a random number between 0 and 19 int randInt = (int)( Math.random() * 20 ) + 1; //a random number between 1 and 20

What is repeating the same code segment several times called?

Iterating

Is the break at the end of the case required in a switch statement?

No...but if omitted it causes the program to "fall through" and continue to the next case.

Is the default clause optional in a switch statement?

Yes

Off-by-one error:

a loop executes one too few, or one too many, times Example: int years = 0; while (balance < 2 * initialBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; } System.out.println ("The investment reached the target after " + years + " years.");

What are the three control statements Java provides for iterations?

for, for each, while, and do-while

Write a do loop that reads integers and computes their sum. Stop when reading the value 0.

int x; int sum = 0; do { x = in.nextInt(); sum = sum + x; } while (x != 0);

Variables can hold _____; then the type is the _____ of the object.

objects; class

A savings account pays 5 percent interest annually. Write a program that calculates the number of years it takes for an initial deposit of $1,000 to reach $3,000. Use one while loop; do not use any library methods.

public class Interest { public static void main (String[] args) { int yr = 1; double amt = 1000; while (amt < 3000) { amt *= 1.05; yr++; } System.out.println (yr); } }

Write a program that prints out the smallest positive integer k such that (int)(k * 0.01 * 100.0) != k

public static void main (String[] args) { int k = 1; while ((int) (k * 0.01 * 100.0) == k) { k++ } System.out.println (k); }

Recall that k k ! 1 ... = ⋅ ⋅ . An integer p ≥ 2 is a prime if and only if ( p −1! 1 ) + is evenly divisible by p. Using this fact, write a program that prints out the first n primes ( n ≤ 5 ). Your program should use one while loop and no other iterative statements or recursion.

public static void main (String[] args) { int n = 5; int p = 2, factorial = 1, count = 0; while (count < n) { if ((factorial + 1) % p == 0) { System.out.println (p + " "); count++; } factorial *= p; p++; } }

Example of the basic structure of a switch statement:

switch ( variable_to_test ) { case value: code_here; break; case value: code_here; break; default: values_not_caught_above; }

What is the output? public class Test { public static void main(String[] args) { for(int x = 10; x < 20; x++) { if(x == 15) { break; } System.out.print("value of x : " + x ); System.out.print("\n"); } } }

value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14

While loop syntax:

while ( condition ) { statement1; statement2; ... statementN; }

Find and fix a bug in the following code: if (isLeapYear(year)) if (month > 2) { System.out.println("Adding extra day"); day++; } else System.out.println("Not a leap year");

{ after first if and } before else


संबंधित स्टडी सेट्स

Experimental Psychology chapter 9-11

View Set

Module 10: How We Got Here: Formation of Our Solar System

View Set

5 - Bull Moose From the Bully Pulpit

View Set

Nutrition test number 4 Chapter 10-12

View Set

Chapter 7- Miscellaneous Personal Lines Coverage

View Set

Biology 2 Lecture Connect HW - Ch. 39 Flowering Plants Transport

View Set

Using Equations and Powers of Numbers (271-32-4)

View Set

Mastering A&P - Ch.16 - End of Chapter Review

View Set