When we actually need a loop in programming?
Ans:
When we perform a same procedure as a repititive process for several times.
At that time we actually need a loop to reduce our effort.
This is best way to think about loop for the given scenerio.
Steps to think for a loop:
Try to convert the given scenerio into any story.
Write down the actual output via programming with your know steps.
e.g, Print 5 numbers.
code:
print(1)
print(2)
print(3)
print(4)
print(5)
After writing the above type of code think like a intermediater between the lines of code and the computer. Try to make the process as repititive(if you need).
Introduce a new variable if only you think it is needed.
e.g, i think a variable can look like uniformly in tha above code.
so i introduce a variable,
no = 1
print(no)
print(no)
print(no)
print(no)
print(no)
the above code does not produce the correct answer but it form an uniform and repititive process.Now we need to convert the modified code into correct code.
In this case i need to add 1 on each line before printing the number.
For that I initialize the variable with 0.
no = 0
no = no +1
print(no) -> 1
no = no + 1
print(no) -> 2
no = no+1
print(no) -> 3
no = no+1
print(no) -> 4
no=no+1
print(no) -> 5
-- stop the program.Notice that we modify the code into an uniform repititive process and its output was correct, now its time to convert it to the loop.
First don't think about the condition. Make the inner body of the loop, we already know that right!
no=no+1
print(no)
This is the repititive code we already wrote.while ()
no=no+1
print(no)Try to find the condition to stop the loop from the above code.
In this case when you look carefully we print the numbers untill 5 or the no becomes 5.
so this is the condition we need to give in loop.
We are able to find the condition easily in this case, all the case are not like this, but all case have anyone condition, that condition is also found in your preparation, try to find it.-
After finding the condition, code the loop.
while(no<=5){
no=no+1
print(no)
}