Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of Numbers C++

Tags:

c++

for-loop

sum

I am supposed to write a program that asks the user for a positive integer value. The program should use a loop to get the sum of all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1, 2, 3, 4, ... 50.

But for some reason it is not working, i am having trouble with my for loops but this is what i have down so far.

#include <iostream>
using namespace std;

int main()
{
    int positiveInteger;
    int startingNumber = 1;
    int i = 0;

    cout << "Please input an integer up to 100." << endl;

    cin >> positiveInteger;

    for (int i=0; i < positiveInteger; i++)
    {
        i = startingNumber + 1;
        cout << i;
    }

    return 0;

}

I am just at a loss right now why it isn't working properly.

like image 894
soniccool Avatar asked Nov 29 '22 16:11

soniccool


1 Answers

The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.

like image 130
Ernest Friedman-Hill Avatar answered Dec 05 '22 07:12

Ernest Friedman-Hill