Question
Find the sum of odd numbers in a given range using recursion.
ENTER THE LOWER RANGE
1
ENTER THE UPPER RANGE
10
Sum of odd number between 1 AND 10 :25
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 odd numbers between "+lowerRange+" AND "+upperRange+" :"+sum);
}
public static void main()
{
sum ob1=new sum();
ob1.accept();
ob1.display();
}
}