·Thewhile statement: definition, syntax

·Loop ax

·Loops using the while statement:

oCounter-controlled loops (definite loops)

oEvent-controlled loops (indefinite loops)

§Sentinel-controlled loops

§EOF-controlled loops

§Flag-controlled loops

·Looping subtasks (counting, summing, etc)

·Choosing the correct type ofloop for a given problem.

·Nested whileloops.

·SamplePrograms (Program#1, regimen #2) and also Exercises

OUTLINE


1. The while statement

Loop = A regulate structure that reasons a explain or group of statements to be enforcement repeatedly. The scheduled word while deserve to be offered to repeat a set of statements until a specific condition is met. A when statement (while loop) will certainly test a condition. Statements may be executed over and over until the condition is met. Once the expression is tested and found to be false, the loop is exited and control passes to the explain which complies with the loop body. Syntax:

while(Expression)//test . //loop human body . //loop body

Note1: The loop body can be asingle statement, a null statement, or a block. Note2:Do not placed a semicolon after while(Expression) - null explain Note3:Do no interchange if and also while reasoning that both statements have conditional tests. Whatis the difference?

while Loop:

Example 1:

intx = 0; when ( x x = x + 1; System.out.println("x= " + x);}

2.Loop Terminology

Loop problem (the expression to it is in tested) - acts together a decision-maker and also it is a logical expression. Likewise called loop test (the Expression is evaluated and a decision is made come either begin a new iteration or skip to the first statement adhering to the loop.) Loop regulate variable = A change in the loop condition that is offered to recognize whether the human body of the loop will certainly execute or not. Loop body - statements to be repeated. Can be either a simple or compound statement. Loop entry = the allude where the regulate reaches the very first statement within the loop human body Iteration = repeat of the loop body (each time as soon as the body of the loop is executed) Loop exit = the allude where the repetition of the loop human body ends and also control is passed come the first statement complying with the loop. Note: The loop leave occurs only when the loop check is performed, no midway v the execution of the loop - the existing iteration is completed prior to the while Expression is confirm again. In other words, the loop is exited just when control passes to the peak of the loop and also the termination problem is uncovered to be true. If the manage enters the loop body, execution of the human body is completed prior to the following test is made. Termination condition = the condition that reasons the loop to be exited. Note: In a when loop, the termination condition is that the while Expression becomes false. A loop that proceeds to execute unending is dubbed an infinite loop.

You are watching: Which structure causes a statement or set of statements to execute repeatedly?

3. LoopsUsing the while Statement

Types the loops: Counter-controlled loops - repeat a specified variety of times (when you recognize upfront the number of iterations) Event-controlled loops - some condition within the loop body changes and this causes the repeating come stop and also the loop to be exited (when girlfriend don"t recognize the exact variety of iterations). The termination problem depends on some event occurring while the loop human body is executing. Types: Sentinel managed - keep handling data until a special value (which is not a possible data value) is gone into to show that processing need to stop End-of-file regulated - keep processing data as long as over there is much more data in the paper Flag controlled - keep processing data until the value of a flag (usually a boolean variable) alters in the loop body

Example of species of loops:

Counter-controlled loop

Read specifically 100 numbers

Sentinel-controlled loop

Read part numbers, until a special value, liked by you, which is no a legitimate value, is found

End-of-file managed loop

Read all the number in the file, no issue how countless they are

Flag-controlled loop

Read some numbers, till a distinct value is found. Once found, readjust the worth of the flag.

Another example: The "temperature"problem (to be discussed with all types of loops)

Counter-controlled loop

Read specifically 100 temperatures

Sentinel-controlled loop

Read temperatures, till a one-of-a-kind value, liked by you, i m sorry is no a legitimate value, is found (Ex: temp = 999)

End-of-file managed loop

Read every temperatures in the file, no issue how countless they are

Flag-controlled loop

Read temperatures, until a dangerously high worth (Ex: temp >= 200) is found. When found, adjust the worth of the flag (from true/false to false/true).

because that all varieties of loops, 3 an easy design rules:

1. Initialize: the loop-control variable need to be somehowinitialized before the loop 2. Test (for proceeding the loop) 3. Update: the loop-control variable need to be somehowupdated within the loop (to avoid boundless loops)

usage a respond to in the loop test. Style rules:

1. Initialize the counter prior to the loop 2. Test (for continuing the loop) 3. Update: the counter should it is in updated within the loop

The syntax because that a counter-controlled while loop looks like this (pseudocode):

int N = somevalue one of two people inputted by the user, or some stated value; intcounter = 0; //initialize while (counter //test declaration ... counter++; //update

instance 2: Discuss and also analyze the output. What need to be done to print the values in reverse order?

intcounter = 0; // initialize respond to while(counter // test System.out.print("\t"+ counter); // repeated activity counter++ ; //update counterSystem.out.println("\nDone");

instance 3:

int number = 1;

while (number System.out.print(number+ " "); number *= 2; }SAMPLE OUTPUT: 1 2 4 8 16 32 64 128

Example: The "temperature" trouble (with a counter-controlled loop)

// Counter-controlled loop import java.util.Scanner;

class Temp_Counter public static final int MAX = 10;

public static void main(String<> args) //Declarations Scanner input = brand-new Scanner(System.in); twin temp; double sum = 0; dual avg; int loopCount = 1; //initialize respond to while (loopCount //testcounter: specifically MAX iterations System.out.print("Enter a temperature: ");temp = input.nextDouble(); sum = sum + temp; loopCount = loopCount + 1;//update respond to avg = amount / MAX; System.out.println("\nTheaverage temperature is: " + avg);

SAMPLE OUTPUT: Enter a temperature:39 enter a temperature:56 enter a temperature:34 get in a temperature:56 enter a temperature:78 enter a temperature:67 enter a temperature:56 enter a temperature:78 get in a temperature:89 get in a temperature:59 The median temperature is:61.2

You might not know precisely how countless times a collection of statements needs to it is in executed, but you do recognize that the statements must be executed till a particular event take away place. In various other words, friend don"t understand the exact variety of iterations. Example 4: This loop will never be executed. Why?

.... charanswer; Scanner input = new Scanner(System.in);

while (answer == "Y") System.out.println("Hello, hello!"); System.out.print("Continue?(y/n): "); answer = input.next().charAt(0);

Example 5: This loop will certainly be executedforever. Why?

.... charanswer; prize = "y"; if (answer == "y") System.out.println("Hello,hello!");

Note:Pay attention when experimentation for equality!

while(ans= "y") // wrong! Don"t use =, but == while(ans== "y"); // wrong! Don"t use ;after whilewhile((ans =="Y") && (ans =="y")) // wrong! Can"t it is in both while((ans =="Y") || (ans =="y")) // CORRECT

just how it works: you review the first item before entering the when statement. If this item does no equal the sentinel, the human body of the if statement executes. The if loop continues to execute as long as the program has not read the sentinel. Style rules: The syntax for a sentinel-controlled while loop looks favor this (pseudocode):

Priming read: input an initial data iteminto variable; //initialize sentinel

while(variable != sentinel) //test sentinel statements ... ... following read: intake a data article intovariable; //update sentinel

example 6:

while(temp != 999) //incorrect, tempwas not initialized System.out.print("Entera temperature(999 come stop) "; temp = input.nextDouble(); amount = amount + temp; ... ...

instance 7:

System.out.print("Entera temperature(999 to stop) "; temp = input.nextDouble(); // CORRECT, priming read before loop while(temp != 999) //testsentinel System.out.print("Entera temperature (999 to stop) "; temp = input.nextDouble();//incorrect, following read have to be at the end of the loop sum = sum + temp; ... ...

example 8:

System.out.print("Entera temperature(999 to stop) "; temp = input.nextDouble(); // CORRECT, priming read before loop while(temp != 999) //testsentinel ... ... sum = sum + temp; ... ... System.out.print("Entera temperature(999 to stop) "; temp = input.nextDouble();//CORRECT, next read at the finish of the loop

Example: The "temperature" difficulty (with a sentinel-controlled loop)

//Sentinel-controlled loopimport java.util.Scanner;

classTemp_Sentinel_2 public static final int SENTINEL = 999; public static void main(String<> args) //Declarations Scanner entry = new Scanner(System.in); dual temp; double sum = 0; dual avg; int count = 0; System.out.print("Enter a temperature(" +SENTINEL + " to stop): "); temp = input.nextDouble(); //primingread while (temp != SENTINEL) //testsentinel sum = amount + temp; count = counting + 1; System.out.print("Enter a temperature(" +SENTINEL + " to stop): "); temp = input.nextDouble(); //nextread if(count != 0) avg = amount / count; System.out.printf("\nTheaverage temperature is: %6.2f", avg); System.out.println(); rather System.out.println("ERROR! NO input, NOoutput!!!");

SAMPLE OUTPUT: FIRST RUN:Enter a temperature(999 come stop): 999 ERROR! NO input, NOoutput!!! 2nd RUN:Enter a temperature(999to stop): 87 get in atemperature(999 come stop): 86 enter atemperature(999 come stop): 79 get in atemperature(999 to stop): 58 get in atemperature(999 come stop): 69 enter atemperature(999 to stop): 94 go into atemperature(999 come stop): 87 get in atemperature(999 come stop): 91 enter atemperature(999 come stop): 999 The averagetemperature is: 81.38

style rules:

1. Initialize a flag (to true or false). Make certain that you use ameaningful name for the flag 2. Test the flag in the loop test expression. 3. Update: A condition in the loop body alters the worth of the flag(to falseor true)

The syntax for this loop deserve to be comparable to the following (pseudocode):

booleanfound = false; while(!found) ... ... if(expression) found = true; ...

The "temperature" problem (with a flag-controlled loop):

//Flag-controlled loopimport java.util.Scanner;

classTemp_Flag public static void main(String<> args) //Declarations Scanner input = brand-new Scanner(System.in); double temp; double sum = 0; double avg; int counting = 0; boolean isSafe = true; //initialize flag if (isSafe) //testflag System.out.print("Enter a temperature(>= 200to stop): "); temp = input.nextDouble(); if (temp >= 200) isSafe = false; //updateflag else sum = sum + temp; counting = counting + 1; if(count != 0) avg = sum / count; System.out.printf("\nTheaverage temperature is: %6.2f", avg); System.out.println(); rather System.out.println("ERROR! NO input, NOoutput!!!");

SAMPLE OUTPUT: FIRST RUN:Enter a temperature(>= 200 come stop): 999 ERROR! NO input, NOoutput!!! 2nd RUN:Enter a temperature(>= 200 come stop): 78 get in atemperature(>= 200 to stop): 89 enter atemperature(>= 200 come stop): 80 get in atemperature(>= 200 to stop): 77 get in atemperature(>= 200 to stop): 67 go into atemperature(>= 200 to stop): 85 go into atemperature(>= 200 come stop): 333 The averagetemperature is: 79.33

instance 9: Sum all positive integers input from user; stop when a an unfavorable value is entered.

// Flag-controlled loop

importjava.util.Scanner;

classFlag_Negative public revolution void main(String<> args) //Declarations Scanner intake = brand-new Scanner(System.in); boolean nonNegative;int sum = 0; int number; nonNegative = true; //initializeflag if (nonNegative) //testflag: default test done for true System.out.print("Enter a number(negative tostop) "); number = input.nextInt(); if (number //test the condition tochange the flag nonNegative = false; //(reset)updateflag else amount = sum + number; System.out.println("\nThesum that all positive #s is: " + sum);

SAMPLE OUTPUT: FIRST RUN:Enter a number(negative to stop) -1 The sum of allpositive #s is: 0 second RUN:Enter anumber(negative come stop) 1 go into anumber(negative come stop) 2 get in anumber(negative come stop) 3 go into anumber(negative to stop) 4 go into anumber(negative to stop) 5 get in a number(negativeto stop) -1 The sum of allpositive #s is: 15

a) Counting every data values: counting the variety of iterations in a loop byusing one iteration counter (a respond to variable the is incremented with each iteration). Note: the loop control variableof a counter-controlled loop is an iteration counter. However, not alliteration counters space loop regulate variables (See the instance with the averagetemperature). b) Counting distinct data values. Example: the amount of all odd (or even)numbers in a succession of random numbers; the number of positive (or negative)numbers in a sequence of arbitrarily numbers, etc. An occasion control has to be used. c) Summing data values: you need an accumulator. Example:

Counter-controlled loop

Sentinel-controlled loop

import java.util.Scanner; class Loop_Counter public static void main(String<> args) //Declarations Scanner input = brand-new Scanner(System.in); int number, how_many; int amount = 0; int counting = 1; // initialize counter System.out.print("How plenty of numbers in input? "); how_many = input.nextInt(); while(how_many //validate intake System.out.print("\nERROR! have to be positive. Reenter: "); how_many = input.nextInt(); when (count how_many) //test counter number = input.nextInt(); // input a worth amount = sum + number; // update amount count++; // increment counter System.out.println("Sum = " + sum); } SAMPLE OUTPUT: How plenty of numbers in input? 5 1 2 3 4 5 sum = 15

import java.util.Scanner; class Loop_YesNo public static void main(String<> args) //Declarations Scanner entry = brand-new Scanner(System.in); int number; int amount = 0; char ans; System.out.print("Input values and also get the sum?(Y/N): "); ans = input.next().charAt(0); // priming read if (ans == "Y" SAMPLE OUTPUT: an initial RUN: intake values and also get the sum?(Y/N): n sum = 0 2nd RUN: intake values and also get the sum?(Y/N): y go into a number: 1 execute you desire to continue? (Y/N): )y enter a number: 2 do you want to continue? (Y/N): )y enter a number: 3 carry out you desire to continue? (Y/N): )y enter a number: 4 carry out you want to continue? (Y/N): )n amount = 10

Example 10: Count and sum the an initial ten oddnumbers in a data set.

import java.util.Scanner;

class FirstTenOdd public static final int MAX = 10; public revolution void main(String<> args) Scanner intake = new Scanner(System.in); int amount = 0; int count = 0; boolean flag = true; //initialize flag int number;

while (flag) // check flag number = input.nextInt(); if (number % 2 == 1) // test because that odd number count++; if (count sum = sum + number; rather flag = false; // upgrade flag System.out.println("The amount of very first " +MAX + " odd numbers is: " + sum);

d)Keeping monitor of a previous and current value: as soon as you have to remember the previous worth of a variable.

