DEV Community

Control/Lopping Statement : For loop and While loop

Loops are programming constructs used to repeatedly execute a block of code. A while loop continues to execute its code block as long as a specified condition remains true. The condition is checked before each iteration, and if it is false, the loop terminates. For instance, a while loop can print numbers from one to five by incrementing a counter until it exceeds five. A for loop is typically used when the number of iterations is known in advance. It consists of an initialization, a condition, and an update expression. The initialization happens once, and then the condition is checked. If true, the loop body executes, followed by the update expression. This cycle repeats until the condition becomes false. A for loop can also achieve the same result of printing numbers one to five. The choice between for and while loops often depends on whether the iteration count is fixed or dependent on a condition. While loops are more suitable for conditions that are not tied to a specific number of repetitions. For loops offer a concise structure when the iteration count is predetermined. Both loop types can be adapted to handle conditional execution, though their syntax differs. You can use a while loop to repeatedly ask for user input until valid input is provided. Similarly, a for loop can be structured to achieve the same input validation behavior.
favicon
dev.to
dev.to
Image for the article: Control/Lopping Statement : For loop and While loop
Create attached notes ...