Java Quiz 1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

The _____ operator can be used to ensure that two conditions are both true before choosing a certain path of execution.

&&

Describe the four basic elements of counter-controlled repetition.

1. A controlled variable (or loop counter) 2. The initial value of the control variable. 3. The increment (or decrement) by which the control variable is modified each time through the loop (known as each iteration of the loop). 4. The loop-continuation condition that determines if looping should continue.

True or False? A nested control statement appears in the body of another control statement.

True.

True or False? An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which they execute.

True.

True or False? An expression containing the || operator is true if either or both of its operands are true.

True.

True or False? Java provides the arithmetic compound assignment operators +=, -=, *=, /=, and %= for abbreviating assignment expressions.

True.

True or False? Listing cases consecutively with no statements between them enables the cases to perform the same set of statements.

True.

Discuss a situation in which it would be more appropriate to use a do...while statement than a while. Explain why.

Use do...while instead of while when a set of instructions/block of statements that need to executed at least once. Example: Need to input set of integers in range 1 through 10 and find cumulative sum. int number, sum=0; cout<<"Enter number:"; cin>>number do{ sum=sum+number; cout<<"Enter number:"; cin>>number; }while(number>0&&number<10);

Declare variables x of type int and initialize it to 1.

int x = 1;

If the increment operator is _______ to a variable, first the variable is incremented by 1, then its new value is used in the expression.

prefixed

Determine the value of the variables in the statement product *= x++; after the calculation is performed. Assume that all variables are type int and initially have the value 5.

product = 25, x = 6

Instance variables of types char, byte, short, int, long, float, and double are all given the value _______ by default.

0 (zero)

Only there forms of control are needed to implement an algorithm:

Sequence Selection Repetition

True or False? Pseudocode helps you think out a program before attempting to write it in a programming language.

True.

True or False? Specifying the order in which statements execute in a program is called program control.

True.

True or False? The comma ( , ) formatting flag in a format specifier (e.g., %,20.2f) indicates that a value should be output with a thousands separator.

True.

Use one statement to assign the sum of x and y to z, then increment x by 1.

z = x++ + y;

