![]() |
VOOZH | about |
In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines.
It consists of a block of code and a condition. First of all the condition is evaluated and if it is true then execute the code within the block. It repeats until the condition becomes false because every time the condition is checked before entering into the block. The while loop can be thought of as repeating of if statements.
while(condition) {
// code to run
}
In the program below, we print the numbers using a while loop.
Example:
Output:
1
2
3
4
5
6
7
8
9
10
In the below program, we create an array(names) and initialize it with different numbers of strings, and also initialize a variable index to 0. The size of an array can be calculated by using arrayName.size. Put the condition (index < names.size) in the while loop.
If index value less than or equal to array size then it enters into the block and print the name stored at the respective index and also increment the index value after each iteration. This repeats until the condition becomes false.
Example:
Output:
Praveen
Gaurav
Akash
Sidhant
Abhi
Mayank