0
While loops
Sorry new at all this. I am not getting the while loop statement. How would you output only even numbers and how does each line correspond together? Thanks
3 odpowiedzi
+ 2
All you need to set a condition to while statement and increase your initial variable by 2 inside the loop.
+ 1
While loops are much easier than you think. It simply keeps iterating the loop(executing the code), as long as the condition is TRUE, once the condition is FALSE, It will stop the loop.
Example:
I want to create a loop for printing even numbers from 1 to 20.
-First: I need to create a counter for iteration =====》 counter = 1
-Second: I need to specify the condition for iteration =====》 counter <= 20
-Third: I need to create an if statements to examine the even numbers using the remainder operation on 2, if the result is zero, then It,s even number =====》 if( counter % 2 == 0) then print(counter), otherwise do nothing and continue the loop.
-Forth: To keep the loop iterating until we reach 20, we increment counter by 1 ====》counter = counter + 1
Sample code:
counter = 1
while (counter <= 20):
if (counter % 2 == 0)
print(counter)
counter = counter + 1
+ 1
Thank so much! Create break down .