[course03] 02 While Loops
The Basic While Loop
A while loop is used to repeat a given statement over and over. Of course, it's not likely that you would want to keep repeating it forever. That would be an infinite loop, which is generally a bad thing
while (boolean-expression)
statement
// with block
while (boolean-expression) {
statements
}
When the computer comes to a while statement, it evaluates the boolean-expression, which yields either true or false as its value. If the value is false, the computer skips over the rest of the while loop and proceeds to the next command in the program. If the value of the expression is true, the computer executes the statement or block of statements inside the loop.
example : a while loop that simply prints out the numbers 1, 2, 3, 4, 5
The do...while Statement
example:
do while and while do
Use a do-while if you must execute the body of the loop at least once.
break and continue
When the computer executes a break statement in a loop, it will immediately jump out of the loop.
The continue statement is related to break, but less commonly used. A continue statement tells the computer to skip the rest of the current iteration of the loop. However, instead of jumping out of the loop altogether, it jumps back to the beginning of the loop and continues with the next iteration
example
CalculateNumberSum
Prime Number
Number 4 or 7
find the nth number that is a multiple of either 4 or 7
find the nth number that is a
Last updated
Was this helpful?