Problem statement:- Program to find the sum of odd numbers using recursion.
Data requirement:-
Input Data:- num2
Output Data:-SumOdd(num1,num2)
Output Data:-SumOdd(num1,num2)
Program in C
Here is the source code of the C Program to find the sum of odd numbers using recursion.
Code:
#include<stdio.h>
int SumOdd(int num1, int num2)
{
if(num1>num2)
return 0;
return num1+SumOdd(num1+2,num2);
}
int main()
{
int num1=1,num2;
printf("Enter your Limit:");
scanf("%d",&num2);
printf("Sum of all odd numbers in the given range is: %d",SumOdd(num1,num2));
}
Enter your Limit:12
Sum of all odd numbers in the given range is: 36
Program in C++
Here is the source code of the C++ Program to find the sum of odd numbers using recursion.
Code:
#include<iostream>
using namespace std;
int SumOdd(int num1, int num2)
{
if(num1>num2)
return 0;
return num1+SumOdd(num1+2,num2);
}
int main()
{
int num1=1,num2;
cout<<"Enter your Limit:";
cin>>num2;
cout<<"Sum of all odd numbers in the given range is:"<<SumOdd(num1,num2);
}
Enter your Limit:5
Sum of all odd numbers in the given range is:9
Program in Java
Here is the source code of the Java Program to find the sum of odd numbers using recursion.
Code:
import java.util.Scanner;
public class FindSumOfOddNumber {
static int SumOdd(int num1, int num2)
{
if(num1>num2)
return 0;
return num1+SumOdd(num1+2,num2);
}
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
int num1=1,num2;
System.out.print("Enter your Limit:");
num2=cs.nextInt();
System.out.print("Sum of all odd numbers in the given range is:"+SumOdd(num1,num2));
cs.close();
}
}
Enter your Limit:25
Sum of all odd numbers in the given range is:169
Program in Python
Here is the source code of the Python program to find the sum of odd numbers using recursion.
Code:
def SumOdd(num1,num2):
if num1>num2:
return 0
return num1+SumOdd(num1+2,num2)
num1=1
print("Enter your Limit:")
num2=int(input())
print("Sum of all odd numbers in the given range is:",SumOdd(num1,num2))
Enter your Limit:
155
Sum of all odd numbers in the given range is: 6084
Most Recommend Questions:-
More Questions:-
0 Comments
Please do not Enter any spam link in the comment box