4. Just how toDesign Loops

(Checklist) Points to be taken into consideration when making a loop:

1. What is the condition that end the loop? 2. Just how should the condition be initialized? 3. How should the condition be updated? 4. What is the procedure being repeated? 5. How should the procedure be initialized? 6. How should the procedure be updated? 7. What is the state of the program when exiting the loop?

Where:

1 - 3 = making theflow control 4 - 6 = handling within the loop 7 = the loop exit

designing the circulation Control

1. Counter-Controlled Loops

Initialize the iteration counter to 0/1 (or part max value if relocating down). Increment (or decrement) the iteration counter at the finish of every iteration.

2. Sentinel-Controlled Loops

The priming read might be the only initialization necessary.

3. EOF-Controlled Loops

same initialization together in sentinel-controlled loops (open the file, carry out a priming read).

4. Flag-Controlled Loops

Initialize the flag change to true or false, together appropriate. Upgrade the flag change as soon as the condition changes. creating the process within the Loop The Loop Exit

5. Nested Loops

general pattern:

initializeouter loop while(outer loop condition) . . . initialize inside loop while(innerloop condition) . . . innerloop update external loop update . . .

each loop has actually its very own initialization, test, and update. To style a nested loop: begin with the external loop when you gain to wherein the inner loop appears, do it a different module and also come ago to its design later. Finally, for every loops, be extra cautious with these: Don"t usage the assignment operator (=) rather of = = operator prevent unintended null explanation (don"t use ; ~ while) Don"t failure to usage braces when compelled Don"t forget indentation! Indent only the human body of the loop, not the whole while statement. Avoid boundless loops (syntax or reasonable related)! Problem: publish the median blood push for different people. Every input has actually a patient ID, the number of readings for the patient, adhered to by the really blood push readings.

