Java exam 1 part 33

¡Supera tus tareas y exámenes ahora con 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.

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.

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.

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? 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? 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? 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.

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

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

Sequence Selection Repetition

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

Stacking and Nesting

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; }

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.

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

True.

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

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.

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);

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

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; }

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

static

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


Conjuntos de estudio relacionados

Accounting applications midterm (ch. 1-5)

View Set

Neurosensory and Musculoskeletal

View Set

ExamFX Life Insurance (Taxes, Retirement, and Other Insurance Concepts)

View Set

AR Life Insurance Exam Study Guide

View Set

N-283 Ch. 40-41 Practice Questions

View Set

Slope, Intercepts, and Slope Intercept Form, Slope and Slope Intercept Form

View Set