Total function!!!

Hi,

How can I write a separate function that sums up all the values of the cells of the array that I inserted it below and then show the total in the main function.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#define height 2
#define width 3
using namespace std;


int x,y;

int main ()
{
int eidan[height][width];


for (x=0;x<height;x++)
		for (y=0;y<width;y++)
		{
		cout <<"Enter the value\n";
		cin >> eidan[x][y];
		cout << "\n\n";
		
		}
		
return 0;
}
Here's an example:

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
#include <iostream>
#define height 2
#define width 3
using namespace std;


int x,y;

int main ()
{
int eidan[height][width];


for (x=0;x<height;x++)
		for (y=0;y<width;y++)
		{
		cout <<"Enter the value\n";
		cin >> eidan[x][y];
		cout << "\n\n";
		
		}
		
int accumulator=0;
for (x=0;x<height;x++)
		for (y=0;y<width;y++)
		{
		accumulator = accumulator+eidan[x][y];
        }
        cout<<accumulator<<"/n";
system ("pause");
return 0;
}


that's fine.. but how can I calculate the total in a separate function not in the main function and then show the total in the main.

thanks
Last edited on
This should 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
#include <iostream>
#define height 2
#define width 3
using namespace std;


int x,y;

int sum_array(int eidan[height][width])
{
    int accumulator = 0;
    for (x=0;x<height;x++)
		for (y=0;y<width;y++)
		{
            accumulator += eidan[x][y];
        }
        return accumulator;
}
            

int main ()
{
int eidan[height][width];


for (x=0;x<height;x++)
		for (y=0;y<width;y++)
		{
		cout <<"Enter the value\n";
		cin >> eidan[x][y];
		cout << "\n\n";
		
		}
		int array_value = sum_array(eidan);
        cout << array_value << "\n";

system("PAUSE");
return 0;
}
Topic archived. No new replies allowed.