Sample input:

ID##Readings___ Actualreadings 45675 180140 153 170 130 23182170 215 52323150 151 145

Sample Output:

For patient ID#: 4567 averageBP = 154.60 for patient ID#: 2318 typical BP = 192.50 for patient ID#: 5232 median BP = 148.66 ... ... ... There to be 432 patients.

See more: What Is The Formula For Copper(Ii) Phosphate? ? What'S The Formula For Copper Ii Phosphate

The Algorithm:

1. Initialize patientCountto 0 2. Get very first patient identifier 3. While patient ID no 0 obtain how countless readings forthis patient

IncrementpatientCount use a count-controlled loop come read and sum up this patient’s howMany BP’s calculate typical for patient

Display ID and average because that patient

Getnext patient ID

4. DisplaypatientCount(how numerous patients)

The Java Program: import java.util.Scanner;

class clinical publicly static final int SENTINEL = 0;

public revolution void main(String<> args) //Declarations Scanner entry = new Scanner(System.in); int patientCount=0; // counter for the variety of patients int thisID; // patience ID int howMany; // how plenty of readings because that patient int thisBP; // existing blood press int totalForPatient;int count; // counter forinner loop dual average; // typical BP for patientSystem.out.print("Enter patience ID(" +SENTINEL + " to stop): "); thisID = input.nextInt(); // priming review for outer loop while(thisID != SENTINEL) //test sentinel (outer loop) System.out.print("How countless readings? ");howMany = input.nextInt();while(howMany //validateuser intake System.out.println("ERROR!!!Must bepositive!"); System.out.print(" How countless readings? ");howMany = input.nextInt(); patientCount++; totalForPatient = 0; counting = 0; // initialize within loop counterwhile (count howMany) //test counter (inner loop) System.out.print("Enter analysis for thispatient: "); thisBP = input.nextInt();count++; //update within loop respond to totalForPatient = totalForPatient+ thisBP; //close inside loop average = totalForPatient / (double)(howMany); System.out.printf("For patience ID#: " + thisID + " average BP = %6.2f", average); System.out.print("\nEnterpatient id (" + SENTINEL + " to stop): "); thisID = input.nextInt(); // following read for external loop //close external loop System.out.println(patientCount+ " patients have been tested.\n"); //close main() } //close class

