4.5 More loop examples

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

++ operator can appear as

++i (prefix form) i++(postfix form)

What are the values of currC for the first four iterations? Type as: 1 9 2 6

-10 -5 0 5 currC is initialized with -10. The update amount is + 5. Thus, the first four iterations are -10, -10+5 or -5, -5+5 or 0, and 0+5 or 5.

for (i = -3; i <= 3; ++i) { (Put i to output, followed by a space) }

-3 -2 -1 0 1 2 3 A for loop can start with a negative value

What is the loop's variable's name?

-currC While the loop variable could have been named i, the name currC (current Celsius) is more descriptive, helping a reader better understand the program.

Avoid these loop variations

// initialExpression not related to counting iterations; move r = rand() before loop for (i = 0, r = rand(); i < 5; ++i) { // Loop body } // updateExpression not related to counting iterations; move r = r + 2 into loop body for (i = 0; i < 5; ++i, r = r + 2) { // Loop body }

Type the output of the for loop. Whitespace matters, including after the last item. for (i = 1; i <= 5; ++i) { (Put i to output, followed by a space) } Outputs: 1 2 3 4 5 1) for (i = 0; i < 5; ++i) { (Put i to output, followed by a space)

0 1 2 3 4 This loop is the standard counting for loop that happens to output the loop variable's value.

for (i = 0; i < 5; ++i) { (Put 2 * i to output, followed by a space) }

0 2 4 6 8 Notice that the output is of 2 * i, not just of i. A for loop may iterate N times and use N in calculations.

for (i = 0; i < 10; i = i + 2) { (Put i to output, followed by a space) }

0 2 4 6 8 The update expression is i = i + 2 rather than ++i. Thus each iteration increases i by 2, not 1. Also, 8 is the last value output, because 10 < 10 is false.

for (i = 1; i <= 5; ++i) { (Put i to output, followed by a space) }

1 2 3 4 5 The loop starts with 1 due to i = 1. The loop ends with 5 rather than 4, due to <= 5 rather than < 5.

for (i = 5; i >= 0; --i) { (Put i to output, followed by a space) }

5 4 3 2 1 0 A for loop can count down rather than up. Notice the use of --i rather than ++i.

Before entering the loop, what is the maximum value seen so far from the list of integers?

Before the loop, no list item has been input yet, so no max has been seen.

// initialExpression not related to counting iterations; move r = rand() before loop for (i = 0, r = rand(); i < 5; ++i) { // Loop body } // updateExpression not related to counting iterations; move r = r + 2 into loop body for (i = 0; i < 5; ++i, r = r + 2) { // Loop body } The above two for loop variations each yield a syntax error.

False In Java, the for loop has three parts: initialization, condition, and update. While it is valid to include code in any of these parts, it is generally best practice to restrict each part to counting only. It is not a good idea to include code in the initialization or update parts that is not related to counting because it can make the code harder to read and understand. For example, while it is true that the initialization expression executes before the loop, and the update expression executes after the loop body, this does not justify including unrelated code in these parts. The initialization and update expressions should be used to increment or decrement a loop variable, and should not be used for other purposes.

// initialExpression not related to counting iterations; move r = rand() before loop for (i = 0, r = rand(); i < 5; ++i) { // Loop body } // updateExpression not related to counting iterations; move r = r + 2 into loop body for (i = 0; i < 5; ++i, r = r + 2) { // Loop body } Putting ++i at the end of a for loop body, in addition to in the updateExpression part, yields a syntax error.

False The code is valid. The ++i in the loop body will execute, and then the ++i from the updateExpression part will also execute, thus incrementing i twice.

What is the loop expression? (The expression checked for whether to enter the loop body).

currC <= 40 The loop will iterate with currC of 40, but not with 45. The programmer could have written currC < 45 (or 41), but the <= 40 approach is more explicit, making clear that the last value considered is 40. (Note that this expression differs from the standard approach when merely looping N times, which starts with i = 0 and has expression i < N).

For each iteration after the first iteration, the comparison _____ is checked.

currValue > maxSoFar After the first iteration, i == 0 will be false, so the else if expression is checked. If the current value is greater than the max seen so far, then that current value is the new max seen so far, so the else if branch executes maxSoFar = currValue.

Write code that prints: countNum ... 2 1 Print a newline after each number. Ex: If the input is: 3 the output is: 3 2 1

import java.util.Scanner; public class ForLoops { public static void main (String [] args) { int countNum; int i; Scanner input = new Scanner(System.in); countNum = input.nextInt(); for (/* Your code goes here */) { System.out.println(i); } } }

Write code that prints: Ready! numVal ... 2 1 Go! Your code should contain a for loop. Print a newline after each number and after each line of text. Ex: If the input is: 3 the output is: Ready! 3 2 1 Go!

import java.util.Scanner; public class ForLoops { public static void main (String [] args) { int numVal; int i; Scanner input = new Scanner(System.in); numVal = input.nextInt(); /* Your code goes here */ } }

Write a for loop that prints: 1 2 ... numVal Ex: If the input is: 4 the output is: 1 2 3 4

import java.util.Scanner; public class ForLoops { public static void main (String [] args) { int numVal; int i; Scanner input = new Scanner(System.in); numVal = input.nextInt(); for (/* Your code goes here */) { System.out.print(i + " "); } } }

Write a for loop that prints userNum ... -1 0. Ex: If the input is: -3 the output is: -3 -2 -1 0

import java.util.Scanner; public class ForLoops { public static void main (String [] args) { int userNum; int i; Scanner input = new Scanner(System.in); userNum = input.nextInt(); for (/* Your code goes here */) { System.out.print(i + " "); } } }

Loop style issues

normalizing on looping N times by starting with i=0 and checking for i < N rather than using i = 1, and i = <=N One reason is due to using arrays or vectors using with loops starting with 0.

Do these loops iterate the same number of times? for (i = 0; i < 5; ++i) { ... } for (i = 1; i <= 5; ++i) { ... }

Yes The first iterates with i as 0, 1, 2, 3, and 4. The second iterates with i as 1, 2, 3, 4, and 5. Both iterate 5 times. Starting with 0 is simply the more standard approach.

The loop's first iteration gets the list's first integer into variable currValue. Is that the maximum value seen so far?

Yes The first value is the max value seen so far, as well as being the min value seen so far. The if-else statement's i == 0 branch detects that this iteration is the first, and simply assigns maxSoFar = currValue.

Is the following valid code? for (int i = 0; i < 5; ++i) { ... }

Yes The int i = 0; part declares a variable i and initializes i with 0. That form is common in practice. However, for learners, this material declares all variables first, rather than throughout the code, and thus this material avoids such in-loop declaration.

Does this for loop iterate 5 times? for (i = 0; i < 5; ++i) { ... }

Yes! The update expression can be either ++i or i++. In this case, no difference occurs. But this material uses ++i, which some teachers consider to be safer for learners.


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

Life Span Development by John Santrock 13th Edition Chapter 8

View Set

Lesson 12: LIFE IN A PURITAN COMMUNITYLIFE IN A PURITAN COMMUNITY

View Set

FINC 512 Quizzes1-11 (Final Exam)

View Set

Biology Section 4-3 Review: Cell Organelles and Features

View Set

Anatomy and physiology directional terms

View Set

Chapter 6 concepts & Definitions

View Set

Chemical Formulas & Equations (Test 12/9)

View Set

Animal Classification 3 (mylab and mastering)

View Set

MGT 3013 Chapter 13, 14, 15, & 16 Multiple Choice Questions

View Set