Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have a computer science project I\'m working on and I need help. I need to imp

ID: 3768796 • Letter: I

Question

I have a computer science project I'm working on and I need help. I need to implient the int sum into my main function and write the code for it to get the recursive version to calculate the sum of 1 + 2 + .... + n. Please help me.

#include <iostream>

using namespace std;

int str_length(char s[], int start);

int sum(int n);

void write_vertical(int n);

int main() {

// test str_length function

char sentence[81];

cout << "Enter a sentence: ";

cin.getline(sentence, 80);

cout << "There are " << str_length(sentence, 0) << " charcters in the sentence." << endl;

// test sum function

// test write_vertical funtcion

int n;

cout << "Enter an integer: ";

cin >> n;

write_vertical(n);

system ("pause");

return 0;

}

int str_length(char s[], int start) {

if(s[start] == '')

return 0;

return 1 + str_length(s, start + 1);

}

int sum(int n) {

return 0;

}

void write_vertical(int n) {

// If n is single integer, write it directly.

if (n <= 9) {

cout << n << endl;

return;

}

// write out all digits execpt last one

write_vertical(n/10);

//write out last digit of n

cout << n%10 << endl;

}

Explanation / Answer

#include <iostream>
using namespace std;

int str_length(char s[], int start);
int sum(int n);
void write_vertical(int n);

int main(){
   char sentence[81];
   cout << "Enter a sentence: ";
   cin.getline(sentence, 80);
   cout << "There are " << str_length(sentence, 0) << " charcters in the sentence." << endl;
  
   // test sum function
   int n;
   cout << "Enter an integer: ";
   cin >> n;
   cout << "Sum is " << sum(n) << endl;  

   // test write_vertical funtcion
   cout << "Enter an integer: ";
   cin >> n;
   write_vertical(n);
   return 0;
}

int str_length(char s[], int start){
   if (s[start] == '')
       return 0;
   return 1 + str_length(s, start + 1);
}

int sum(int n){
   if (n == 0)
       return 0;
   return n + sum(n-1);
}

void write_vertical(int n){
   if (n <= 9){
       cout << n << endl;
       return;
   }
   write_vertical(n%10);
   cout << n%10 << endl;
}