4.2 While Loop

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

Character valueIn is read from input. Write a while loop that reads characters from input until character 's' is read. Then, count the total number of characters read. Character 's' should not be included in the count. Ex: If the input is k s, then the output is: 1

import java.util.Scanner; public class CountCalculator { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); char valueIn; int sum; sum = 0; valueIn = scnr.next().charAt(0); /* Your code goes here */ System.out.println(sum); } }

A while loop reads integers from input. Write an expression that executes the while loop until a negative integer is read from input. Ex: If the input is 27 45 -15, then the output is: Integer is 27 Integer is 45 Exit

import java.util.Scanner; public class IntegerReader { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int value; value = scnr.nextInt(); while (/* Your code goes here */) { System.out.println("Integer is " + value); value = scnr.nextInt(); } System.out.println("Exit"); } }

Each execution of the loop body is called

iteration

Each loop iteration outputs the current number of ancestors (numAnc), and then doubles numAnc in preparation for the next iteration.

-True Updating a value in each iteration is a common pattern

What is happening in this program?

-program asks for user to enter a year, then outputs the approdximate number of a persons ancestors who were alive for each generation leading back to that year with the powers of 2. Each iteration prints a line with the year and ancestors.

For the following code, indicate how many times the loop body will execute for the indicated input values. Input: -1 5 4 int userNum = //Get input into userNum while (userNum > 0) { // Do something ... userNum = //Get input into userNum }

0 The loop's expression will see: -1 > 0: False, so body does not execute The additional inputs are not relevant; the -1 ends the looping.

