Thursday, October 4, 2018

How while loop works

This question focus on the understanding regarding the principle of while loop.

while loop is repeating the step under it until you cannot fulfill the condition

Python code 
inputNo = 10
i = 1
while (i <= inputNo):
    outputFile.write(str(i) + '\n')
    i = i + 1

Example
inputNo = 10 : Assign/set 10 to inputNo (inputNo is the name that store value 10)
i = 1 : Assign / set 1 to i (i is the name that store value 1)
while (i <= inputNo): 
means that while you can fulfill the condition in the brackets , that's mean you can find i that is smaller or equal to the inputNo

now i = 1, which is smaller or equal to 10
so do the actions under it 

write i to outputFile ('\n' means enter to the next line)
then i = i + 1 : means we add 1 to i, i is become 2 now

Again while (i <= inputNo): now i = 2 which is smaller than 10
then write 2 to output file
i = 2 + 1 = 3

Now i = 3, i is smaller than 10
write 3 to output file
i = 3 + 1 = 4

Now i = 4, i is smaller than 10
write 4 to output file
i = 4 + 1 = 5


...... (repeat the step)

Now i = 8, i is smaller than 10
write 8 to output file
i = 8 + 1 = 9

Now i = 9, i is smaller than 10
write 9 to output file
i = 9 + 1 = 10 

Now i = 10, i is equal to 10, fulfill the condition too
write 10 to output file
i = 10 + 1 = 11

Now i = 11, i is not smaller than 10, i is not equal to 10
we cannot fulfill the condition.
So, break the loop. We will exit the loop which means we will not repeat the action under the loop.


Counting question

No comments:

Post a Comment

Superior of partial fraction

What is complex fraction? Complex fraction is a fraction whereby its numerator or denominator or both consists of fractions. Partial frac...