Mar 13, 2013 at 12:48am UTC
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:59am UTC
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 UTC
Use below code
Last edited on Mar 13, 2013 at 1:20am UTC
Mar 13, 2013 at 1:08am UTC
Why making the operation so complicated?
Mar 13, 2013 at 1:17am UTC
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 UTC
Mar 13, 2013 at 1:38am UTC
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:
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 UTC
Mar 13, 2013 at 1:54am UTC
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.