Rewrite following code fragment using while loop
(a)
for i in range(5):
print(i)
(b)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
(c)
for x in range(10):
if x % 2 == 0:
continue
print(x)
(python)
Answers
Question:-
➡ Rewrite the following code using while loop.
Solution to question 1:-
Given code,
for i in range(5):
print(i)
Using while loop, the code will be,
i=0
while (i<5):
print(i)
i=i+1
Solution to question 2:-
Given code,
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
Using while loop, we can write like this,
num=2
while(num<10):
if(num%2==0):
print("Found an even number",num)
continue
print("Found a number", num)
num=num+1
Solution to question 3:-
Given code,
for x in range(10):
if x % 2 == 0:
continue
print(x)
Using while loop, we can write in this way,
x=0
while (x<10):
if (x%2==0):
continue
print(x)
x=x+1
Remember to increment the values of i, num and x in these three questions otherwise the loop will not terminate.(infinity loop).