I am a 22 year old college gal currently enrolled in a c++ course, and we are on the topic of recursion. I understand how it works and have completed several other exercises on the professor has listed in the book, but this one has me stumped. Is there anyone out there that could help me out? I think I have 90% of it done. The question is in three parts, and its the last part I cannot seem to get:

part 3: Extend the function of exercise 5 so that it also outputs a running total as the numbers are printed out in revers order. For example the i/o dialog might be the following:

Enter Positive Number, 0 to End: 10
Total: 10
Enter Positive Number, 0 to End: 20
Total: 30
Enter Positive Number, 0 to End: 30
Total: 60
Enter Positive Number, 0 to End: 0

The function then outputs:

30 total: 30
20 total: 50
10 total: 60

It is the last total while the numbers are printed reversed that I just can't get.
I will paste in my "working" code below, omitting the cout portion that I can't figure out. I hope one of ya'll can help me, I've heard good things about this place.

void posInteger(int sum){
     int number;
     cout << "Enter Positive Number, 0 to end: ";
      cin >> number;
      sum = sum+number;
     
     if(number <= 0){
               
               return;
          }
          else{
               cout << "Sum: " << sum << endl;
               posInteger(sum);
               cout << number << " Total: " << endl; 
               
               }
     }

I am a 22 year old college gal

I see what you did there.. :P

This is the short solution I came up with, but I wouldn't know if it's valid for your exercise.

#include <iostream>

using namespace std;

int posInteger(int sum){
	int number, revSum = 0;
	
	cout << "Enter Positive Number, 0 to end: ";
	cin >> number;
     
	if (number <= 0)
		return 0;
	else {
		sum += number;
		cout << "Sum: " << sum << endl;
		revSum += posInteger(sum) + number;
		cout << number << " Total: " << revSum << endl; 
	}
	
	return revSum;
}

int main(){
	posInteger(0);
	cin.get();
	return 0;
}

Note that this can also be done by passing the reference of a variable from main along with the function which would store the reverse summation, but I don't know if this has been covered yet. Plus it doesn't really matter. :p

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.