SAMPLE OUTPUT: FIRSTRUN: Enter patience ID(0 to stop): 0 0 patients have beentested. Second RUN:Enter patient ID(0 come stop): 12345 How many readings? 2Enter reading for thispatient: 132 get in reading because that thispatient: 137 for patient ID#: 12345average BP = 134.50 get in patient ID(0 to stop): 12346 How countless readings? 3Enter analysis for thispatient: 144 go into reading because that thispatient: 147 go into reading for thispatient: 160 because that patient ID#: 12346average BP = 150.33 go into patient ID(0 to stop): 0 2 patients have actually beentested.

Program #1: Employee"s weekly salaries //*************************************************** // Payrollprogram // This routine computes each employee’s weekly salaries // and the total firm payroll // *************************************************** income java.util.Scanner;

class WeeklyWages public revolution final twin MAX_HOURS = 40.0; //Maximum normal hrs public static final double OVERTIME = 1.5; //Overtime pay variable public static last int SENTINEL = 0;

public static void main(String<> args) //Declarations Scanner intake = brand-new Scanner(System.in); twin payRate; // Employee’s salary ratedouble hours; //Hours worked double wages; //Wages earned int empNum; //Employee id number double total; //Total firm payroll complete = 0.0; System.out.print("Enter employee number:"); empNum = input.nextInt();// priming read while (empNum != SENTINEL) //test sentinel System.out.print("Enter salary rate: ");payRate = input.nextDouble();System.out.print("Enter hrs worked: ");hours = input.nextDouble(); if( hrs > MAX_HOURS) incomes = (MAX_HOURS * payRate ) + (hours - MAX_HOURS)* payRate * OVERTIME; else earnings = hours * payRate; System.out.println("This week earnings for theemployee through ID " + empNum + " room $"+ wages); complete = complete + wages; System.out.print("Enter employee number:"); empNum = input.nextInt();// following read System.out.println("\nTotalcompany payroll is: " + total);

