This is the traditional method of looping that executes a sequence of statements multiple times and abbreviates the code that manages the Loop variables.The syntax of For loop consists of initializer, condition, and loop expression. Initializer initializes a variable; the Loop expression increments or decrements the value of the variable; and the condition refers to a condition specified in the loop.
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables.
The condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the loop expression statement. This statement allows you to update any loop control variables.
For -in loop
The for-in loop iterates over collections of items, such as ranges of numbers, items in an array, or characters in a string. The working of for-in loop is similar to for loop. The statements in for-in loop continue to execute for each element in a collection. After iterating each elements in collection, the control transfers to next block of code.
Syntax
- for index in var {
- statement(s)
- }
While
We can use while loop to execute a statement until specified condition evaluates to false. The best scenario to use while loop is when we don’t know how many times the loop should be executed. If the Condition in While loop is true, then the statements inside while loop are executed. Otherwise the statements are not executed.
Syntax
- while condition {
- statement(s)
- }
do… while
The function of do…while loop is similar to the while loop. The main difference in do..while loop is that the condition is checked at the end of the loop. This means the loop executes at least once even if the condition is false.
Syntax
- do {
- statement(s);
- }while( condition );
Conclusion
In this article we learned about looping statements, I hope it was helpful. In my next article, we will see Arrays and accessing Array elements using Looping Statements and Conditional Statement.