This is an example of an infinite while loop in C. The condition inside the parenthesis, in this case true
, will always evaluate to true, causing the code inside the loop to run indefinitely. Make sure to include a way to break out of the loop or it will never end.
1 2 3 4 5 | while (true) { // code to be executed } |
Here’s some code that will print out the numbers from 1 to 1000 using a while
loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Initialize the counter variable counter = 1 # Start the while loop while counter <= 1000: # Print the counter variable print(counter) # Increment the counter variable counter += 1 # Print a message after the loop is finished print("Done!") |
This code will print out the numbers 1 through 1000, each on a separate line, and then print the message “Done!” once the loop has completed.
Here is an example of a while loop that will run for a certain number of iterations:
1 2 3 4 5 6 7 8 9 | int i = 0; int maxIterations = 10; while (i < maxIterations) { // code to be executed i++; } |
In this example, the loop will run as long as the variable i
is less than maxIterations
. The i++
at the end of the loop increments i
by 1, allowing the loop to eventually exit when i
is no longer less than maxIterations
.
Another example, with a condition:
1 2 3 4 5 | while (condition) { // code to be executed } |
In this example, the code inside the loop will be executed as long as the condition
is true.
1 2 3 4 5 6 | while (x < 10) { printf("%d", x); x++; } |
More examples: Python Examples
This loop will execute as long as the value of x
is less than 10, printing the current value of x
each time through the loop and incrementing the value of x
by 1 with each iteration. Once the value of x
is no longer less than 10, the loop will exit and the program will continue with any code that follows the loop.