Write a Java-program to display Even Number or Odd Number based on the N value using for loop

Write a Java-program to display Even Number or Odd Number based on the N value using for loop

Program
public class Main
{
    public static void main(String args[])
    {
        int x,n=10;
        if(n%2==0)
        {
            for(x=1; x<=n; x++)
            {
                if(x%2==0)
                {
                 System.out.println(x); 
                }
            }
        }
        else
        {
            for(x=1; x<=n; x++)
            {
                if(x%2!=0)
                {
                System.out.println(x); 
                }
            }
        
        }
    }
}	

Output:

2
4
6
8
10

Using CommandLine Arguments
public class Main
{
    public static void main(String args[])
    {
        int x,n;
        n=Integer.parseInt(args[0]);    
        if(n%2==0)
        {
            for(x=1; x<=n; x++)
            {
                if(x%2==0)
                {
                 System.out.println(x); 
                }
            }
        }
        else
        {
            for(x=1; x<=n; x++)
            {
                if(x%2!=0)
                {
                System.out.println(x); 
                }
            }
        
        }
    }
}	

Output:

2
4
6
8
10

Using Scanner Class
import java.util.*;
public class Main
{
    public static void main(String args[])
    {
        int x,n;
        Scanner s=new Scanner(System.in);
        System.out.println("Enter n value: ");
        n=s.nextInt();
        if(n%2==0)
        {
            for(x=1; x<=n; x++)
            {
                if(x%2==0)
                {
                 System.out.println(x); 
                }
            }
        }
        else
        {
            for(x=1; x<=n; x++)
            {
                if(x%2!=0)
                {
                System.out.println(x); 
                }
            }
        
        }
    }
}	

Output:

Enter n value : 10
2
4
6
8
10





More Questions


45 . Write a Java-program to display display Even Numbers using for loop
46 . Write a Java-program to display Even Number or Odd Number based on the N value using for loop
47 . Write a Java-program to display Even Number or Odd Number based on the N value using single for loop
48 . Write a Java-program count the number of divisible numbers in a given range(1-100) ?
49 . Write a Java-program count the number of divisible numbers in a given range(1-100) without loop
50 . Write a Java-program to print Factorial Number using for loop ?
51 . Write a Java-program to print Factorial of upto N Numbers using for loop ?
52 . Write a Java-program to print sum of natural numbers using for loop ?
53 . Write a Java-program to print sum of Even numbers using for loop ?
54 . Write a Java-program to print sum of Odd numbers using for loop ?
55 . Write a Java-program to print sum of even or odd numbers based on the N value using for loop ?