For this assignment, you will write two functions. Function 1: Write a function
ID: 3669397 • Letter: F
Question
For this assignment, you will write two functions.
Function 1:
Write a function that accepts an integer argument and returns the sum of all the integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function will return the sum of 1, 2, 3, 4, ... 50. Use recursion to calculate the sum. Demonstrate the function in a program.
Function 2:
Write a recursive function that accepts a string object as its argument and prints the string in reverse order. Demonstrate the function in a driver program.
Explanation / Answer
#include<iostream>
#include<string.h>
using namespace std;
int function1(int);
int function2(string);
main()
{
int num,sum;
string str;
cout<<"Please enter a number: ";
cin>>num;
sum=function1(num);
cout<<"The sum is: "<<sum;
getline(cin,str);
function2(str);
}
int function1(int num)
{
if(num == 1)
return 1;
return num+function1(num-1);
}
int function2(string str)
{
int len;
len = str.length();
if(len == 1)
cout<<str;
else
{
cout<<str[len-1];
function2(str.substr(0,len-1));
}
}
//Hope it helps. :-)
//If you have any query or confusion, please leave a comment, I’ll try to explain in more details.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.