Different types of Loops are used to execute different part of the code in different logics and conditions. Some time loops are recursively use part of a code for a number of times with conditional checking. We will learn different types of loops and their uses in this section.
We can print number 1 to 10 by using for loop.
In the above code we have added one line break after each step of printing of number so the numbers will be displayed vertically. Now let us try to display numbers starting from 10 to 0
In the first example x value is increased by 1 starting from 1 and in second example x value is decreased by 1 starting from 10
Using break to come out of loopWe can come out of the loop by using break statement inside the loop. Let us use one if condition to break the loop once x value reaches 5 . Here is the code with break statement.
The above code will display number 1 to 6 vertically. You can see once the value of x reaches 6 the if condition returns true and breaks the for loop.
Using step value higher than 1If we want to use incremental value higher than 1 , then we can use step value. Here is the sample code with step value ( incremental value ) of 5
This article is written by plus2net.com team.
|More on Loops and Variables|