2D array

my output for the main function is not outputting correctly. the first number is "2005398656" when all the numbers in the file are 1-7. the rest of the numbers fit in those parameters, but are out of order, and when I add the values in a row and output the sum the first 5 of 7 numbers are correct.
not to sure how to fix this, mainly the problem with the first number.

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <fstream>
//Jacob Wilt
//Monkey Business
using namespace std;
ifstream infile;
ofstream outfile;
const int rowmax = 7;       //the rows are each monkey
const int colmax = 7;       //the columns are the days
void totalaverage(int []), least(int []), greatest(int []), monkeyaverage(), dayaverage();
int main()
{
    infile.open("C:\\Users\\Jacob\\Desktop\\monkeyFile.txt");
    outfile.open("monkeys.txt");
    int sum[colmax];
    int monkey[rowmax][colmax];
    for (int i = 1; i <= rowmax; i++)
    {
        monkey[i][i] = 0;
    }
    int a = 0;
    int b = 0;
    int c = 0;
    for (int i = 1; i <= 49; i++)
    {
        infile >> a >> b >> c;
        monkey[a][b] = c;
        cout << monkey[a][b] << "   ";
        if (i % 7 == 0)
            cout << endl;
    }
    for (int i = 1; i <= rowmax; i++)
    {
        int x = 0;
        for (int j = 1; j <= colmax; j++)
        {
            x = x + monkey[i][j];
        }
        sum[i] = x;
        cout << sum[i] << "  ";
    }
    totalaverage(sum);
    least(sum);
    greatest(sum);
    monkeyaverage();
    dayaverage();
    infile.close();
    outfile.close();
    return 0;
}
void totalaverage(int sum[])
{
    cout << "\n\nAVERAGE\n";
    int total = 0;
    int average;
    for (int i = 1; i <= rowmax; i++)
    {
        total = total + sum[i];
    }
    average = total / rowmax;
    cout << "Average = " << average;
}
void least(int sum[])
{
    cout << "\n\nLEAST\n";
    int small = 500;
    for (int i = 1; i <= colmax; i++)
    {
        if (sum[i] < small)
        {
            small = sum[i];
        }
    }
    cout << "Smallest = " << small;
}
void greatest(int sum[])
{
    cout << "\n\nGREATEST\n";
    int big = 0;
    for (int i = 1; i <= colmax; i++)
    {
        if (sum[i] > big)
        {
            big = sum[i];
        }
    }
    cout << "Largest = " << big;
}
Array indices start at 0, not 1.
So for instance, to loop over a one-dimensional array, it would be this:
1
2
3
4
int array[10];
// ...(set values here)
for (int i = 0; i < 10; ++i)
    // Do stuff 

When working with any container, indecies start at 0, and end at their (size - 1).

Also, when working with containers and referencing indecies, it's good practice to reference the index with an unsigned integer.
Last edited on
Topic archived. No new replies allowed.