import java.util.Scanner;
public class PrintEvenNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = sc.nextInt();
System.out.println("Even numbers from 1 to " + n + " are:");
for(int i=1;i<=n;i++){
if(i%2==0){
System.out.print(i + " ");
}
}
System.out.println();
System.out.println("Even numbers from 1 to 100 are:");
for(int i=1;i<=100;i++){
if(i%2==0){
System.out.print(i + " ");
}
}
}
}
Enter the value of n: 25
Even numbers from 1 to 25 are:
2 4 6 8 10 12 14 16 18 20 22 24
Even numbers from 1 to 100 are:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
n
from the user using the Scanner
class. We then use a for
loop to iterate from 1
to n
, and check if each number is even using the modulo operator (%
). If a number is even, we print it using the System.out.print()
method.for
loop to print even numbers from 1
to 100
. We follow the same logic as before to check if a number is even or not, and print it if it is.