Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm doing a very simple program to add large sum of numbers, I'm using unsigned long long int. I have a working solution already, I just need help to understand why my first trial with just one variable (sum) won't work.

What I have tried:

C++
#include <iostream>
using namespace std;

int main(){
    int input;
    cin >> input; // How many input for sum ?

    // just one variable that I use as input
    // then I just sum this variable via loop
    unsigned long long int sum = 0;

    for (int i =0; i < input; i++){ //loop for sum
        cin >> sum;
        sum+=sum;
    }
    
    cout << sum << endl;
    return 0;
}

The working solution is this one, I've added a new variable for looping input :
C++
#include <iostream>
using namespace std;

int main(){
    int input;
    cin >> input; // How many input for sum ?
    
    //two variables, one for input and one for sum of the input
    unsigned long long int sum = 0, in;

    for (int i =0; i < input; i++){ //loop for sum
        cin >> in;
        sum+=in;
    }
    
    cout << sum << endl;
    return 0;
}
Sample input :
5 (How many input)
1000000001 1000000002 1000000003 1000000004 1000000005 (Actual input)

Answer from code 1          = 2000000010
Correct answer (code 2)     = 5000000015
What explanation did I miss here ?
Posted
Updated 13-Oct-21 4:38am

1 solution

You answered it yourself:
cin >> sum;
sum+=sum;
Each loop, your new input is overwriting the contents of sum. And then doubling that.
 
Share this answer
 
Comments
lock&_lock 12-Oct-21 20:25pm    
@Joe For godsake, I'm completely embarrassing myself. It's is using cin, therefore it will replace the existing value instead of just adding it, why did I think it would work. You are correct, thank you. I'm so blind, I really need to rest.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900