Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




RUBY - WHILE LOOP


While Loop is one kind loop used by Ruby. Let us see it in the below example to print the numbers from 1 to 10.


Example of while loop with while statement at the beginning of block:


Example :



num = 1;
while num <= 10 do 
		
	puts num;
	num = num + 1;
end



So, we are telling Ruby to print the numbers from 1 to 10.


Firstly, we are asking Ruby to store the number 1 to a variable num.


num = 1;

Then we are using the while loop.


while num <= 10 do

	puts num;
	num = num + 1;
end

The above condition says, continue to be in the loop until the value of num is less than or equal to 10 (i.e. num<=10).


And inside the loop, we will increase the value of num by 1 every time it enters the loop.


Example :

It is same as, you go on putting 1 cup of water in a container until it gets overflowed.

Code explanation in detail:


num = 1;
while num <= 10 do

	puts num;
	num = num + 1;
end
  1. The initial value of num is 1.

    int num = 1;

  2. When it comes to while num <= 10 do line, it finds 1 is less than 10.

  3. So, it gets inside the loop,

  4. And finds the line puts num;. So, it prints 1(Since, num is holding the value 1).

  5. In the next line we are adding 1 to num.

    num = num + 1; i.e. 1 is added to num.


    So the new value of num is 2.

  6. Then it reaches the end statement and since it is a loop, it is sent to the

    while num <= 10 do


    statement again. Where it checks if num<=10.

  7. Off course 2 is less than 10. So it gets inside the loop again. Comes to puts num; which prints 2.

  8. Then it comes in the next line

    num = num + 1;


    So the current value of num becomes 3.

  9. And the same thing continues again and again until the value of num is less than or equal to 100.

  10. So, when the value of num is 11, it comes out of the loop.

Note : 'num = num + 1;' can also be written as 'num+=1'

Example of 'while' loop with 'while' statement at the end of block:


This is the other way of writing the while loop where the while statement is written at the end of the loop block.


This loop will execute the code block at least once, because it gets into the loop first, executes the block inside the loop. Then it checks for the conditional part i.e. while num<=10.


Example :



num = 1;
begin

	puts num;
	num = num + 1;
end while num<=10



In this while loop there is no conditional statement in beginning of the loop. So it gets into the code block.


begin
	puts num;
	num = num + 1;
end while num<=10

Finally, after executing the block inside the loop, it comes to the conditional part of the loop.