Question

Find sum of even numbers in given range using recursion.

				
					ENTER THE LOWER RANGE
1
ENTER THE UPPER RANGE
100
Sum of even number between 1 AND 100 :2550
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class sum
{
    long lowerRange=0,upperRange=0,sum=0;
    public void accept()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("ENTER THE LOWER RANGE");
        lowerRange=sc.nextLong();
        System.out.println("ENTER THE UPPER RANGE");
        upperRange=sc.nextLong();

    }

    public long findSum(long lowerRange)
    {
        if(upperRange< lowerRange)
        {
            return 0;
        }
        else if(lowerRange%2==0)
        {
            return lowerRange+findSum(lowerRange+1);  
        }
        else
        {
            return findSum(lowerRange+1);
        }

    }

    public void display()
    {
        sum=findSum(lowerRange);
        System.out.println("Sum of even number between "+lowerRange+" AND "+upperRange+" :"+sum);
    }

    public static void main()
    {
        sum ob1=new sum();
        ob1.accept();
        ob1.display();

    }
}  

				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *