A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.
"Hi."
"Hi, Ellie!"
"It's time to learn about loops. Loops are as simple as if/else statements, but even more interesting. You can use a loop to execute any command or a block of commands multiple times. In general, a loop looks like this:"
while(boolean condition)
command;
while(boolean condition)
block of commands in curly brackets
"It's all very simple. A command or block is executed again and again as long as the loop condition is true. First, the condition is checked. If the condition is true, the loop body (block of commands) is executed. The condition is checked again. If the condition is true, the loop body is executed again. This repeats until the condition ceases to be true."
"What if it is always true or always false?"
"If it is always true, then the program will never stop running: it will repeat the loop indefinitely. If it's always false, then the loop body will never be executed."
Here are some examples:
Java code | Description |
---|---|
|
3 2 1 0 |
|
0 1 2 |
|
The program will print strings from the keyboard until the string 'exit' is input. |
|
The program will repeatedly display the letter C on screen. |
|
The program will read strings from the keyboard until the string 'exit' is input. |
"After conditional statements, this doesn't seem complicated. I already want to try it."