SAMPLEOUTPUT: Enter employee number:12345 enter pay rate: 23.6Enter hours worked: 44This week earnings for the employeewith id 12345 space $1085.6 go into employee number:12346 enter pay rate: 32.7Enter hours worked: 60This week incomes forthe employee v ID 12346 space $2289.0 go into employee number:0 Total agency payrollis: 3374.6

Program#2: Display the very first 50 confident evenintegers 5 to a line.

import java.util.Scanner;class display publicstatic final int MAX_COUNT = 50;

public static void main(String<> args) int n = 1; //initialize while(n //test System.out.printf("%6d", n * 2); // if n is divisible by 5, calculation a line feed. If (n % 5 == 0 ) System.out.println(); n++; // update //close main() //close course

Exercises:

String example - use features length()and charAt(). What is the output?

import java.util.Scanner; class display screen public revolution void main(String<> args)//Declarations string name; int position = 0; Scanner input =new Scanner(System.in); System.out.print("Enter name: "); name = input.nextLine(); while(positionname.length()) System.out.println(name.charAt(position)); position++;

What is the output?

... Int border = 5;intj = 1; while(j if(j % 2 == 0) j++: }

System.out.println("j= " + j);

What is the output?

... Intm = 1; intn = 3; while(m m = m + 1; n = n + 2; }System.out.println("Thesum is " + (m + n));