Java Program to Print Even Numbers from 2 to 20 Explained with Efficient For-Loop Logic

preview_player
Показать описание
Step-by-Step Explanation:

Choose the range and step size:
We want to print even numbers starting from 2 up to 20. Since even numbers increase by 2, we initialize the loop counter i at 2 and increment by 2 each iteration.

Set up the for-loop:
The loop starts with int i = 2, runs while i -= 20, and increments by 2 (i += 2) each time, effectively jumping over all odd numbers.

Print each even number:

Logic Summary:

The loop only iterates through even numbers, making it efficient.

This method avoids checking each number with % (modulus) operator, which is useful for performance.

The loop runs exactly (20 / 2) = 10 times.

Related Interview Questions:

What is the difference between for, while, and do-while loops?
For is best when iteration count is known, while is condition-based, and do-while executes the loop body at least once.

How can you print even or odd numbers without using the modulo operator %?
By incrementing the counter in steps of 2 starting from the first even or odd number.

What is the time complexity of this loop?
O(n/2) which simplifies to O(n), where n is the upper limit.

How would you modify the loop to print even numbers in reverse from 20 to 2?
Initialize i = 20, run while i -= 2, decrement by 2 (i -= 2).

Can you write this logic using a while or do-while loop?
Yes, by initializing a counter before the loop and updating it inside.

How would you print even numbers between two user-given inputs?
Accept inputs, then loop from the lower to the higher input, adjusting the start to the nearest even number.

Complete Java Code:

java

public class PrintEvenNumbers {
public static void main(String[] args) {
// Loop from 2 to 20, stepping by 2 to print only even numbers
for (int i = 2; i -= 20; i += 2) {
}
}
}
Hashtags:
#Java,#ForLoop,#EvenNumbers,#ProgrammingBasics,#CodingInterview,#JavaProgramming,#Looping,#CodingTips,#AutomationTesting,#SoftwareTesting,#DeveloperTips
Рекомендации по теме
join shbcf.ru