Identify and correct the errors in each of the following pieces of code. if (age>= 65); System.out.println("Age is less than or equal to 65"); else System.out.println("Age is less than 65)";

Correction: no semi colon after if statement. if ( age >= 65 )

Find the error(s) in the following segments of code: The following code should print whether integer value is even or odd: switch (value % 2 ) { case 0: System.out.println("Even integer"); case 1: System.out.println("Odd integer"); }

Each case block should end with a break statement unless it is desired case 0 and case 1 print every time the program is executed. { case 0: System.out.println("Even integer"); break; case 1: System.out.println("Odd integer"); break; }

Find the error in each of the following code segments, and explain how to correct it: The following code should print the values 1 to 10: n = 1; while(n < 10) System.out.println(n++);

Error: An improper relational operator is used in the while's continuation condition. Correction: Use <= rather than <, or change 10 to 11.

Identify and correct errors in the following code: while (c <= 5) { product *= c; ++c

Error: The closing right brace of the while statement's body is missing. Correction: Add a closing right brace after the statement ++c;.

Find the error in each of the following code segments, and explain how to correct it: switch (n) { case 1: System.out.println("The number is 1"); case 2: System.out.println("The number is 2"); break; default: System.out.println("The number is not 1 or 2"); break; }

Error: The missing code is the break statement in the statements for the first case. Correction: Add a break statement at the end of the statements for the first case. This omission is not necessarily an error if you want the statement of case 2: to execute every time the case 1: statement executes.

Identify and correct errors in the following code: if (gender == 1) System.out.println("Woman"); else; System.out.println("Man");

Error: The semicolon after else results in a logic error. The second output statement will always be executed. Correction: Remove the semicolon after else.

Find the error in each of the following code segments, and explain how to correct it: i = 1; while (i <= 10); ++i; }

Error: The semicolon after the while causes an infinite loop, and there's a missing left brace. Correction: Replace the semicolon with a {, or remove both the ; and }.

Find the error in each of the following code segments, and explain how to correct it: for(k = 0.1; k != 1.0; k += 0.1) System.out.println(k);

Error: Using a floating-point number to control a for statement may not work, because the floating-point numbers are represented only approximately by most computers. Correction: Use an integer, and perform the proper calculation in order to get the values you desire: for(k = 1; k!= 10; k++) System.out.pringln((double) k/10);

True or False? A selection statement specifies that an action is to be repeated while some condition remains true.

False. A repetition statement specifies that an action is to be repeated while some condition remains true.

True or False? A set of statements contained within a pair of parentheses is called a block.

False. A set of statements contained within a pair of braces { and } is called a block.

True or False? The expression (( x > y) && (a < b)) is true if either x > y is true or a > b is true.

False. Both of the relational expressions must be true for the entire expression to be true when using the && operator.

True or False? Instance variables of type boolean are given the value true by default.

False. Instance variables of type boolean are given the value false by default.

True or False? The break statement is required in the last case of a switch selection statement.

False. The break statement is used to exit the switch statement. The break statement is not required for the last case in a switch statement.

True or False? The default case is required in the switch selection statement.

False. The default case is optional. If no default action needed, then there's no need for default case.

True or False? The primitive types (boolean, char, byte, short, int, long, float, and double) are portable across only Windows platforms.

False. The primitive types (boolean, char, byte, short, int, long, float, and double) are portable across all computer platforms that support Java.

True or False? To test for a range of values in a switch statement, use a hyper (-) between the start and end values of the range in a case label.

False. The switch statement does not provide a mechanism for testing ranges of values, so every value that must be tested should be listed in a separate case label.

True or False? The unary cast operator (double) creates a temporary integer copy of its operand.

False. The unary case operator (double) creates a temporary floating-point copy of its operand.

Find the error(s) in the following segments of code: For( i = 100, i >= 1, i++) System.out.println(i);

In looping statement for 'F' cannot be capital, all the initialization, condition, and increment/decrement must be separated by semicolons. The loop is an infinite loop--i value must be decremented (decreasing) for(i = 100; i >= 1; i--) System.out.println(i);

Find the error(s) in the following segments of code: The following code should output the even integers form 2 to 100: counter = 2; do{ System.out.println(counter); counter += 2; } While (counter > 100);

In while looping statement 'w' must be lowercase. counter = 2; do{ System.out.println(counter); counter += 2; } while (counter > 100);

What is the difference between pre incrementing and posincrementing a variable?

Pre-incrementing a variable causes the variable to be incremented by 1. The value of the variable is used in the expression in which it appears. Example: ++a; Post-incrementing variable causes the variable to incremented by 1. This causes the current value of the variable to be used in the expression in which it appears, then the expression value is incremented. Example: a++;

When it's not known in advance how many times a set of statements will be repeated, a(n) _______ value can be used to terminate the repetition.

Sentinel, signal, flag or dummy (only possible in while statements)

The _______ structure is built into Java; but by default, statements execute in the order they appear.

Sequence

All programs can be written in terms of three types of control structures _______, _______, and ______.

Sequence, selection, and repetition.

Describe the two ways in which control statements can be combined.

Stacking and Nesting

Print "The sum is: ", followed by the value of variable sum.

System.out.printf("The sum is: %d%n", sum);

Compare and contrast the *if* single-section statement and *while* repetition statement. How are these two statements similar? How are they different?

The *if* single-selection statement is a single-entry/single-exit control statement. The *while* repetition (or looping) statement allows you to specify that a program should repeat an action while some condition remains true. The similarity of a single-section and while repetition statements are entry condition checking statements. The difference is *if* block executes the statements only once, where as *while* executes that statements repeatedly until the condition is false and it also needs a counter variable to control the execution of loop.

Compare and contrast the break and continue statements.

The break statement, when executed in a while, for, do...while, or switch, causes immediate exit from that statement. The break statement is used to escape early form a loop or to skip the remainder of switch. The continue statement, when executed in a while, for, or do...while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. In a while and do...while statement, the program evaluates the loop-continuation test immediately after the continue statement executes. In a for loop, the increment expression executes then the program evaluates the loop continuation test.

Identify and correct the errors in each of the following pieces of code. while (y > 0) { System.out.println(y); ++y;

The code is missing the closed brace. The correct code is: while (y > 0) { System.out.println(y); +=y; }

What type of repetition would be appropriate for calculating the sum of the first 10 positive integers? Briefly describe how this task could be performed.

The counter controlled repetition would be appropriate for the calculating sum of first 100 positive integers because the number of repetitions is known in advance--the program that performs this task could use a while repetitions statement with a counter variable that takes on the values of 1 to 100. The program could then add the current counter value to the total variable in each repetition of the

Identify and correct the errors in each of the following pieces of code. int x =1, total ; while (x <= 10) { total += x; ++x; }

The error is variable total must be initialized to zero before using the while loop. Correct code is: int x=1, total=0;

Find the error(s) in the following segments of code: The following code should output the odd integers from 19 to 1: for (i = 19; i >= 1; i += 2) System.out.println(i);

The loop is infinite--i value must be decremented by 2. for (i = 19; i >= 1; i -= 2) System.out.println(i);

What type of repetition would be appropriate for calculating the sum of an arbitrary number of positive integers? Briefly describe how this task could be performed.

The sentinel controlled repetition would be appropriate for calculating the sum of an arbitrary number of positive integers. The program that performs this task could use a sentinel value of -1 to mark the end of data entry. The program could use a while repetition statement that tools positive integers from the user enters the sentinel value.

Identify and correct the errors in each of the following pieces of code. while (x <= 100) total += x; ++x;

The set of statements that must be executed repeatedly must be placed in a set of braces and the logic provided will result in an infinite loop. Correct code is: while (x <= 100) { total += x; ++x; }

What is wrong with the following while statement? while (>= 0) sum += z;

The value of the variable z is never changed in the sale statement. Therefore, if the loop-continuation condition (z >= 0) is true, an infinite loop is created. To prevent an infinite loop form occurring, z must be decremented so that it eventually becomes less than 0.

Compare and contrast the while and for repetition statements

The while statement can be used to implement any counter controlled loop but the for repetition statement is for specifying the counter controlled repetition detail in a single line of code. The for statements are used for counter controlled repetition and the while statements for sentinel controlled repetition. Both the while and for can each be used for either repetition type.

Explain what happens when a Java program attempts to divide one integer by another. What happens to fractional part of the calculation? How can you avoid that outcome?

When a Java program attempts to divide one integer by another then any fractional part of the calculation is lost (i.e. truncated). In this situation, assuming that integer division rounds (rather than truncates) can lead to incorrect results. For example, 7/4, which yields 1.75 in conventional arithmetic, truncates to 1 in integer arithmetic, rather than rounding to 2.

The do...while statement tests the loop continuation condition ______ executing the loop's body; therefore, the body always executes at least once.

after

The _____ statement, when executed in a repetition statement, skips the remaining statements in the loop body and proceeds with the next iteration of the loop.

continue

Repeating a set of instructions a specific number of times is called _______ repetition.

counter-controlled (or definite)

Write a Java statement or a set of Java statements to accomplish each of the following tasks: Calculate the value of 2.5 raised to the power of 3, using the pow method.

double result = Math.pow(2.5, 3);

If the loop-continuation condition in a for header is initially _____, the program does not execute the for statement's body.

false

Typically, _____ statements are used for counter-controlled reputation and _____ statements for sentinel-controlled repetition.

for while

Write a Java statement or a set of Java statements to accomplish each of the following tasks: Print the integers from 1 to 20, using a while loop and the counter inside the variable i. Assume that the variable i has been declared, but not initialized. Print only five integers per line. [Hint: Use the calculation i % 5. When the value of this expression is 0, print a newline character; otherwise, print a tab character. Assume that this code is an application. Use the System.out.println() method to output the newline character, and use the System.out.print('\t') method to output the tab character.]

i = 1; while(i <= 20) { System.out.print(i); if(i % 5 == 0) System.out.println(); else System.out.print.('\t'); ++i; }

Test whether variable count is greater than 10. If it is, print "Count is greater than 10".

if (count > 10) System.out.println("Count is greater than 10");

The _______ statement is used to execute one action when a condition is true and another when that condition is false.

if...else

Declare variables sum of type int and initialize it to 0.

int sum = 0;

Calculate the remainder after q is divided by divisor, and assign the result to q. Write this statement in two different ways.

q %= divisor; or q = q % divisor;

Methods that perform common tasks and do not require objects are called _____ methods.

static

Java is a(n) _______ language; it requires all variables to have a type.

strongly typed

Add variable x to variable sum, and assign the result to variable sum.

sum += x; or sum = sum = x;

Write a Java statement or a set of Java statements to accomplish each of the following tasks: Sum the odd integers between 1 and 99, using for statement. Assume that the integer variables sum and count have been declared.

sum = 0; for (count = 1; count <= 99; count += 2) sum += count;

The _____ statement selects among multiple actions based on the possible values of an integer variable or expression or a String

switch

Use one statement to decrement the variable x by 1, then subtract it from variable total and store the result in variable total.

total -= --x;

Write four different Java statements that each add 1 integer to integer variable x.

x = x + 1; x += 1; ++x; x++;


Kaugnay na mga set ng pag-aaral

BJU Physical Science (6th ed.) - Chapter 4

View Set

Prevention to Sports Injury Ch. 7-12

View Set

Die Revolution der Erde um die Sonne

View Set

Biology: MICROBIAL TAXONOMY and FUNGI Quiz Review

View Set

SA Practice Parallel Circuits and Circuit Elements

View Set