Input: -1 5 4 int userNum = 3; while (userNum > 0) { // Do something userNum = // Get input into userNum }

1 3 > 0: Loop body executes -1 > 0: False, so body does not execute The additional inputs are not relevant; the -1 ends the looping.

If the user's first input is 'n', how many times will the loop iterate?

1 After the first iteration, the user's input of 'n' is gotten into userChar, and execution jumps back to the while part. userChar == 'y' is thus false, and a second iteration will not occur. The only output would be "0 C is 32 F".

For the following code, indicate how many times the loop body will execute for the indicated input values. Input: 5 -1 int userNum = //Get input into userNum while (userNum > 0) { // Do something ... userNum = //Get input into userNum }

1 The loop's expression will see: 5 > 0: Body executes -1 > 0: False, body does not execute Thus, the loop body was executed once

While Loop Example

1.When encountered, a while loop's expression is evaluated. If true, the loop's body is entered. Here, userChar was initialized with 'y', so userChar == 'y' is true 2.Thus, the loop body is executed, which outputs currPower's current value of 2, doubles currPower, and gets the next input. 3.Execution jumps back to the while part. userChar is 'y' (the first input), so userChar == 'y' is true, and the loop body executes (again), outputting 4. 4.userChar is 'y' (the second user input), so userChar == 'y' is true, and the loop body executes (a third time), outputting 8. 5.userChar is now 'n', so userChar == 'y' is false. Thus, execution jumps to after the loop, which outputs "Done"

x = 5; y = 18; while (y >= x) { System.out.print(y + " "); y = y - x; }

18 13 8 -as long as y is greater than or equal to 5, y's value will be printed then decremented by 5. -there is a space after each number.

For the following code, indicate how many times the loop body will execute for the indicated input values. Input: 2 1 0 int userNum = //Get input into userNum while (userNum > 0) { // Do something ... userNum = //Get input into userNum }

2 The loop's expression will see: 2 > 0: Body executes 1 > 0: Body executes 0 > 0: False, so body does not execute So the body executes 2 times.

1.Some loop expressions use a relational operator like userNum > 0. If the input is 902, the first iteration executes (902 > 0), so outputs 902 % 10, or 2.

2.The body assigned userNum = userNum / 10, so 902 becomes 90. The loop jumps back, and since 90 > 0, the loop iterates again, outputting 90 % 10 or 0.

For the following code, indicate how many times the loop body will execute for the indicated input values. Input: 2 1 0 int userNum = 3; while (userNum > 0) { // Do something userNum = // Get input into userNum }

3 The loop's expression will see: 3 > 0: Body executes 2 > 0: Body executes 1 > 0: Body executes 0 > 0: False, so body does not execute So the body executes 3 times.

Each iteration adds _____ to celsiusValue.

5 The loop body includes the statement: celsiusValue = celsiusValue + 5; This pattern of updating a value in each iteration is commonplace.

For the user inputs shown, how many times did the loop iterate?

9 Each iteration outputs C and F values. 9 such outputs occur (0 C is 32 F, 5 C is 41 F, ..., 40 C is 104 F), so the loop must have iterated 9 times.

The user is asked to enter a value at the end of each loop iteration

False User only enters one value before the loop begins, then the loop executes while the consYear is greater than or equal to userYear

Infinite loop

Loop that never stops iterating -to prevent this we have to update a variable in a body, or creating a loop expression whose evaluation to false isnt always reachable.

Expression describes when the loop should iterate

Not when the loop should terminate

While Loop

Program construct that repeatedly executes a list of sub-statements (loop-body) expressions evaluates to be true

Iterate while c equals 'g'.

c=='g'

Loop body execution continues to

Body's end even if the expression would become false midway through.

// Get input into userChar while (userChar == 'y') { // Do something ... // Get input into userChar }

Getting input before a loop got user input into a variable only at the end of the loop body. that variable an initial value that always caused the loop body to execute the first time. Another common pattern gets that initial value from user input as well, thus getting input in two places: before the loop, and at the loop body's end.

x = 0; while (x <= 5) { System.out.print(x + " "); }

IL Infinite loop because x is not updated within the loop x is always less than 5. Not updating is a common cause for a infinite loop.

x = 10; while (x != 3) { System.out.print(x + " "); x = x / 2; }

IL No matter how many times 10 is divided by 2, the result will never equal 3. The programmer should have used x>= 3

Sometimes a loop is executed as long as the value is greater than another value, or less than another value.

Sometimes a loop is executed as long as a value is NOT equal to another value. EX: While loop using a relational operator in the loop expression

The loop expression involves a relational operator.

True As long as the considered year is greater than or equal to the user year the loop iterates.

True or False, the loop will always iterate at least once.

True userChar is initialized with 'y' and then the loop expression userChar == 'y' is checked. So for that first check, the expression is always true and the loop will iterate at least that first time.

int userNum = 3; while (userNum > 0) { // Do something userNum = // Get input into userNum } Second time: 5 > 0 (5 was gotten from input).

True, so loop body executes. Third time: -1 > 0 (-1 was gotten from input). False, so loop body does NOT execute. Thus, the loop body was executed twice.

Common errors with loops

Use the opposite loop expressire like using x==0 rather than x!=0.

x = 0; while (x > 0) { 'System.out.print(x + " "); x = x - 1; } System.out.print("Bye");

What will the following code output, for infinite loop type "IL" Bye x=0 so the loop is never entered

The loop body updates the considered year consYear

Yes consYear was initialized with 2020. Each loop iteration decreased consYear by YEARS_PER_GEN which is 20.

Iterate while c is not equal to 'x'.

c!='x' As long as c is not equal to 'x' the loop executes. When c equals x the loop finishes.

Iterate until c equals 'z'

c!='z' 'Until' meaning to loop while c does not equal 'z' the 'not equal' is needed here.

userChar = scnr.next().charAt(0);

next() reads a string from the user input, then charAt(0) gets the first character within that string.

While Loop Syntax

while (expression) { // Loop expression // Loop body: Executes if expression evaluated to true // After body, execution jumps back to the "while" } // Statements that execute after the expression evaluates to false

1)Iterate while x is less than 100.

x < 100

Iterate while x is greater than or equal to 0.

x>=0 x=>0 is not okay because its not an operator


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

Exam 3: Time Value of Money - Finding Present Value

View Set

Field Devices and Controllers (ICS410.2)

View Set

BL Ch. 33: Limited Partnerships and Limited Liability Corporations

View Set

NB Practice Questions - Behavioral/Psychosocial

View Set

clicker questions chapter 23 and 24

View Set

Basic physical assessment Prep- U

View Set

Ultrasound SPI Chapter 1 Questions

View Set