Loops are used to execute set of statements repeatedly based on a condition. It is sometimes necessary to execute set of statements again and again. For example, checking whether number in an array are prime or not.
While loop is used to execute a block or segment of code repeatedly until the condition becomes false.
Syntax of While loop:
while (condition) statements end
First the condition is checked, if it is true the statements inside
while block is repeatedly. At the end of each iteration the condition is checked again. When the condition is found to be false,
while loop terminates.
Consider the below example that prints "Hello, World" 5 times.
Let's check its output now
Oh, Wait! What's this? It should have printed "Hello, World" only 5 times. But what happened?
The variable count is initialized with the value 1 and the loop will terminate when count becomes 5. But inside the while loop, there is no statement that increments the value of count. Since the condition never becomes false it won't terminate. This is called
Now, in this code you could see that the value of count is incremented by 1. So, every time the loop is executed the value of count is incremented and if the value of count becomes 6, the condition fails and comes out of the loop. Now, let's see the output.
Well, that's our expected output. After the condition fails, it comes out of
while block and executes the next statement followed by
The next program prints the sum of first ten numbers.
Until loop is very similar to
The only difference between while loop and until loop is that while loop executes set of statements repeatedly until the condition becomes false and until loop executes set of statements repeatedly until the condition becomes true.
Until is vice versa of
Syntax of While loop:
until (condition) statements end
The condition is checked, if it false it executes the statements inside
until block, when the condition becomes true, it comes out of the loop.
The loop executes until count becomes 6. When count becomes 6, the condition will be true and exits the loop. The output of the program is :
Program to print the sum of first 10 numbers
The output of the above program is :
Each Iterator is used to iterate over an array
It pulls out each element of a container or an array and assigns to the variable x. Using the value of the variable x, we can do our desired operation.
It's just like
unless loop to execute set of statements repeatedly. Using this we can also iterate through containers.
In this code, it pulls out each element of the array nums and storing it in a single element(variable) num. Then using that value, we can do the required operation. The output of the above code is :
To sum 10 numbers using for in loop:
And its output is :