98.2k views
5 votes
Given positive integer n, write a for loop that outputs the even numbers from n down to 0. If n is odd, start with the next lower even number.

User Pkumarn
by
4.7k points

1 Answer

2 votes

Answer:

if(n % 2 == 0){

for(int i = n; i >= 0; i-=2){

System.out.println(i);

}

}

else{

for(int i = n - 1; i >= 0; i-=2){

System.out.println(i);

}

}

Sample output

Output when n = 12

12

10

8

6

4

2

0

Output when n = 21

20

18

16

14

12

10

8

6

4

2

0

Step-by-step explanation:

The above code is written in Java.

The if block checks if n is even by finding the modulus/remainder of n with 2. If the remainder is 0, then n is even. If n is even, then the for loop starts at i = n. At each cycle of the loop, the value of i is reduced by 2 and the value is outputted to the console.

If n is odd, then the else block is executed. In this case, the for loop starts at i = n - 1 which is the next lower even number. At each cycle of the loop, the value of i is reduced by 2 and the value is outputted to the console.

Sample outputs for given values of n have been provided above.

User Oleksiy Syvokon
by
4.4k points