user3068686
user3068686

Reputation:

Need to fix a simple loop

Okay I need to write a function that takes an integer parameter and prints the sum of each number up to that point. For example, n = 10 would be 1+2+3+4+5+6+7+8+9+10.

int SumOneToN(int n)
{
    int x = 0;
    while (x <= n)
    {
        cout << x+(x+1) << " ";
        x++;
    }
    cout << endl;
}

So what's going on here? 1. Set up the function as SumOneToN. 2. Initialize x to 0. 3. Create a while loop that states while x is less than our parameter, we take x, add it to x+1 (so that we get our current x value added to the next one), print it, then we add to x for the loop to go again until we meet the parameter.

That's how I thought it should work, anyways. What actually returns is:

1 3 5 7.. etc

I'm not sure where I went wrong?

Upvotes: 0

Views: 123

Answers (6)

Viswajith
Viswajith

Reputation: 31

Hey you are using same variable for Sum & as looping variable

try this code

int add(int n)
{
    int sum=0;

    for(int i=1;i<=10;i++)
        sum=sum+i;

    return sum;
}

Upvotes: 0

Sumedh
Sumedh

Reputation: 404

You can try this:

int SumOneToN(int n){
    int sum=n,x=1;
    while(x<n){
        cout<<x<<"+";
        sum+=x;
        x++;
    }
    cout<<x;
    return sum;
}

Note: This wont print an additional '+' after last number.

Upvotes: 0

Shaan
Shaan

Reputation: 25

Write the "+" sign in the inverted commas and cout x; once before the while loop. If you want to do it by SUM than you have to introduce another variable and the above solutions are fair enough.

#include <iostream>
using namespace std;

int SumOneToN(int n)
{
    int x = 1;
    cout << x ;
    x++;
    while (x <= n)
    {
        cout << " + " << x ;
        x++;
    }
    cout << endl;
}

int main()
{
    int x;
    cin >>x;
    SumOneToN(x);
    return 0;
}

Upvotes: 0

Karthik Surianarayanan
Karthik Surianarayanan

Reputation: 626

int SumOneToN(int n)
{
    int sum=0;
    for(int x=1;x<=n;x++)
    {
        sum+=x; 
        cout << sum << " ";
    }
    cout << endl;
    return sum;
}

Upvotes: 0

Harichandan Pulagam
Harichandan Pulagam

Reputation: 368

Try this :

int SumOneToN(int n)
{
    int x = 1, sum=0;
    while (x <= n)
    {
        sum=sum+x; 
        cout << sum << " ";
        x++;
    }
    cout << endl;
    return sum;
}

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 60037

Why not use some maths an not have the loop in the first place?

i.e.

int SumToOne(int n) {

    return (n * (n + 1))/2;
}

Upvotes: 1

Related Questions