Search code examples
c++visual-studio-2012for-loopiomanip

How to get the sum of 3 columns of existing output using <iomanip>


I'v wrote a program for class which uses a for loop to have the user enter a values and it gives you a table with a loop counter, show number entered, and product. I'm trying to get the sum of All 10 numbers in each column to display at the end of each. I'm rather confused how to sum each column and display it underneath. Any help would be GREAT! I'm using Visual Studio Express 2012

#include <iostream>
#include <iomanip> 
using namespace std;

int main()
{

int input;

cout << "Enter Value: ";
cin >> input;
cout << "Loop Counter" << setw(20) << "Number Entered" << setw(14) << "Product" << endl;

for(int counter = 1; counter <= 10; counter++)

{
    int product = input * counter;

    if (product < 10 && counter != 10)
        cout << setw(6) << counter << setw(17) << input << setw(17) << product << endl;  
    else if (product > 10 && counter != 10)
        cout << setw(6) << counter << setw(17) << input << setw(18) << product << endl; 
    else
        cout << setw(7) << counter << setw(16) << input << setw(18) << product << endl;
}
cout<<setfill('_')<<setw(45)<<"_"<<endl;
}

Solution

  • You'll need to sum up the column values in separate variables. Change your code like this:

    #include <iostream>
    #include <iomanip> 
    using namespace std;
    
    int main() {
    
        int input = 0;
    
        cout << "Enter Value: ";
        cin >> input;
        cout << "Loop Counter" << setw(20) << "Number Entered" << setw(14) << "Product" << endl;
    
        int counterSum = 0;
        int inputSum = 0;
        int productSum = 0;
        for(int counter = 1; counter <= 10; counter++) {
            int product = input * counter;
    
            if (product < 10 && counter != 10)
                cout << setw(6) << counter << setw(17) << input << setw(17) << product << endl;  
            else if (product > 10 && counter != 10)
                cout << setw(6) << counter << setw(17) << input << setw(18) << product << endl; 
            else
                cout << setw(7) << counter << setw(16) << input << setw(18) << product << endl;
            counterSum += counter;
            inputSum += input;
            productSum += product;
        }
        cout<<setfill('_')<<setw(45)<<"_"<<endl;
        cout << setfill(' ') << setw(7) << counterSum << setw(16) << inputSum << setw(18) << productSum << endl;
    }