Initializing an array in a while loop

Hi,

I have the following code to sum the raws of an array.
Basically I have 4 raw and xx col and I want to sum the raw in that order:
raw 2 and raw 3
raw 2 and raw 3 and raw 4
raw 1 and raw 3
raw 1 and raw 3 and raw 4

The loops work except that it keeps accumulating. I am sure it's because I need to reinitialize my array within the loop, I tried at line 37, but it won't work.
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <fstream>
#include <vector>

#define row 4
#define col 191880

double dailydens [row][col];
double dens4d[col];

int i,j,k;
int di = 1, dj = 2, dij=0;

int main ()
{
	/* Load files */
	std::ifstream dens ( "md4d.txt" );
	if ( !dens ) {
		std::cout << "Unable to read density file";
		exit(1);
	}
	for ( i=0; i<row; i++ ) {
		for ( j=0; j<col; j++ )
			dens >> dailydens[i][j];
	}

	/* Start while loops */
	while (di >= 0)
	{
		while (dj < row)
		{
			for ( j=0; j<col;j++)
				for ( i=di;i<dj+1;i++)
				{
					dens4d[j] = dens4d[j] + dailydens[i][j];
				}
			dens4d[col]=0;
			dj++;
		}
		dj=3;
		di--;
	}

	/* Save files */
	std::ofstream tryy ( "SumDens4d.txt" );
		for ( j=0; j<col; j++)
		    tryy << dens4d[j] << std::endl;

	std::cin.get();
	return 0;
}
I'm not sure what you want to obtain, but for the start let me tell you what you have to fix:

1. You can get rid off the std:: scope by making it global with this instruction
using namespace std;
After this, you don't have to type std::cout/std::cin.get() etc, just cout, cin.get() etc. It gives you a ,,better" picture of the code. Be advised, at some points it might get into conflict with what you write.

2. You don't have reinitialize the dens4d variables. Every global variable is always initialized with 0. In the case you would have declared your variables inside the function, everything would have collapsed, because in your code, you firstly make the sum, then initialize, which results in a big error.

3. If you set after every second while loop dj=3, what do you think it will happen? The second while will always meet it's condition and will repeat forever, despite you increment it. You must eliminate the dj=3 instruction, and the code will work.

4. For the sake of beauty, terminate those 2 processes with this function.
variable.close(); where variable is tryy and dens
Topic archived. No new replies allowed.