Write a Java-program to print sum of even or odd numbers based on the N value using do while loop ?

Write a Java-program to print sum of even or odd numbers based on the N value using do while loop ?

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

Output:

9

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

Output:

9

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

Output:

Enter n value : 5
9





More Questions


86 . Write a Java-program to print sum of even or odd numbers based on the N value using do while loop ?
87 . Write a Java-program to print sum of even or odd numbers based on the N value using single do while loop ?
88 . Write a Java-program to display the Table using do while loop ?
89 . Write a Java-program to display vowels using continue statement ?
90 . Write a Java-program to display the whose values divisible by 2 and 3 Continue statement in java ?
91 . Write a Java-program to Break the loop which number is divisible by 2 and 3 in java ?
92 . Write a Java-program to print a to z character
93 . Write a Java-program to print A to Z character
94 . Write a Java-program to print character numbers
95 . Write a Java-program to print symbols
96 . Write a Java-program to print ASCII values of a to z