views
Learn how a while loop works. No matter which language you're using, a while loop always runs like this: The program executes. A while loop is found in the program. The condition specified in the while loop is evaluated to check whether it is true or false. If the condition is true, the statements in the loop are executed. The condition is checked again once the statements in the loop have run. If the condition remains true, the loop will run again. The process repeats until the condition becomes false. When the condition becomes false, the statements in the loop stop running. When loop ends, the next lines in the program will run.
See the syntax for while loops in different languages. While a while loop works the same in all programming language, the syntax varies. C and C++ while(condition) { statement(s); } Java while (condition) { statement(s) } Python while condition: statement(s) Ruby while condition statement(s) end
Identify your variable(s). For example, if your variable i is the value that should control how long the loop lasts, define i as a whole number or similar data type.
Start the while loop by writing a while command. Use the syntax examples above to ensure that you're entering the command in the proper format for the language you're coding in. Replace condition with the condition to check for the variable you're evaluating. You can specify more than one conditional expression in a while loop.
Enter the code that should run inside the while loop. Replace statement(s) in the code with the code that should run if the condition is true. As long as the conditions are true, the statements will run repeatedly. Once the condition tests false, the while loop will end on its own.
Add an else clause in Python (optional). If you're coding in Python, you can opt to add additional statements that can run as soon as the loop ends. This can be helpful if you want to print a message of success (or failure) to the screen after the commands are run. In this example, we'll use an else statement to print "All done" to the screen after the loop finishes. i = 0 while i > 0: i -= 1 print(i) else: print("All done")
Comments
0 comment