Drewdinie Drewdinie - 19 days ago 7
C++ Question

Only returns the first value of x=a or 'start' variable

#include <iostream>
using namespace std;
int sumTo(int a, int b);


int main()
{
int start;
int end;

cout << "Enter one number " << endl;
cin >> start;
cout << "The second number " << endl;
cin >> end;

int total = sumTo(start, end);


cout << "The sum of the integers btween these 2 numbers is " <<total<<endl ;

return 0;

}
int sumTo(int a, int b)
{
int sum = 0;
for (int x = a; x <= b; x++)
{

sum += x;
cout << sum << endl;
return sum;
}
}


Hi so with this one It needs to find the sum of all the numbers between the two input numbers. Right now it only returns the first input number not sure why?

Answer

The problem with your code is that return sum; has been placed inside of the for loop. This will result in the for loop running only once because the function has already returned the value of sum, which is a.

int sumTo(int a, int b)
{
    int sum = 0;
    for (int x = a; x <= b; x++)
    {

        sum += x;
        cout << sum << endl;
        return sum; // Here is your problem.
    }
}

Your function actually should be

int sumTo(int a, int b)
{
    int sum = 0;
    for (int x = a; x <= b; x++)
    {

        sum += x;
        cout << sum << endl;
    }
        return sum; // This line should be placed here instead.
}
Comments