Java Chapter 5 Looping

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

The following loop displays _______________. for (int i = 1; i <= 10; i++) { System.out.print(i + " "); i++; }

1 3 5 7 9 (i++ is post iteration)

How many times will the following code print "Welcome to Java"? int count = 0; while (count < 10) { System.out.println("Welcome to Java"); count++; }

10

How many times will the following code print "Welcome to Java"? int count = 0; do { System.out.println("Welcome to Java"); count++; } while (count < 10);

10

How many times will the following code print "Welcome to Java"? int count = 0; do { System.out.println("Welcome to Java"); } while (++count < 10);

10

How many times will the following code print "Welcome to Java"? int count = 0; while (count++ < 10) { System.out.println("Welcome to Java"); }

10

What is the value in count after the following loop is executed? int count = 0; do { System.out.println("Welcome to Java"); } while (count++ < 9); System.out.println(count);

10

How many times will the following code print "Welcome to Java"? int count = 0; do { System.out.println("Welcome to Java"); } while (count++ < 10);

11

Given the following method static void nPrint(String message, int n) { while (n > 0) { System.out.print(message); n--; } } What is k after invoking nPrint("A message", k)? int k = 2; nPrint("A message", k);

2

What is the output of the following code? int x = 0; while (x < 4) { x = x + 1; } System.out.println("x is " + x);

4

What is the output for y, 13, 0 or 45 int y = 0; for (int i = 0; i<10; ++i) { y += i; } System.out.println(y);

45

What will be displayed when the following code is executed? int number = 6; while (number > 0) { number -= 3; System.out.print(number + " "); }

6 0 (4.5 question...)

FOR LOOP. The initial-action, loopcontinuation- condition, and action-after-each-iteration are separated by _.

;

