Category: Control
Executes a block of statements while the specified condition is true.
Apps sometimes need to repeatedly execute some code while something is true. The while loop uses a boolean condition to repeatedly run a block of code. It will check the expression, and if it is true it runs the block of code contained within the curly braces. This process of checking the condition and running the block of code is repeated as long as the boolean condition remains true. Once the boolean expression becomes false it will stop.
A while block requires you to define an expression that evaluates to true or false. Just as in arithmetic there are some operators you can use to write expressions that evaluate to a number, programming languages also have a comparison operators (< <= == > >= !=) and boolean operators (&& || !) that let you write expressions that evaluate to true or false.
// Keep rolling a die while you do not roll a 6. (event-controlled loop) var die=randomNumber(1,6); while (die !=6) { write(die); die=randomNumber(1,6); } write(die); |
// Roll a die 5 times. (counter-controlled loop) var count=1; while (count<=5) { write(randomNumber(1,6)); count=count+1; }
Example: Prompt and Loop Prompt the user for exam scores and find the average.
// Prompt the user for exam scores and find the average. var examGrade = promptNum("Enter an exam score from 0 to 100:"); var sum=0; var count=0; while (examGrade>=0 && examGrade<=100) { sum=sum+examGrade; count=count+1; examGrade = promptNum("Enter an exam score from 0 to 100:"); } if (count>0) { write("Average="+(sum/count)); } else { write("No valid exam scores entered"); }
while (condition) { statement }
Name | Type | Required? | Description |
---|---|---|---|
condition | boolean expression | Yes | An expression that evaluates to true or false. Comparison operators include < <= == > >= !=. Boolean operators include && |
statement | App Lab statement(s) | Yes | Any valid App Lab statements. |
No return value.
Found a bug in the documentation? Let us know at documentation@code.org
while( ){ // code }
Found a bug in the documentation? Let us know at documentation@code.org