Search code examples
c++for-loopsubtraction

subtract n times int value


My code subtract n times a quantity:

int op = 0,quan,numbers,many;
cout << "Quantity to substract: " << endl;
        cin >> quan;
        cout << "Times to subs quantity:" << endl;
        cin >> many;
        for(int count = 1; count <= many; count++)
        {
            cout << "Insert " << count << " Number" << endl;
            cin >> numbers;                 
            op = quan - numbers;
        }
cout << "Total: " << op << endl;

But is not working.

Program Run:

Quantity to substract:
10
Times to subs quantity:
5
Insert 1 Number:
1
Insert 2 Number:
1
Insert 3 Number:
1
Insert 4 Number:
1
Insert 5 Number:
1
Total:
9

Total should be 5

Could you support me with this problem? Thank you


Solution

  • It looks like the goal here is to subtract all 5 numbers from quan. The code in question subtracts only the last one.

    To subtract all numbers, initialize the result variable to the first number:

    op = quan;
    

    and in the loop, subtract from the result variable:

    op = op - numbers; // alternatively: op -= numbers