int count = 0; while (count < 100) {/ / Point A System.out.println("Welcome to Java!"); count++; // Point B } // Point C count < 100 is always true at Point count < 100 is always false at Point

A, C

__ consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew.

Nested loops

Print the string length for the Str1

System.out.println(Str1.length());

Use integers for _. Imprecision in floating point numbers make them unreliable.

counters

A _ loop is the same as a while loop except that it executes the loop body first and then checks the loop _ condition.

do while, continuation

The do-while loop is a variation of the while loop. Its syntax is:

do { statements; } while (loop continuation condition);

The result of a floating-point calculation can depend on the order of _.

evaluation

Eventually, the value of the control variable should force the loop-continuation-condition to become _; otherwise, the loop is _.

false, infinite

Don't use _ values for equality checking in a loop control; they are approximations for some values, using them could result in imprecise counter values and inaccurate results

floating point

while (loop-continuation-condition) { } do the same with a FOR...

for ( ; loop-continuation-condition; ) { }

In the _, the action-after-each-iteration is performed, then the loop-continuation-condition is evaluated, immediately after the continue statement.

for loop

Finding the Greatest Common Divisor 5 (update gcd)

gcd = k;

Finding the Greatest Common Divisor 4 (check using if whether k to kn is a common divisor for n1 and n2.... if (...)

if (n1 % k == 0 && n2 % k == 0)

The program in Listing 5.13 adds integers from 1 to 20 except 10 and 11 to sum. while (number < 20) { number++; __ __ sum += number; }

if (number ==10 || number == 11) continue;

The program in Listing 5.12 adds integers from 1 to 20 in this order to sum until sum is greater than or equal to 100. while (number < 20) { number++; sum += number; __ __ }

if (sum >= 100) break;

Analyze the following statement: The program compiles and runs fine; there is no _ double sum = 0; for (double d = 0; d < 10;) { d += 0.1; sum += sum + d; }

infinite loop

Make sure that the loop-continuation-condition eventually becomes false so that the loop will terminate. A common programming error involves _ _ (i. e., the loop runs forever). If your program takes an unusually long time to run and does not stop, it may have an infinite loop. If you are running the program from the command window, press CTRL+C to stop it.

infinite loops

FOR LOOP METHOD for (_; loop-continuation-condition; action-after-each-iteration) { // Loop body; Statement(s); }

initial action

The _ in a for loop can be a list of zero or more comma-separated variable declaration statements or assignment expressions. For example: for (int i = 0, j = 0; i + j < 10; i++, j++) { // Do something }

initial action

The control variable must be declared inside the control structure of the loop or before the loop. If the loop control variable is used only in the loop, and not elsewhere, it is a good programming practice to declare it in the _ of the for loop.

initial action

for (initial-action; loop-continuation-condition; action after each iteration) { Loop body; } --- do this with While using the same terms

initial action; while (loop continuation condition) { Loop body; action after each iteration; }

FOR LOOP: The initial action often _, the action-after-each-iteration usually increments or decrements the control variable

initializes a control variable

java SentinelValue < input.txt. This command is called _. The program takes the input from the file input .txt rather than having the user type the data from the keyboard at runtime.

input redirection

Using a loop (while) statement, say "Welcome to Java" 100 times... (use the word count not i)

int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; }

Finding the Greatest Common Divisor 1 (// Initial gcd is 1)

int gcd = 1;

When guess matches number, the loop should end. So, the loop can be revised as follows: (also initialise the guess first).

int guess = -1; while (guess != number) { ( Note that guess is initialized to -1. Initializing it to a value between 0 and 100 would be wrong, because that could be the number to be guessed)

The loop control variable can be declared and initialized in the for loop. Here is an example for int i = 0): for (__; i < 100; i++) { System.out.println("Welcome to Java!"); }

int i = 0 (If there is only one statement in the loop body, as in this example, the braces can be omitted.)

the following for loop prints Welcome to Java a hundred times: int i; for (....

int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java"); }

Finding the Greatest Common Divisor 2 (// initialise k)

int k = 2;

// Generate a random number to be guessed between 1-100

int number = (int)(Math.random() * 101);

Given the following method static void nPrint(String message, int n) { while (n > 0) { System.out.print(message); n--; } } What will be displayed by the call nPrint('a', 4)?

invalid call (because char 'a' cannot be passed to deal table)

The command for output redirection is:

java ClassName > output.txt

This command is called input redirection. In the preceding example, if you have a large number of data to enter, it would be cumbersome to type from the keyboard. You can store the data separated by whitespaces in a text file, say input.txt, and run the program using the following command. The program takes the input from the file input .txt rather than having the user type the data from the keyboard at runtime.

java SentinelValue < input.txt

Input and output redirection can be used in the same command. For example, the following command gets input from input.txt and sends output to output.txt:

java SentinelValue output.txt

Finding the Greatest Common Divisor 6 (Next possible gcd) (k...)

k++;

After this loop, sum is 50.49999999999995. Adding from biggest to smallest is _ accurate than adding from smallest to biggest.

less (page 179)

You have used the keyword break in a switch statement. You can also use break in a _ to immediately terminate.

loop

The part of the loop that contains the statements to be repeated is called the __. A one-time execution of a loop body is referred to as an iteration (or _) of the loop

loop body, repetition

Each loop contains a _, a Boolean expression that controls the execution of the body.

loop continuation condition

The initial-action, i = 0, initializes the control variable, i. The _, i < 100, is a Boolean expression.

loop continuation condition

for (initial-action; _; action-after-each-iteration) { // Loop body; Statement(s); }

loop continuation condition

If the variable is declared inside the ___, it cannot be referenced outside the loop. In the preceding code, for example, you cannot reference i outside the for loop, because it is declared inside the for loop.

loop control structure

The signature of a method consists of ____________.

method name and parameter list

Does the method call in the following method cause compile errors? public static void main(String[] args) { Math.pow(2, 4); }

no

Does the return statement in the following method cause compile errors? public static void main(String[] args) { int max = 0; if (max != 0) System.out.println(max); else return; }

no

Programmers often make the mistake of executing a loop one more or less time. This is commonly known as the _. For example: While (count <= 100) { The error lies in the condition, which should be count < 100.

off by one error

sends the output to a file rather than displaying it on the console. (term)

output redirection

Arguments to methods always appear within ________.

parentheses

while (count < 100) { The loop-continuation-condition must always appear inside the _. The braces {} enclosing the loop body can be omitted only if the loop body contains one or no statement

parentheses

When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as _________.

pass by value

The do-while loop is called a __ because the condition is checked after the loop body is executed.

posttest

The while loop and for loop are called _ because the continuation condition is checked before the loop body is executed.

pretest loops

All Java applications must have a method __________.

public static void main(String[] args)

Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a _ value, signifies the end of the input. A loop that uses a _value to control its execution is called a sentinel-controlled loop.

sentinel

Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value, signifies the end of the input. A loop that uses a sentinel value to control its execution is called a _.

sentinel controlled loop

If the loop-continuation-condition in a for loop is omitted, it is implicitly _.

true

What is i after the following for loop? int y = 0; for (int i = 0; i<10; ++i) { y += i; }

undefined (the scope of i is inside the loop. After the loop, i is not defined. )

var str = "HELLO WORLD"; __ Return the first character of a string. Call it res.

var res = str.charAt(0)

5.1 Suppose your method does not return any value, which of the following keywords can be used as a return type?

void

You should fill in the blank in the following code with __. public class Test { public static void main(String[] args) { System.out.print("The grade is "); printGrade(78.5); System.out.print("The grade is "); printGrade(59.5); } public static __________ printGrade(double score) { if (score >= 90.0) { System.out.println('A'); }

void

A _ loop executes statements repeatedly while the condition is true

while

Finding the Greatest Common Divisor (3). Program for while k <= n1 and <=n2.

while (k <= n1 && k <= n2) {

while loop format

while (loop continuation condition) { Statements; }

program to let a user repeatedly enter a new answer until it is correct, number1 + number2 = answer. Start of while loop (no statement).

while (number1 + number2 != answer) {

for ( ; ; ) --> same as---> for ( ; true; ) { but better is:

while (true) { }

The continue statement is always inside a loop. In the _ loops, the loop-continuation-condition is evaluated immediately after the continue statement.

while (while, do-while)

Java provides three types of loop statements: _ loops, _ loops, and _ loops.

while, do while, for

Is the following loop correct? for (; ; );

yes

Finding the Greatest Common Divisor 7 (end)

}

Do the following two statements in (I) and (II) result in the same value in sum? (I): for (int i = 0; i<10; ++i) { sum += i; } (II): for (int i = 0; i<10; i++) { sum += i;

Yes

Which of the following should be defined as a void method? A. Write a method that prints integers from 1 to 100. B. Write a method that returns a random integer from 1 to 100. C. Write a method that checks whether current second is an integer from 1 to 100. D. Write a method that converts an uppercase letter to lowercase.

a

Each time a method is invoked, the system stores parameters and local variables in an area of memory, known as _______, which stores elements in last-in first-out fashion.

a stack

The __, i++, is a statement that adjusts the control variable. This statement is executed after each iteration and increments the control variable.

action after each iteration

for (initial-action; loop-continuation-condition; _) { // Loop body; Statement(s); }

action after each iteration

Use a do-while loop if you have statements inside the loop that must be executed __, as in the case of the do-while loop in the preceding TestDoWhile program. These statements must appear before the loop as well as inside it if you use a while loop.

at least once

You should fill in the blank in the following code with ______________. public class Test { public static void main(String[] args) { System.out.print("The grade is " + getGrade(78.5)); System.out.print("\nThe grade is " + getGrade(59.5)); } public static _________ getGrade(double score) { if (score >= 90.0) return 'A'; else if (score >= 80.0) return 'B'; else if (score >= 70.0) return 'C'; else if (score >= 60.0) return 'D'; else return 'F'; } }

char

The action-after-each-iteration in a for loop can be a list of zero or more _. For example: for (int i = 1; i < 100; System.out.println(i), i++);

comma-separated statements (This example is correct, but it is a bad example, because it makes the code difficult to read. Normally, you declare and initialize a control variable as an initial action and increment or decrement the control variable as an action after each iteration.)

You can also use the _ keyword in a loop. When it is encountered, it ends the current iteration and program control goes to the end of the loop body.

continue

In other words, _ breaks out of an iteration while the _ keyword breaks out of a loop.

continue, break

A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates. This variable is referred to as a _.

control variable

FOR LOOP: the action-after-each-iteration usually increments or decrements the _

control variable

In this example, you know exactly how many times the loop body needs to be executed because the control variable count is used to count the number of executions. This type of loop is known as a _.

counter controlled loop


Ensembles d'études connexes

American History Activity questions Unit 2

View Set

AP Macro Unit 1: Basic Economic concepts

View Set