Question: c++ Write the following 2 functions and test them. Both of them need to be recursive functions. int sum(int n); // recursive version to calculate
c++ Write the following 2 functions and test them. Both of them need to be recursive functions.
int sum(int n);
// recursive version to calculate the sum of 1 + 2 + ..... + n
int str_length(char s[];
// Returns length of the string s[] and the null character, '0\', is not counted in the length).
Example of program execution;
Enter a positive integer: 10 (user input)
The sum of 1+ 2+....+10 is: 55
Enter a sentence: Hello World! (user input)
The sentence contains 12 characters, including white spaces.
Do you want to run again? Y/N: y (user input)
repeat above steps...
Do you want to have another run? Y/N? n (user input)
Program ended with exit code: 0
What I have so far;
#include "stdafx.h"
#include
using namespace std;
int str_length(char s[], int start);
int sum(int n);
char ch;
int main()
{
//characters
char sentence[100];
cout << "Enter a sentence: ";
cin.getline(sentence, 99);
cout << "There are " << str_length(sentence, 0) << " charcters in the sentence." << endl;
// sum
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Sum is " << sum(n) << endl;
}
int str_length(char s[], int start) {
if (s[start] == '\0')
return 0;
return 1 + str_length(s, start + 1); //recursive method to count char from 1 to '\0'
}
int sum(int n) {
if (n == 0)
return 0;
return n + sum(n - 1); //recursive method to calculate sum from 1 to n
}
I just need help with setting it up to ask the user if they want to run again and if they say yes, doing so. What I've tried so far either caused infinite loops or errors.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
