2. Write a program to print the even
numbers from 2 to 20 using While
loop *
Your answer
estion
Answers
The following codes have been written using Python.
i = 2
while i <= 20:
if i%2 == 0:
print(i)
i = i + 1
There must be a condition for the while loop to keep iterating till the needed value. We assign 2 to 'i', since we need to start from 2, and give i <= 20 as the condition for the while loop to keep iterating. So as long as the value stored in 'i' is lesser than or equal to 20, it'll keep iterating.
After that, it checks 'i''s divisibility by 2. If it's divisible, it'll be printed. And then you increment 'i' by 1. So if 'i''s current value was 2, 2 + 1 = 3. The loop will the run with 'i''s value as 3. It'll keep running till 'i' becomes 20 and once it increments, i.e., when 'i' becomes 21, the i <= 20 condition will result to 'False' and it will stop running.
Answer:
//Java program to print the even numbers from 2 to 20
import java.util.Scanner;
public class EvePrint {
public static void main (String ar []) {
int i=2;
while(I<=20)
System.out.println(I);
I+=2;
}
}
#Python Program to print even numbers from 2 to 20
I=2
while(I<=20):
print(I)
I+=2
Qbasic program:
CLS
I=2
WHILE I<=20
PRINT I
I=I+2
WEND
END
Logic:-
- Run a loop from 2 to 20 with increment value 2
- print the loop value