i don't understand what "while" and "until" loops are and what they do. I passed the lesson by basically copying the lesson showing what to do, but i'm completely confused as to what this is.
I passed the lesson by basically copying the lesson showing what to do
That's your problem. Before moving on to another concept, it's critical to understand the one presented.
until are keywords, they're used to repeat a code a certain number of times. The loops stop when a certain condition is met.
while will keep doing the code as long as a condition is true/false, and
until will keep doing the code until () a condition is true/false.
For example, if you want to print "Hello" 5 times, you could do:
i = 0 while (i < 5) puts "Hello" i += 1 end
i think i get the concept, but i dont understand why you do "i=0" and "while (i<5)" and "1+=1" and all that..
Well then you don't really understand the concept then. You might think you understand it, but if you're not able to explain it (even only to yourself), then you don't understand it.
The idea is to be able to repeat code. Of course we don't want to repeat the code indefinitely, we want to be able to choose how many times to repeat it.
That's why we need to use a limit, a condition (in my example, the limit will be based on the value of an integer, the variable
i, but you can use any condition you want).
First we initialize our
i to 0 OUTSIDE of the loop (so that we know where we start from):
i = 0
Then we set the condition INSIDE the loop (so that we know when to stop):
while (i < 5)
Then we increment our
i value INSIDE the loop so that we can reach the condition at least once (otherwise we would have an infinite loop):
i += 1
Of course we also add the action we want to repeat INSIDE the loop, otherwise our loop is pointless:
i=0 is basically the first condition set .There after the next instruction "while (i<5)" means as long as "i" is less than 5 we will print our message "Hello".But this would go on forever as i=0 which is definately less than five and will stay that way unless we change it.So to avoid this we must give a condition that will stop the code from running at some point.This is done by increasing "i" by one each time which is represented as i += 1 ..Ps "i was set to zero(i=0)".When "i" is increased plus one until its more than five the code stops running.