Arrays & Stringseasy
8 views

JAVA – Package – EvenPrinter

Print all even numbers in a given range using a custom class

Understand the Problem

Problem Statement

The class Hello.java is given below.

import java.util.Scanner;
import com.letuscrack.util.EvenPrinter;
public class Hello {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int from = scan.nextInt();
        int to = scan.nextInt();
        EvenPrinter.printEvenRange(from, to);
    }
}

Write the code for the class EvenPrinter.java in the package com.letuscrack.util so that the program prints all even numbers in the given range (inclusive) separated by spaces.

Constraints

  • 1 ≤ from ≤ to ≤ 1000
  • Both from and to are integers
  • The EvenPrinter class must be in the package com.letuscrack.util
  • The method printEvenRange must be static and public

Examples

Example 1
Input
5 10
Output
6 8 10
Explanation

The range is 5 to 10. The even numbers in this range are 6, 8, and 10.

Example 2
Input
12 24
Output
12 14 16 18 20 22 24
Explanation

The range is 12 to 24. All even numbers from 12 to 24 inclusive are printed.

Example 3
Input
1 5
Output
2 4
Explanation

The range is 1 to 5. The even numbers in this range are 2 and 4.

Solution

#include <stdio.h>

// Simulating the EvenPrinter functionality in C
void printEvenRange(int from, int to) {
    for (int i = from; i <= to; i++) {
        if (i % 2 == 0) {
            printf("%d ", i);
        }
    }
}

int main() {
    int from, to;
    scanf("%d %d", &from, &to);
    printEvenRange(from, to);
    return 0;
}
Time:O(n) where n is the size of the range (to - from + 1)
Space:O(1) - only using a constant amount of extra space
Approach:

The C solution creates a function printEvenRange that iterates from from to to. For each number, it checks if it's divisible by 2 using the modulo operator. If the remainder is 0, the number is even and gets printed with a space separator.

Visual Explanation

Loading diagram...