average from column

I have 1000 rows in a column in a txt file. i want the average of each five row of the column. like average of 1 to 5, then average of 6 to 10, then 11 to 15 and so on.
I am using the ifstream to read the column from the txt file, but after that dnt understand how to do the average....

please help!!!
1
2
3
4
5
6
7
8
suppose your array is a[1000]
for(int i = 0; i<1000;)
{
    int temp = a[i] + a[i+1] + a[i+2] + a[i+3] + a[i+4];
    cout<<"average of "<<i+1<<"to";
    i = i + 1;
    cout << i << "is" << temp/5;
}
Last edited on
I'm sorry, HiteshVaghani1 but your code is wrong in several ways...

1
2
3
4
5
6
7
8
9
10
11
float a[1000]; 

for (int i = 0; i < 1000; i += 5) {
    float average = 0;
    for (int j = i; j < i + 5; ++j) {
         average += a[j]; // get the sum of corresponding entries
    }
    average /= 5.f; // compute the average value
    
    std::cout << "Average of rows " << i + 1 << " to " << i + 5 << " is " << average << std::endl;
} 


I usually don't write code in answers to such questions, but I really don't want tatai to be confused. Tatai, please try to understand each line of code that I have written and ask me if something is confusing you.
Last edited on
Thank you KRAkatau. I could not understand,
average/=5.f;

what is 'f'.

i have the data in txt file. i need to read the data from that file first. but in that case, I cant use the ARRAY. please explain how can I read a column from a txt file as an array.
.f turns a number into a floating point type.
you should use the std::ifstream to open a file and then use operator>> to read data like this:

1
2
3
4
std::ifstream input("in.txt");

float v;
input >> v;


Just create an array and the data into it in a loop.
I am using the following code for the purpose. I need to get the average of colb. I am considering colb as 'float', but it is not working.

how to get the number of rows in each column??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<stdio.h>
#include<iostream>
#include<fstream>
using namespace std;

void main()
{
	float cola, colb, colc,cold, cole,colf,colg, colh, coli, colj; 
	ofstream summay("summary.out");
	
	while(summay<<cola<<colb<<cold<<cole<<colf<<colg<<colh<<coli<<colj)
	{

for (int i = 0; i < 10; i += 5) 
{
    float average = 0;
    for (int j = i; j < i + 5; ++j) 
	{
         average += colb[j]; // ERROR IN THIS STEP!!!!
    }
    average /= 5.f; 
    
    cout << "Average of rows " << i + 1 << " to " << i + 5 << " is " << average << endl;
}
	system("pause");
} 
}
Last edited on
Topic archived. No new replies allowed.