Go to Top

Saturday 19 November 2011

To find the sum of even and odd numbers

Question 68 : Write a program in Java to find the sum of odd and even numbers between a range.

Java Program : 

public class sum_range
{
 int e,o,l,u;
 public sum_range(int lower_limit,int upper_limit)
 {
     l=lower_limit;
     u=upper_limit;
     e=0;
     o=0;
     sum();
     display();
    }
    public void sum()
    {
        for(int i=l;i<=u;i++)
        {
            if(i%2==0)
            even(i);
            else
            odd(i);
        }
    }
    public void odd(int a)
    {
        o=o+a;
    }
    public void even(int a)
    {
        e=e+a;
    }
    public void display()
    {
        System.out.print("The sum of even numbers : "+e);
        System.out.print("\nThe sum of odd numbers : "+o);
    }
}
    

No comments:

Post a Comment

ShareThis