I need help online now have no clue at all how to do this

Mar 13, 2013 at 12:48am
Write a program that asks the user for a number. Then the program outputs the sum of all positive numbers up to that number.

For example, if the user types in 10
The program outputs 55
Because that is what 1+2+3+4+5+6+7+8+9+10 is.

Mar 13, 2013 at 12:56am
Mar 13, 2013 at 12:59am
int main(){
int number, result=0;

cin>>number;
for(int i=0;i<number;i++){
result= result+i;
}

}

something like that, figure out the rest, this program will not include the number 10 in the addition, it goes UP TO number.
Mar 13, 2013 at 1:01am
Use below code
Last edited on Mar 13, 2013 at 1:20am
Mar 13, 2013 at 1:08am
Why making the operation so complicated?
Mar 13, 2013 at 1:17am
Sorry mrtyson86. Use this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "stdafx.h"
#include <iostream>
using namespace std;


int main() {
   int input = 0;
   int newNum = 1;
   cout << "Enter number: ";
   cin >> input;
   for (int i=1; i < input; i++) {
		newNum += i + 1;
   }
   cout << newNum;
}


or something to that effect.
Last edited on Mar 13, 2013 at 1:25am
Mar 13, 2013 at 1:38am
Or you can use early German mathematician Carl Gauss's formula for finding the sum of all numbers up to N, and eliminate the need for the loop all together:

Gauss's formula is:
 
x = n * (n+1) / 2


Less complex yet:
1
2
3
4
5
6
7
8
9
10
11
#include "stdafx.h"
#include <iostream>
using namespace std;

int main() {
   int input, newNum;
   cout << "Enter number: ";
   cin >> input;
   newNum = input * (input + 1)/2;
   cout << newNum;
}


I guess math really is cool?
Last edited on Mar 13, 2013 at 2:00am
Mar 13, 2013 at 1:54am
What I would do is to use the formula as a cross-check in order to verify that the loop and summation is giving the correct answer.

Topic archived. No new replies allowed.