I choose a program that can read data from a txt file. Now, I input two column from txt file and i want to substract first value of 2nd column to every value of 2nd column. finally I want the sum of substracted values. Can anyone please help me. Actually, i did like substract(1)+substract(2)+substract(3)+.........substract(n). But these becomes so long and mistaken can happened. So, I want a shot rules like h= sum(test[i]-test[0]).

#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
#include<cmath>
#include<iomanip>
#include <windows.h>

using namespace std;
//void calculateAverage();
//int calculateGrade();
//void updateFrequency();
int main()
{
    const int size=25;
    int debug=size;
    double test1[size], test2[size],h;
    ifstream infile;
    for(int i=0;i<size;i++)
    {
        test1[i]=0;
        test2[i]=0;
    }
    cout<<"Reading from file ''input.txt''..."<<endl;
    infile.open("input.txt");
    while(size==debug)
    {
        for(int i=0;i<size;i++)
        {
            infile>>test1[i];
            infile>>test2[i];
        }
        debug--;
    }
    for(int i=0;i<size;i++)
    {
        h=(test[i]-test[0]);
        cout<<test1[i]<<" "<<test2[i]<<" "<< h <<" "<<endl;
    }
    infile.close();
    system("pause");
    return 0;
}

Recommended Answers

All 2 Replies

Just make a sum variable and accumulate the results into it:

int sum = 0;

for (int i = 0; i < size; i++)
{
    sum += (test[i] - test[0]);
}

cout << "Sum of differences: " << sum << '\n';

thank you very much sir.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.