Skip to main content

Command Palette

Search for a command to run...

Java Program : Print even numbers using for loop

Published
1 min readView as Markdown
Java Program : Print even numbers using for loop

Example

Input
6
Output
2 4

Required to know

Use of Variables, Use of different operators like assignment or arithmetic operators, Use of methods like System. out. print(), and use for loop, and Use of Data types.

Steps

  • Take range as input from the user.

  • Run the loop by providing a condition that it will go on printing values until it is greater than the range. Now inside the loop provide a condition that will segregate out the even numbers and print it.

Program

Case 1: - In this case we have used if condition for printing the even numbers

import java.util.Scanner; 
public class Mavenproject1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        int n; 
        System.out.print("Enter the number"); 
        n = sc.nextInt(); 
        for(int i=1;i<=n;i++){
            if(i%2==0)
            System.out.print(i+ " "); 
    }

    }
}

Case 2: In this case, we will only be using the for loop to print the even numbers.

import java.util.Scanner; 
public class Mavenproject1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        int n; 
        System.out.print("Enter the number"); 
        n = sc.nextInt(); 
        for(int i=2;i<=n;i=i+2){
            System.out.print(i+ " "); 
    }

    }
}

More from this blog

TheCodingcoder

60 posts

Empowering the coding community by simplifying complex tasks.