First 2-D Array

Pages: 123
I feel so lost trying to do this program. I have no idea what I am doing or how to do it. I've been trying to do this average function, and I'm getting no where. I'm not certain as to what I need to do. As I do appreciate the semantics that everyone explains to me, I learn better seeing the syntax.

Do I need multiple arrays to store my data into such as, averages, totals??
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
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

//Prototypes
int read(ifstream&, float);
void print(ofstream&, float, int);
void header(ofstream&);
float averages(float,int);

const int MAXROWS = 50, COLS = 14;

int read(ifstream& inf, float ary[][COLS])
{
    int r = 0;
    for (int id; inf >> id; r++)
    {
        if (r == MAXROWS)
        {
            cout << "Table overflowed\n";
        }
        ary[r][0] = id;
        for (int c = 1; c < COLS; c++)
        {
            inf>> ary[r][c];
        }
    }
    return r;
}

void print(ofstream& out, float ary[][COLS], int rows)
{
    out << fixed;
    for (int r = 0; r < rows; r++)
    {
        out << setprecision(0); // print id without decimals
        out << setw(4) << ary[r][0];
        out << setprecision(2); // print others with 2 decimals
        for (int c = 1; c < COLS; c++)
        {
            out << setw(9) << ary[r][c];
        }
        out << endl;
    }
}

void header(ofstream& out)
{
    out << "\nSalesman ID " << "Last Years AVG "
        << "Current Year Monthly Sales "
        << "Current Year AVG(minus worst month) \n";
}

float averages(float ary[][COLS],int rows)
{
    float sum=0;
    for(int r=0; r<rows; r++)
    {
       for(int c=1; c<12; c++)
        sum+=ary[r][c];
    }
      return sum/=12.0;
}
int main()
{
    ifstream inf("Wildin.txt");
    if (!inf)
    {
        cout << "Error opening the input file\n";
        return 1;
    }

    ofstream out("Wildout.txt");

    float salesmen[MAXROWS][COLS],avg;
    int rows = read(inf , salesmen);
    print(out, salesmen, rows);
    header(out);
    avg=averages(salesmen,rows);
    out << avg;

}
Andy, I agree with you completely on making a list and working them out one at a time, but I am having such an issue with just trying to get one thing to function as it should. I'm unsure of what to do to 'test' the hardcoded numbers. I don't understand why my average function isn't listing the numbers for each salesman.

Correction: I don't know what I am doing enough to understand how to do it. DO I need to make more arrays to store certain data into? How do I make the array of data print the specific information it needs to the file? More specifically, just ID's, then average, totals, etc etc. Do I need to create more functions that call just that row or column?

I"m just confused with the 2d array, in class, the professor made it sound so simple and easy, but now that I've sat down and looked at this the last 4 days, I'm just lost and confused.

I learn better looking at the syntax than semantics. IF at all possible can you attempt to show syntax in the same style as I am using?

Thank you again for all your help, it's greatly appreciated
You need to study up on how to use functions, function prototypes, and function calls. Remember that each need to agree as to the type and number of parameters. Also you are confusing the issue by having the prototype different from the actual function implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Function prototype.
void print(ofstream&, float, int);

// Function implementation.
void print(ofstream& out, float ary[][COLS], int rows)
{

}

// Function call (in main())

    ofstream out("Wildout.txt");

    float salesmen[MAXROWS][COLS],avg;
    int rows = read(inf , salesmen);
    print(out, salesmen, rows);


Please notice that the function prototype and the function implementation do not match, I really suggest that you keep the function prototype and the function implementation exactly the same.

By the way do you know why the two don't match?

So this function should be prototyped and implemented something like:


1
2
3
4
5
6
7
8
// Function prototype.
void print(ofstream& out, float ary[][COLS], int rows);

// Function call
void print(ofstream& out, float ary[][COLS], int rows)
{

}



Since you seem so confused by the multidimensional array you may want to start with a single dimensional array, just read each column into an array and print that array. Then once you see how a single dimensional array is used it should be simpler to move to multidimensional arrays.

Hello CodeNovice01,


I'm unsure of what to do to 'test' the hardcoded numbers.


You do not test the hard coded numbers. There are only used to to get the output to look right.

To get this:


                                                           Total Monthly Sales
-------------------------------------------------------------------------------------------------------------------------------------------
       Last                                                                                                                  This
       Years                                                                                                                 Years   Worst
  ID  Average  January  February   March   April     May      June     July    August  September October November December  Average  Month
-------------------------------------------------------------------------------------------------------------------------------------------
 2021 17353.20 15371.70 31660.10  1950.28 25420.30 26744.20 29213.90  8022.51 30317.70 12677.90  2430.61 14591.50 32974.80  2747.90  1950.28


I used this code to start with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void printReport(ofstream& out, double salesmen[][COL], const int cnt)
{
	constexpr size_t WID{ 9 };
	std::string headings{ "  ID  Average  January  February   March   April     May      June     July    August  September October November December  Average  Month\n" };
	size_t len = headings.size();

	out << std::fixed << std::setprecision(2) << '\n' << std::string(((headings.size() / 2) - 10), ' ') << "Total Monthly Sales\n";

	out << std::string(len, '-') << '\n'
		<< "       Last" << std::string(114, ' ') << "This\n"
		<< "       Years" << std::string(113, ' ') << "Years" << "   Worst\n" 
		<< headings
		<< std::string(len, '-') << '\n';
	
	out << " " << static_cast<int>(salesmen[row][0]);
	out << std::setw(WID) << salesmen[row][13];

        out << std::setw(WID) << salesmen[0][0]
        out << std::setw(WID) << salesmen[0][1]
        out << std::setw(WID) << salesmen[0][2];

	out << '\n';
}

As you can see I created this function mostly to make it easier to work with. The name of the function could be better, but works for now.

Most times I find it easier to create one big string for the column headings and just use spaces between the words. I think it is easier to work with this way. There are other ways you could do this.

Line 16 I added after I figured out what I had missed.

Line 20 would repeat until the second dimension reaches (12). After I had the column headings the way I wanted and the information in each row spaced the way I wanted. I had something to start with.

After that I created a nested for loop to print out the first part. The first part being everything except the last two columns. Then I add the next to last column heading and created the function for the average.
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
void printReport(ofstream& out, double salesmen[][COL], const int cnt)
{
	constexpr size_t WID{ 9 };
	std::string headings{ "  ID  Average  January  February   March   April     May      June     July    August  September October November December  Average  Month\n" };
	size_t len = headings.size();

	out << std::fixed << std::setprecision(2) << '\n' << std::string(((headings.size() / 2) - 10), ' ') << "Total Monthly Sales\n";

	out << std::string(len, '-') << '\n'
		<< "       Last" << std::string(114, ' ') << "This\n"
		<< "       Years" << std::string(113, ' ') << "Years" << "   Worst\n" 
		<< headings
		<< std::string(len, '-') << '\n';
	
	for (int row = 0; row < cnt / 14; row++)
	{
		out << " " << static_cast<int>(salesmen[row][0]);
		out << std::setw(WID) << salesmen[row][13];

		for (size_t col = 1; col < COL - 1; col++)
		{
			out << std::setw(WID) << salesmen[row][col];
		}

		out << std::setw(WID) << CurrentYearAverage(salesmen, row);
		out << std::setw(WID) << WorstMonth(salesmen, row);
		out << '\n';
	}
}

Lines 25 and 26 i worked on one at a time. I found this easier than trying to do everything at once.

For your average function you are almost there:
1
2
3
4
5
6
7
8
9
10
11
12
float averages(float ary[][COLS], int rows)
{
    float sum=0;
                                     // <--- Blank line makes for easier reading.
    for(int r=0; r<rows; r++)
    {
       for(int c=1; c < 12; c++)
        sum += ary[r][c];
    }
                                     // <--- Blank line makes for easier reading.
      return sum/=12.0;
}

First thing I would suggest is to change the "float"s to "double"s, but it will be OK as is.

The next thing is that you should be working with one row at a time not the whole array. You asked if you needed multiple arrays to store your data. No you just need to use the one that you have.

You need to do away with the outer for loop and just correct the inner for loop.

In line 20 change "c" to "col". you started with (1) and that part is good, but in the condition part you say "< 12". This will add up elements 1 - 11 which is not what you want.

Line 8 is more understandable as sum += ary[row][col];

Line 11 may be a problem if your IDE/compiler interprets the "12.0" as a double. Since "sum" is defined as a "float" trying to divide a "float" by a "double". You would be better off just using (12). This way the int will be promoted to a float before the calculation.

This is what I did for the average function:
1
2
3
4
5
6
7
8
9
10
11
12
13
double CurrentYearAverage(double salesmen[][COL], const int row)
{
	constexpr double YEAR{ 12 };

	double sum{};

	for (int col = 1; col < COL - 1; col++)
	{
		sum += salesmen[row][col];
	}

	return sum / YEAR;
}



I"m just confused with the 2d array, in class, the professor made it sound so simple and easy


The best way to think about and work with a 2D array ia like this:

    0       1       2       3
0) 2021  15371.7 31660.1 1950.28 25420.3 26744.2 29213.9 8022.51 30317.7 12677.9 2430.61 14591.5 32974.8 17353.2

1) 1178  27352.5 28583.3 30570.9 23609.4   20661   33381 16392.5 19339.5 31867.9 16165.2  7635.1 11454.8 26701.3

2) 5141  22977.5 9582.07 3783.97  7096.1 31259.8 9007.33 15359.9 8655.28 19197.6 10245.3 19846.7 14194.6 14267.2


The first line represents the column numbers and the numbers on the left represent the row numbers. Do not confuse your-self trying to comprehend how the computer stores the array. Just think of it as rows and columns.

Andy
Thank you Andy for the help

I've updated and now I've got an understanding of waht I am doing, but how do I make the array to print in a table format instead of down the page?
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
89
90
91
92
93
94
95
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
const int MAXROWS=25, COLS=14;

int read(float[][COLS]);
void printID(float[][COLS],int);
void header();
void sum(float[][COLS],int);
float averages(float, int);


ifstream inf;
ofstream out;


int read(float ary[][COLS])
{
	int r=0;
    for(int id;inf >> id ;r++)
   {
	   if(r == MAXROWS)
		   cout << "Table Overflowed\n";
	   ary[r][0]=id;
        for(int c=1; c<COLS ;c++)
        {
            inf >> ary[r][c];
        }
    }
    return r;
}

void header()
{
    out << "|Salesman ID|  " << " |Last Year's Avg| "
        << " |Current Monthly Sales| " << " |Current Year Avg(minus Lowest)\n";
}

void printID(float ary[][COLS], int rows)
{
	out << fixed;
    for(int r=0; r<rows; r++)
    {
		out << setprecision(0) << "\t"<< ary[r][0] << endl;
    }
}
void printLYA(float ary[][COLS], int rows)
{
    out<< fixed;
    for(int r=0; r<rows;r++)
    out << setprecision(2) << " " << ary[r][13] << endl;
}
void sum(float ary[][COLS], int rows)
{
    float total=0;
    for(int r=0; r<rows;r++)
    {
        for(int c=1;c<COLS-1;c++)
        {
            total += ary[r][c];
        }
        out << total << " " << endl;
    }
}
float averages(float ary[][COLS],int rows)
{
    float sum=0,year=12.0;

    for(int c=1; c<COLS-1; c++)

        sum+=ary[rows][c];

      return sum/=year;
}

int main()
{
    inf.open("Wildin.txt");
    if(!inf)
        cout << "error opening file";
    out.open("Wildout.txt");


    float salesmen[MAXROWS][COLS],total;
	int rows,readit;
    rows = read(salesmen);
    header();
    printID(salesmen, rows);
    printLYA(salesmen, rows);
    sum(salesmen,rows);

   return 0;
}

OUTPUT:
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
|Salesman ID|   |Last Year's Avg|  |Current Monthly Sales|  |Current Year Avg(minus Lowest)
	2021
	1178
	5141
	8347
	6577
	2617
	2891
	7538
	2571
	9872
	5250
	4422
	1864
 17353.20
 26701.30
 14267.20
 20758.70
 14371.70
 20719.30
 20793.20
 12939.40
 15701.60
 18020.80
 19350.80
 18636.80
 25219.70
231375.50 
498388.62 
669594.81 
896053.00 
1068513.25 
1317145.38 
1525077.62 
1697603.25 
1854619.25 
2051209.75 
2283419.75 
2531910.25 
2807034.00 
 
Is this syntax acceptable for this function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void averages(float ary[][COLS],int rows)
{
    float sum=0,year=12.0;
    float small=ary[0][0];
    for(int r =0; r<rows;r++)
    {
         for(int c=1; c<COLS-1; c++)
         {
             if(small>ary[r][c])
             {
                 small=ary[r][c];
             }
            sum=sum+ary[r][c]-small;
         }
        out << '\n' << sum/year << " ";
    }
}

The assignment asks for the average of the current year minus the lowest month in sales.
Last edited on
Here's how I suggest you break this down. Copy the full text of the assignment into a source file. Put // in front of each line to turn it into comments. Then read it carefully and start writing data and function/method prototypes for what you think you need. Rearrange the text of the assignment as needed. The goal is to make the text of the assignment (or pieces of it) into the comments for your code and data.

Then go back over what you have and make changes as needed. After 2-3 passes, you should have a pretty good structure for what you need.

Here is my first pass, to show you what I mean:
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
// The “Wild and Wooley” company has a large salesman staff and the
// company needs to gather info about the salesman’s yearly sales
// results. You have been tasked with this assignment. There are no
// more than 15 salesmen on staff
const unsigned MaxSales = 15;

// and for each salesman the company
// has recorded for each month of the year, each salesman’s total
// monthly sales.
struct Salesman {
    double sales[12];		// sales for each month
};
// Also recorded for each salesman is his ID and his
// last year’s average monthly sales.
// Scratch that struct above, how about:
struct Salesman {
    double sales[12];		// sales for each month
    int id;			// his id
    double lastYearsAvg;	// last year's average monthly sales
};
    
// You are to compute for each
// salesman, this year’s average monthly sales.
double thisYearsAvg();

// Since everyone
// generally has a bad month, and the company is nice, you will also
// calculate a second monthly average sales dropping his one worst
// monthly sales.
double worstMonthlySales();  // the sales amount for this salesman's worst month
double thisYearsAvgModified();  // average, minus their worst month.
             // QUESTION: what's the math to compute this?

// The information to be reported are the following: Print out each
// salesman’s
// - ID,
// - his last year’s average monthly sales,
// - the current year’s monthly sales,
// - the current year’s average monthly sales minus his worst month
// - whether they have 10% increase
// all in a table format (columns, headers, ect.).
void printTable();

// Also to show in the table are the
// salesmen who had a 10% increase for this year’s sales over last
// years. (use 12 month averages). These salesmen will be slated
// for a year in bonus. 
bool has10PctIncrease(); // compute whether a salesman has the 10% increase

// Also, show my worst salesman whose
// two-year average is the lowest of all the salesmen, again to be
// shown in the table.
unsigned worst(Salesman salesmen[], size_t size);  // compute index of worst salesman

// List out each salesmen information in a nice table format. (The
// columns must be lined up.)

// 	Your input will be found in input file: “WildSalemen.dat” 
// 	The format of the input file:
//	ID    JanSales   Feb   Mar ….   Dec   LastYrAvg

// 	Ex input:  284  2500.00  8000.00  3050.00 7300.00 …. 1700.00    5525.00
//     Fields        ID    Jan            Feb         Mar      Apr               Dec       PrevYrAvg
bool read(istream &);

// 	A last minute update from the main accounting office:  
//	They need the total sales for each month to see how the company
//      is doing for the year.  
//     Generate a second table with the additional information:
//    Format:      
//	Total Monthly Sales
//	    January        February        March    ……                         //               Dec
//	    25000.00      82000.00     78525.00     …….                        //      19880.00
void printTotalSales(Salesman salesmen[], size_t size);


Thank you for the very insightful way of solving a problem, I hadn't thought of doing that. I will try that next go around, Only because I am so far into this now that I don't want to mess myself up..

Another question again, besides the numbers printing down the page instead of table format, my average function which totals up the 12 months and suppose to subtract the lowest month and divide by 12. IE: total+= ary[r][c]-small; the only issue I am having is that the code isn't taking the smallest value out of the calcualtions.

What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void averages(float ary[][COLS],int rows)
{
    float year=12.0;
    for(int r =0; r<rows;r++)
    {    float small=ary[0][1];

        float sum=0;

         for(int c=1; c<COLS-1; c++)
         {
             if(small>ary[rows][COLS])
             {
                 small=ary[rows][COLS];
             }
            sum += ary[r][c]-small;
         }
        out << '\n' << sum/year << " ";
    }
}
Can you tell me why when I call the function within a function it prints the same number over and over. But when i use the out statement within the sum and averages function it prints the correct totals.

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
void print(float ary[][COLS], int rows)
{
    float total = sum(ary,rows);
    float monthly = averages(ary,rows);
	out << fixed;
    for(int r=0; r<rows; r++)
    {
		out << setprecision(0) << "\t"<< ary[r][0]
            << setprecision(2) << "\t\t\t" << ary[r][13]
            << "\t\t" << total << "\t\t" << monthly << endl;
    }
}

float sum(float ary[][COLS], int rows)
{
    float total;
    for(int r=0; r<rows;r++)
    {
        total=0;
        for(int c=1;c<COLS-1;c++)
        {
            total += ary[r][c];
        } out << '\n' << total << " ";
    }    return total;
}
float averages(float ary[][COLS],int rows)
{
    float year=12.0,n;
    for(int r =0; r<rows;r++)
    {
        float small=ary[r][1],sum=0;

        for(int c=1; c<COLS-1; c++)
         {
             if(ary[r][c]<small)
             {
                 small=ary[r][c];
             }

            sum += ary[r][c];

            n=sum-small;
         }
    }
    return n/year;
}
Also, how would I create a function that displays the salesmen that have 10% more this year than last year?

I attempted to write the function, but i immediately became confused. I'm not confident on how to bring in the last year avg and compare to this year avg(sum of the 12 months) and then print out the salesmen who accomplished the feat.

It sounds like i'd need to call a few functions within the function. As you can tell from previous post, i'm not very good at that either.

1
2
3
4
5
6
7
8
9
void bonus(float ary[][COLS,int rows,float avg)
{float total;
int salesmen;
    for(int r=0;r<rows; r++)
    for(int c=0;c<COLS;c++)
    if(avg > .1*total)
    out << salesmen;

}


What do I do to make the data read into the function?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void worst(float ary[][COLS], int rows)
{
    out << "\t\tWorst Salesmen:\n";
    
    for(int r=0;r<rows;r++)
    {
        out << ary[r][0];

        for(int c=0; c<COLS;c++)
        {
            if(avg > total)
            {
                out << avg - total;
            }
            else
                out << "0.0";
        }
    }
}


Here's the full code
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
const int MAXROWS=25, COLS=14;

int read(float[][COLS]);
void print(float[][COLS],int);
void header();
void sum(float[][COLS],int);
void averages(float[][COLS], int);
void TotalMonthly(float[][COLS],int);


ifstream inf;
ofstream out;


int read(float ary[][COLS])
{
	int r=0;

    for(int id;inf >> id ;r++)
   {
	   if(r == MAXROWS)
		   cout << "Table Overflowed\n";

	   ary[r][0]=id;

        for(int c=1; c<COLS ;c++)
        {
            inf >> ary[r][c];
        }
    }
    return r;
}

void header()
{
    out << "|Salesman ID|  " << " |Last Year's Avg| "
        << " |Current Monthly Sales| " << " |Current Year Avg(minus Lowest)\n";
}

void print(float ary[][COLS], int rows)
{
	out << fixed;

    for(int r=0; r<rows; r++)
    {
		out << setprecision(0) << "\t"<< ary[r][0]
            << setprecision(2) << "\t\t\t" << ary[r][13]

            << endl;
    }
}

void sum(float ary[][COLS], int rows)
{
    for(int r=0; r<rows;r++)
    {
        float total=0;

        for(int c=1;c<COLS-1;c++)
        {
            total += ary[r][c];
        }
        out <<total <<" \n";
    }
    out << endl;
}
void averages(float ary[][COLS],int rows)
{
    float year=12.0,n;

    for(int r =0; r<rows;r++)
    {
        float small=ary[r][1],sum=0;

        for(int c=1; c<COLS-1; c++)
         {
             if(ary[r][c]<small)
             {
                 small=ary[r][c];
             }

            sum += ary[r][c];

            n=sum-small;
         }
        out << n/year << " \n";
    }
    out <<endl;
}
/*void bonus(float ary[][COLS,int rows,float avg)
{
    out << "\t\tSalesmen Slated for Bonus: \n";
    for(int r=0;r<rows; r++)
    for(int c=0;c<COLS;c++)
    if(avg > .1*)
}

/*void worst(float ary[][COLS], int rows)
{
    out << "\t\tWorst Salesmen:\n";
    
    for(int r=0;r<rows;r++)
    {
        out << ary[r][0];

        for(int c=0; c<MAXROWS;c++)
        {
            if(avg > total)
            {
                out << avg - total;
            }
            else
                out << "0.0";
        }
    }
}*/
void MonthlyHeader()
{
    out << "\t\tTotal Monthly Sales\n"
        << "January   February    March     April     May \t\tJune"
        << "    \tJuly   \tAugust  September  \tOctober  November  December\n";
}
void TotalMonthly(float ary[][COLS],int rows)
{
    for(int c=1; c<COLS-1;c++)
    {
        float total=0;

        for(int r=0; r<rows;r++)
        {
            total+=ary[r][c];
        }
        out  << total << " ";
    }
    out << endl;
}

int main()
{
    inf.open("Wildin.txt");
    if(!inf)
        cout << "error opening file";

    out.open("Wildout.txt");

    float salesmen[MAXROWS][COLS],total;
	int rows;

    rows = read(salesmen);
    header();
    print(salesmen, rows);
    sum(salesmen,rows);
    averages(salesmen, rows);
    MonthlyHeader();
    TotalMonthly(salesmen, rows);

   return 0;
}

I understand I am missing things such as prototypes, its still a work in progress.
OUTPUT:

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
|Salesman ID|   |Last Year's Avg|  |Current Monthly Sales|  |Current Year Avg(minus Lowest)
	2021			17353.20
	1178			26701.30
	5141			14267.20
	8347			20758.70
	6577			14371.70
	2617			20719.30
	2891			20793.20
	7538			12939.40
	2571			15701.60
	9872			18020.80
	5250			19350.80
	4422			18636.80
	1864			25219.70
231375.50 
267013.09 
171206.14 
226458.14 
172460.39 
248632.06 
207932.12 
172525.61 
157016.02 
196590.48 
232209.98 
248490.58 
275123.78 

19118.77 
21614.83 
13951.85 
18705.74 
14235.94 
20455.06 
17205.98 
14242.94 
12970.98 
15961.84 
19145.98 
20382.33 
21708.81 

		Total Monthly Sales
January   February    March     April     May 		June     July   	August  September  	October  November  December
227175.56 259368.69 240468.30 242611.91 217217.11 236757.36 241315.38 236814.31 243304.70 215930.61 188861.62 257208.44 
 
Last edited on
besides the numbers printing down the page instead of table format
Your sum(), averages(), bonus() and worst() functions should compute and return whatever value(s) they compute for a single salesman. All of the printing should occur inside the print() function, which can call the others as needed.

IE: total+= ary[r][c]-small;
No, that math is wrong.
- You are subtracting small each time you add to the sum, so you're subtracting small 12 times instead of once.
- and when you're subtracting it, small is the smallest value seen so far, not the smallest of the 12 months.
- and after you subtract the smallest month, the average is the sum divided by 11, not 12. This is because you're removing the smallest month from the calculation.

You can avoid confusion with some comments in your code.
1
2
3
// Compute the sum of all months, and the month with the worst (smallest) value
// Compute the average of all months except the worst one
double avg = (sum - smallest) / 11;


Can you tell me why when I call the function within a function it prints the same number over and over. But when i use the out statement within the sum and averages function it prints the correct totals.
Please be more specific. When you call what function within which function? I (and I think others here) are happy to answer your questions, but I'm not willing to spend time trying to figure out what the question is :)

What I can say is what I said above: create functions to compute and return some of the data that you need. Then call those functions inside your print function. In the first table, you need to print:
1
2
3
4
5
// - ID,
// - his last year’s average monthly sales,
// - the current year’s monthly sales,
// - the current year’s average monthly sales minus his worst month
// - whether they have 10% increase 

The ID, last years, average and current year's sales are all in the data.
Current year's average sales minus worst month needs to be computed:
1
2
3
// Compute and return the average monthly sales, excluding the worst month
// for ONE salesman
double avgWithoutWorst(float one[COLS]);


You also need to compute whether they get a bonus
// Given the data for ONE salesman, return true if they get a bonus (whether they have
// a 10% increase over previous year
bool getsBonus(float one[COLS]);

I attempted to write the function, but i immediately became confused.
Like I said, comments go a very long way to avoiding confusion. Write comments to say what a function or block of code should do.

By the way, the assignment says you should print "the current year's monthly sales." Does that mean the sales for each month, or the current year's average monthly sales? Taken literally, it means the sales for each month. But the assignment also says you'll need to compute the 12-month average. I suggest that you have the professor clarify.
Hello CodeNovice01,

There are so many things wrong with your code I am not sure just where to begin.

First there is everything that dhayden has said.

Then I will just start at the beginning.

const int MAXROWS = 25, COLS = 14;

Understand first that when someone posts code to show you something it is most likely not going match what you have done. Variable names may be different and something like "MAXROWS" may have a value that is incorrect. Changes are for you to figure out and make.

Be consistent. If you are going to change "ROWS" to "MAXROWS" then change "COLS" to "MAXCOLS". You are the one saying how confused you are, so remove the confusion. A proper variable name can go a long way at making the code easier to understand and removing some of the confusion. It is less work to see "row" and understand its meaning than to take the time to think about what "r" means.

Defining the "ifstream" and "ofstream" as global variables is a bad idea. Again this just adds to your confusion because of the way you are using the two streams.

The "ifstream" should be defined and used in the "read" function. And when the function ends the stream is closed when the function looses scope. Which is fine because the stream is no longer needed.

Many would tell you that a function should do one thing and do it well. Returning a value if needed or if more than one variable needs to be changed then you could pass the variable by reference to keep the change.

Your "read" function is very similar to what dutch posted in http://www.cplusplus.com/forum/beginner/267497/#msg1151105 You should compare what you are using to what he originally wrote and find what you are missing in the code you have used. I do not believe that the if statement will ever become true because the for condition will end before "r" is ever equal to "MAXROWS", which is (25) and should be (15). And if it should ever become true before the for loop condition is finished reading the file you would print out the error message and continue processing the inner for loop which would try to write to memory beyond the boundary of the array.

For the "print" function you should define and open the "ofstream" here then if you need the "header" function call it from "print" passing the "ofstream" to the "header" function for use. Again this will cut down on the confusion because you are printing everything that you need from one function and not in several places. Thus giving you more control of how it is printer to the file or the screen.

Using the "\t" in the "print " function may appear to be easy, but be warned that the "\t" does not always space out properly as you may wnat. You have included "iomanip" in your program. You need to make use of the "std::setw()" from this file. This will make a big difference when spacing out the table information. http://www.cplusplus.com/reference/iomanip/setw/

In the "sum" function you are trying to do two different things here sum and output. The function should only do the sum and leave the output for the "print" function where you have better control over the output.

The next problem is that the "sum" function is adding up the entire array and not the single row that you need. Using what you have the function would work better and be less confusing as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
float sum(float(&ary)[MAXROWS][COLS], const int ROW)
{
	float total = 0;

	for (int col = 1; col < COLS - 1; col++)
	{
		total += ary[ROW][col];
	}

	// <--- These should be in the "print" function.
	//out << total << " \n";

	//out << endl;

	return total;
}

The point of making "ROW' a constant variable and using capital letters is because this variable should never be changed in the function only used.

This same concept should be used in the "average" function.

It can not be stressed enough that you should work in small steps and not try to do everything at once. When I was working on this output, what i did first, I started with:



                                                           Total Monthly Sales
--------------------------------------------------------------------------------------------------------------------------
       Last
       Years
  ID  Average  January  February   March   April     May      June     July    August  September October November December
--------------------------------------------------------------------------------------------------------------------------
 2021 17353.20 15371.70 31660.10  1950.28 25420.30 26744.20 29213.90  8022.51 30317.70 12677.90  2430.61 14591.50 32974.80


Once I had the headings and the numbers the way I wanted I changed the hard coded information I used for spacing to a nested for loop to print each row of the array. After that I added the functions I needed, one at a time, to achieve:



                                                           Total Monthly Sales
--------------------------------------------------------------------------------------------------------------------------------------------
       Last                                                                                                                  This
       Years                                                                                                                 Years   Worst
  ID  Average  January  February   March   April     May      June     July    August  September October November December  Average  Month
--------------------------------------------------------------------------------------------------------------------------------------------
 2021 17353.20 15371.70 31660.10  1950.28 25420.30 26744.20 29213.90  8022.51 30317.70 12677.90  2430.61 14591.50 32974.80 19280.42  1950.28


Adding the last two columns was very easy once I had something to work with.

You are worried about you function "bonus". Do Not be. Based on the code you have now everyone will have more than a 10% increase over last year, so everyone will be getting a bonus. Until the "sum" and "average" functions produce the correct numbers to work with you have no need for the "bonus" function right now.

I see no reason to cover the "bonus" function because you are not ready for it yet.

For the "worst" function you are trying to find the worst month in the entire array not the row that you need. This should be more like the "sum" function dealing with just one row not all the rows.

Andy

Edit:
Last edited on
Gentlemen, thank you again for the advice. I stayed up late working on it and I did alter things after my last reply to the forum. The professor wants us to claim the streams globally for right now, he's slowly building up to stuff.
How do I make the print function work as I need, to print the header information? I've tried to call the sum and average function but I get errors.
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
const int MAXROWS=25, COL=14;

int read(float[][COL]);
void print(float[][COL],int);
void header();
void sum(float[][COL],int);
void averages(float[][COL], int);
void TotalMonthly(float[][COL],int);
void worst(float[][COL],int,int&);
void MonthlyHeader();


ifstream inf;
ofstream out;


int read(float ary[][COL])
{
	int r=0;

    for(int id;inf >> id ;r++)
   {
	   if(r == MAXROWS)
		   cout << "Table Overflowed\n";

	   ary[r][0]=id;

        for(int c=1; c<COL ;c++)
        {
            inf >> ary[r][c];
        }
    }
    return r;
}

void header()
{
    out << "|Salesman ID|  " << " |Last Year's Avg| "
        << " |Current Monthly Sales| " << " |Current Year Avg(minus Lowest)\n";
}

void print(float ary[][COL], int rows)
{
	out << fixed;

    for(int r=0; r<rows; r++)
    {
		out << setprecision(0) << "\t"<< ary[r][0]
            << setprecision(2) << "\t\t\t" << ary[r][13]
            << endl;
    }
}

void sum(float ary[][COL], int rows)
{
    for(int r=0; r<rows;r++)
    {
        float total=0;

        for(int c=1;c<COL-1;c++)
        {
            total += ary[r][c];
        }
        out <<total <<" \n";
    }
    out << endl;
}
void averages(float ary[][COL],int rows)
{
    float year=12.0,n;

    for(int r =0; r<rows;r++)
    {
        float small=ary[r][1],sum=0;

        for(int c=1; c<COL-1; c++)
         {
             if(ary[r][c]<small)
             {
                 small=ary[r][c];
             }

            sum += ary[r][c];

            n=sum-small;
         }
        out << n/year << " \n";
    }
    out <<endl;
}
/*void bonus(float ary[][COL,int rows,float avg)
{
    out << "\t\tSalesmen Slated for Bonus: \n";
    for(int r=0;r<rows; r++)
    for(int c=0;c<COL;c++)
    if(avg > .1*)
}*/

/*void worst(float ary[][COL], int rows, int& smallestID)
{
    out << "\t\tWorst Salesmen:\n";
    float small=ary[0][1];
    smallestID=ary[0][0];

    for(int r=0;r<rows;r++)
    {
        if(ary[r][1]<small)
        {
            small=ary[r][1];
        }
        if(ary[r][0]<smallestID)
        {
            smallestID=ary[r][0];
        }
        out << small << " ";
    }
}*/
void MonthlyHeader()
{
    out << endl << setw(7) << "January" << setw(12) << "February" << setw(8) << "March" << setw(10) << "April"
        << setw(9) << "May" << setw(10) << "June" << setw(10) << "July" << setw(11) << "August" << setw(12)
        << "September" << setw(9) << "October" << setw(11) << "November" << setw(11) << "December\n";
}
void TotalMonthly(float ary[][COL],int rows)
{
    for(int c=1; c<COL-1;c++)
    {
        float total=0;

        for(int r=0; r<rows;r++)
        {
            total+=ary[r][c];
        }
        out  << total << " ";
    }
    out << endl;
}

int main()
{
    inf.open("Wildin.txt");
    if(!inf)
        cout << "error opening file";

    out.open("Wildout.txt");

    float salesmen[MAXROWS][COL],total;
	int rows,ID,IDs;

    rows = read(salesmen);
    header();
    print(salesmen, rows);
    sum(salesmen,rows);
    averages(salesmen, rows);
   // worst(salesmen,rows,IDs);
    MonthlyHeader();
    TotalMonthly(salesmen, rows);

   return 0;
}
Last edited on
Hello CodeNovice01,

While I work on the "print" function.

Given the output:

|Salesman ID|   |Last Year's Avg|  |Current Monthly Sales|  |Current Year Avg(minus Lowest)
	2021			17353.20
	1178			26701.30
	5141			14267.20
	8347			20758.70
	6577			14371.70
	2617			20719.30
	2891			20793.20
	7538			12939.40
	2571			15701.60
	9872			18020.80
	5250			19350.80
	4422			18636.80
	1864			25219.70


Under the heading "Current Monthly Sales" what is this suppose to Represent? The figures for each month? Or a total sales for the year?

Given the instructions

Print out each salesman’s ID, his last year’s average monthly sales, the current year’s monthly sales, the current year’s average monthly sales minus his worst month all in a table format (columns, headers, ect.).


This leads me to believe it should be the sales figures for each month. Unless i am missing something.

I could use a better idea of what you want here.

Andy
This has been a very frustrating thread. Andy has given you good advice, and I like to think that I have too. But you have ignored almost all of it.

Here is your latest code with some changes to help. I have modified the main function so that after opening the input and output files, it is simply:

1
2
3
4
5
6
    float salesmen[MAXROWS][COL];
    int rows;

    rows = read(salesmen);
    printTable1(salesmen, rows);
    printTable2(salesmen, rows);


See how simple that is? See how obvious each function is? Programming is like peeling an onion. This has peeled off the first layer. Now there are 3 functions to write. You've already written the first one (read()).

printTable1() prints its header and then the data. I suggest that you follow Andy's advice and add columns one-by-one to this table.

printTable2() also prints a header and then its data, but it calls another function to compute the monthly totals and store them in a new array. See calcMontlyTotals(). I think you just need to add code to format the results.

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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
const int MAXROWS=25, COL=14;

int read(float[][COL]);
void print(float[][COL],int);
void header();
void sum(float[][COL],int);
void averages(float[][COL], int);
void TotalMonthly(float[][COL],int);
void worst(float[][COL],int,int&);
void MonthlyHeader();


ifstream inf;
ofstream out;


int read(float ary[][COL])
{
	int r=0;

    for(int id;inf >> id ;r++)
   {
	   if(r == MAXROWS)
		   cout << "Table Overflowed\n";

	   ary[r][0]=id;

        for(int c=1; c<COL ;c++)
        {
            inf >> ary[r][c];
        }
    }
    return r;
}

void header()
{
    out << "|Salesman ID|  " << " |Last Year's Avg| "
        << " |Current Monthly Sales| " << " |Current Year Avg(minus Lowest)\n";
}

void printTable1(float ary[][COL], int rows)
{
    header();

    out << fixed;

    for(int r=0; r<rows; r++)
    {
	out << setprecision(0) << "\t"<< ary[r][0]
	     << setprecision(2) << "\t\t\t" << ary[r][13];
	// ADD CODE HERE TO PRINT ADDITIONAL COLUMNS
        out << endl;
    }
}

void sum(float ary[][COL], int rows)
{
    for(int r=0; r<rows;r++)
    {
        float total=0;

        for(int c=1;c<COL-1;c++)
        {
            total += ary[r][c];
        }
        out <<total <<" \n";
    }
    out << endl;
}
void averages(float ary[][COL],int rows)
{
    float year=12.0,n;

    for(int r =0; r<rows;r++)
    {
        float small=ary[r][1],sum=0;

        for(int c=1; c<COL-1; c++)
         {
             if(ary[r][c]<small)
             {
                 small=ary[r][c];
             }

            sum += ary[r][c];

            n=sum-small;
         }
        out << n/year << " \n";
    }
    out <<endl;
}
/*void bonus(float ary[][COL,int rows,float avg)
{
    out << "\t\tSalesmen Slated for Bonus: \n";
    for(int r=0;r<rows; r++)
    for(int c=0;c<COL;c++)
    if(avg > .1*)
}*/

/*void worst(float ary[][COL], int rows, int& smallestID)
{
    out << "\t\tWorst Salesmen:\n";
    float small=ary[0][1];
    smallestID=ary[0][0];

    for(int r=0;r<rows;r++)
    {
        if(ary[r][1]<small)
        {
            small=ary[r][1];
        }
        if(ary[r][0]<smallestID)
        {
            smallestID=ary[r][0];
        }
        out << small << " ";
    }
}*/

// Print the header for the second table
void table2Header()
{
    out << endl << setw(7) << "January" << setw(12) << "February" << setw(8) << "March" << setw(10) << "April"
        << setw(9) << "May" << setw(10) << "June" << setw(10) << "July" << setw(11) << "August" << setw(12)
        << "September" << setw(9) << "October" << setw(11) << "November" << setw(11) << "December\n";
}


// Given the salesmen array, calculate and store the monthly totals
void calcMonthlyTotals(float ary[][COL],int rows, float monthlyTotals[12])
{
    for(int c=1; c<COL-1;c++) {
        float total=0;

        for(int r=0; r<rows;r++) {
            total+=ary[r][c];
        }

	// Jan, Feb, Mar, ... are columns 1,2,3,... in ary,
	// but they are columns 0,1,2,... in monthlyTotals.
	// So to convert from ary index to monthlyTotals index,
	// subtract 1
	monthlyTotals[c-1] = total;
    }
}

// Print the second table
void printTable2(float ary[][COL], unsigned rows)
{
    float monthlyTotals[12];	// stores the montly totals

    // Store the monthly totals.
    calcMonthlyTotals(ary, rows, monthlyTotals);

    table2Header();		// print the table header

    // Now print the totals. I'm separating them with tabs for now
    for (unsigned i=0; i<12; ++i) {
	out << monthlyTotals[i] << '\t';
    }
}

int main()
{
    inf.open("Wildin.txt");
    if(!inf)
        cout << "error opening file";

    out.open("Wildout.txt");

    float salesmen[MAXROWS][COL];
    int rows;

    rows = read(salesmen);
    printTable1(salesmen, rows);
    printTable2(salesmen, rows);

    return 0;
}
This has been a very frustrating thread.

Something akin to an understatement.

OP is in obviously in denial and needs to take a break, deep breathe, review arrays, functions (for me, 'later' and start writing code that is planned even if it's just a scrabbly note on scrap paper and use simple statements with sensible self-documenting variable names.

Of course, checking the brief and making sure the arithmetic are things I haven't done - a privilege all mine :)

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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

const int NO_SALES_PEOPLE{15};
const int NO_SALES_PERIODS{13};

int main()
{
    int pers[NO_SALES_PEOPLE];
    double sales[NO_SALES_PEOPLE][NO_SALES_PERIODS];
    int COUNT{0};
    
    // READ IN THE DATA FROM A TEXT FILE
    std::ifstream in_file ("sales_in.txt");
    if (in_file.is_open())
    {
        while ( in_file >> pers[COUNT] )
        {
            for(int i = 0; i < NO_SALES_PERIODS; i++)
            {
                in_file >> sales[COUNT][i];
            }
            COUNT++;
        }
        in_file.close();
    }
    else
        {
            std::cout << "Unable to open file\n";
            return -1;
        }
    
    // PROCESS THE DATA
    // AVERAGE MONTHLY SALES & OTHER STATISTICS
    double year_average[NO_SALES_PEOPLE];
    double adjusted_average[NO_SALES_PEOPLE];
    double change[NO_SALES_PEOPLE];
    double sales_range[NO_SALES_PEOPLE][2];
    
    for(int i = 0; i < COUNT; i++)
    {
        sales_range[i][0] = sales[i][0];
        sales_range[i][1] = sales[i][0];
        
        year_average[i] = 0;
        for (int j = 0; j < NO_SALES_PERIODS - 1; j++)
        {
            if( sales[i][j] > sales_range[i][1] )
                sales_range[i][1] = sales[i][j];
            
            if( sales[i][j] < sales_range[i][0] )
                sales_range[i][0] = sales[i][j];
            
            year_average[i] += sales[i][j];
        }
        year_average[i] /= (NO_SALES_PERIODS - 1);
        
        // CHANGE SINCE LAST YEAR
        change[i] =
        100. * (year_average[i] - sales[i][NO_SALES_PERIODS - 1])
        /sales[i][NO_SALES_PERIODS - 1];
        
        // ADJUSTED AVERAGE
        adjusted_average[i] =
        (year_average[i]* NO_SALES_PERIODS - sales_range[i][0]
         + sales_range[i][1])/(NO_SALES_PERIODS - 1);
    }
    
    // DISPLAY NUMBER OF STAFF
    std::cout << '\n';
    std::cout << "THERE ARE CURRENTLY " << COUNT << " SALES STAFF\n\n";
    
    // DISPLAY DATA AS READ IN
    std::string heading_1a
    {"No:     ID      JAN      FEB      MAR      APR      MAY      JUN      "};
    std::string heading_1b
    {"JUL      AUG      SEP      OCT      NOV      DEC  PREV_AV"};
    std::string heading_1 = heading_1a + heading_1b;
    
    std::cout << "DATA AS READ IN FROM TEXT FILE\n";
    std::cout << heading_1 << '\n';
    
    for(int i = 0; i < COUNT; i++)
    {
        std::cout << std::setw(3) <<  i << std::setw(7) << pers[i];
        for(int j = 0; j < NO_SALES_PERIODS; j++)
        {
            std::cout << std::right << std::setw(9) << sales[i][j];
        }
        std::cout << '\n';
    }
    std::cout << '\n';
    
    // DISPLAY VARIOUS STATISTICS
    std::string heading_2
    { "No:    ID  PREV_AV  CURR_AV  %CHANGE      MIN      MAX   ADJ_AV"};
    
    std::cout << "PROCESSING THE DATA\n";
    std::cout << heading_2 << '\n';
    for(int i = 0; i < COUNT; i++)
    {
        std::cout
        << std::setw(3) << i << std::setw(6) << pers[i]
        << std::setw(9) << std::right << sales[i][NO_SALES_PERIODS - 1]
        << std::setw(9) << std::right << year_average[i]
        << std::fixed << std::setprecision(2) << std::setw(9) << std::right
        << change[i]
        << std::setw(9) << std::right << sales_range[i][0]
        << std::setw(9) << std::right << sales_range[i][1]
        << std::setw(9) << std::right << adjusted_average[i] << '\n';
    }
    
    //in_file.close();
    return 0;
}


THERE ARE CURRENTLY 13 SALES STAFF

DATA AS READ IN FROM TEXT FILE
No:     ID      JAN      FEB      MAR      APR      MAY      JUN      JUL      AUG      SEP      OCT      NOV      DEC  PREV_AV
  0   2021  15371.7  31660.1  1950.28  25420.3  26744.2  29213.9  8022.51  30317.7  12677.9  2430.61  14591.5  32974.8  17353.2
  1   1178  27352.5  28583.3  30570.9  23609.4    20661    33381  16392.5  19339.5  31867.9  16165.2   7635.1  11454.8  26701.3
  2   5141  22977.5  9582.07  3783.97   7096.1  31259.8  9007.33  15359.9  8655.28  19197.6  10245.3  19846.7  14194.6  14267.2
  3   8347  11046.2  1989.22  28403.4  12368.8    26048  20386.1  25574.2  11926.6  22469.5  33300.9  3614.23    29331  20758.7
  4   6577  1629.14  20494.8  11973.8  3306.99  28215.4  2634.61  15626.3  33516.4  10389.7  20598.9  17999.3  6075.04  14371.7
  5   2617  27756.7  24807.3  27176.1  29743.2  28108.3  5430.77  23123.1  3171.31  30190.3  24862.2   4078.1  20184.7  20719.3
  6   2891  29704.7  16901.2  31960.8  26913.6  5122.53  21332.8  10371.1  9008.73  2575.58  33699.6  1460.37  18881.1  20793.2
  7   7538  2255.97  14672.2  17505.8  24828.5  1610.38  20239.8  2482.95  24967.5  13105.6  28000.7  10293.9  12562.3  12939.4
  8   2571  2498.33    15681  1364.25  12879.4  10246.7  8742.04  23562.4  16441.1  9474.13  1743.16  30240.8  24142.7  15701.6
  9   9872  25349.7  15479.5    20428  32086.9  9661.93  15055.7  18367.5  13452.4  25951.5  7719.95  5048.39     7989  18020.8
 10   5250  32475.2  30367.7  32545.2  2458.19  8096.35  14861.1  28754.7  19290.8  8278.71  15156.3  7571.34  32354.4  19350.8
 11   4422  10716.9  25222.7  12523.2  21708.5  3902.61  26446.3  25864.2    32109  32603.6  4215.98  33425.3  19752.3  18636.8
 12   1864    18041  23927.6  20282.6    20192  17539.9  30025.9    27814    14618  24522.7  17791.8  33056.6  27311.7  25219.7

PROCESSING THE DATA
No:    ID  PREV_AV  CURR_AV  %CHANGE      MIN      MAX   ADJ_AV
  0  2021  17353.2  19281.3    11.11  1950.28 32974.80 23473.44
  1  1178 26701.30 22251.09   -16.67  7635.10 33381.00 26250.84
  2  5141 14267.20 14267.18    -0.00  3783.97 31259.80 17745.76
  3  8347 20758.70 18871.51    -9.09  1989.22 33300.90 23053.45
  4  6577 14371.70 14371.70    -0.00  1629.14 33516.40 18226.61
  5  2617 20719.30 20719.34     0.00  3171.31 30190.30 24697.53
  6  2891 20793.20 17327.68   -16.67  1460.37 33699.60 21458.25
  7  7538 12939.40 14377.13    11.11  1610.38 28000.70 17774.42
  8  2571 15701.60 13084.67   -16.67  1364.25 30240.80 16581.44
  9  9872 18020.80 16382.54    -9.09  5048.39 32086.90 20000.96
 10  5250 19350.80 19350.83     0.00  2458.19 32545.20 23470.65
 11  4422 18636.80 20707.55    11.11  3902.61 33425.30 24893.40
 12  1864 25219.70 22926.98    -9.09 14618.00 33056.60 26374.12
Program ended with exit code: 0
Last edited on
As I do read what you all post, my understanding may not be on par with the lot of you. I'm very simple and I understand you all are frustrated with my lack of knowledge or whatever else there is. I am trying, I have a very busy day to day just like you.

I don't understand this material as well as you all. As I do appreciate all the input, I don't understand certain things you may type as syntax( because it's different from what I am CURRENTLY being taught) or I may not understand your semantics(because its new and I may not have studied that section within my text).

I'm not going to school to be a coder, it's my least favorite of my courses I have to take, but I have to take them. Please bare with me while I struggle along trying to understand. Just so you know, I have a brain injury from active service, so that can play a role at times.

I have tinkered with the program and I have gotten significantly further than I had expected after receiving some help on campus. My only issues now are the "Worst" function is printing the same 3 numbers 13 times and I can't get my "TotalMonthly" to print correctly when I call it within the function "PrintTotalMonthly", but if I use the out statement within the TotalMonthly my answers are correct, but as soon as I call it from PrintTotalMonthly my answers begin with 0 and fill the rest with junk.

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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
const int MAXROWS=25, COL=14;

int read(float[][COL]);
void print(float[][COL],int);
void header();
float sum(float[][COL],int);
float AverageMinusLowest(float[][COL], int);
float Average(float[][COL], int);
float TotalMonthly(float[][COL],int);
string bonus(float[][COL], int);
float worst(float[][COL],int);
void MonthlyHeader();
void PrintTotalMonthly(float[][COL],int);


ifstream inf;
ofstream out;


int read(float ary[][COL])
{
	int r=0;

    for(int id;inf >> id ;r++)
   {
	   if(r == MAXROWS)
		   cout << "Table Overflowed\n";

	   ary[r][0]=id;

        for(int c=1; c<COL ;c++)
        {
            inf >> ary[r][c];
        }
    }
    return r;
}

void header()
{
    out << "|Salesman ID|  "
        << " |Last Year's Avg| "
        << " |Current Monthly Sales| "
        << " |Current Year Avg(minus Lowest)|"
        << " |Bonus|"
        << " |Worst Salesman|\n";
}

void print(float ary[][COL], int rows)
{
	out << fixed;

    for(int r=0; r<rows; r++)
    {
		out << fixed << setprecision(0) << setw(10) << ary[r][0]
            << setprecision(2) << setw(20) << ary[r][13]
            << setw(20) << sum(ary,r)
            << setw(25) << AverageMinusLowest(ary,r)
            << setw(23) << bonus(ary,r)
            << setprecision(0) << setw(20) << worst(ary,r)
            << endl;
    }
}

float sum(float ary[][COL], int rows)
{   float total=0;

    for(int c=1; c<COL-1;c++)
    {
        total += ary[rows][c];
    }
    return total;
}

float Average(float ary[][COL], int rows)
{
    float year=12.0, avg, sum=0;

    for(int c=1; c<COL-1; c++)
    {
        sum += ary[rows][c];
        avg= sum/year;
    }
    return avg;
}

float AverageMinusLowest(float ary[][COL],int rows)
{
    float year=11.0, n, small=ary[rows][1], sum=0;

    for(int c=1; c<COL-1; c++)
         {
             if(ary[rows][c]<small)
             {
                 small=ary[rows][c];
             }
            sum += ary[rows][c];

            n=sum-small;
         }
    return n/year;
}

string bonus(float ary[][COL],int rows)
{
    if(Average(ary,rows)-ary[rows][COL-1] >= (ary[rows][COL-1] * .1))
        return "YES";
    else
        return "NO";
}

float worst(float ary[][COL], int rows)
{
    float WorstSales = ary[0][0],
    WorstAverage = (ary[0][COL-1] + Average(ary,0) /2);

    for(int r=0; r<rows; r++)
        if(((ary[r][COL-1] + Average(ary,r)) /2) < WorstAverage)
        {
            WorstAverage = (ary[r][COL-1] + Average(ary,r)) /2;
            WorstSales = ary[r][0];
        }
    return WorstSales;
}

void MonthlyHeader()
{
    out << endl << setw(7) << "January" << setw(12) << "February" << setw(8) << "March" << setw(10) << "April"
        << setw(9) << "May" << setw(10) << "June" << setw(10) << "July" << setw(11) << "August" << setw(12)
        << "September" << setw(9) << "October" << setw(11) << "November" << setw(11) << "December\n";
}



float TotalMonthly(float ary[][COL],int rows)
{
    for(int c=1; c<COL-1;c++)
    {
        float total=0;

        for(int r=0; r<rows;r++)
        {
            total+=ary[r][c];
        }
        //out << total << "   ";
       return total;
    }
   // out << endl;
}

void PrintTotalMonthly(float ary[][COL], int rows)
{
    for(int r=0; r<rows; r++)
    {
        out << setprecision(2) << fixed
            << TotalMonthly(ary,r) << "  ";

    }
}

int main()
{
    inf.open("Wildin.txt");
    if(!inf)
        cout << "error opening file";

    out.open("Wildout.txt");

    float salesmen[MAXROWS][COL],total;
	int rows;

    rows = read(salesmen);
    header();
    print(salesmen, rows);
    MonthlyHeader();
    total = TotalMonthly(salesmen,rows);
    PrintTotalMonthly(salesmen, rows);

   return 0;
}
OUTPUT:
[code]
|Salesman ID|   |Last Year's Avg|  |Current Monthly Sales|  |Current Year Avg(minus Lowest)| |Bonus| |Worst Salesman|
      2021            17353.20           231375.50                 20856.84                    YES                2021
      1178            26701.30           267013.09                 23579.82                     NO                2021
      5141            14267.20           171206.14                 15220.20                     NO                2021
      8347            20758.70           226458.14                 20406.27                     NO                5141
      6577            14371.70           172460.39                 15530.11                     NO                5141
      2617            20719.30           248632.06                 22314.61                     NO                5141
      2891            20793.20           207932.12                 18770.16                     NO                5141
      7538            12939.40           172525.61                 15537.75                    YES                5141
      2571            15701.60           157016.02                 14150.16                     NO                7538
      9872            18020.80           196590.48                 17412.92                     NO                7538
      5250            19350.80           232209.98                 20886.53                     NO                7538
      4422            18636.80           248490.58                 22235.27                    YES                7538
      1864            25219.70           275123.78                 23682.34                     NO                7538

January    February   March     April      May      June      July     August   September  October   November  December
0.00  15371.70  42724.20  65701.70  76747.91  78377.05  106133.75  135838.45  138094.42  140592.75  165942.45  198417.66  209134.56   

[/code]
Much better! I don't have time right now to track down the remaining bugs but I promise I will.
Hello CodeNovice01,

You have made some great progress with your code. There are still some changes that would help.

againtry wrote:
use simple statements with sensible self-documenting variable names.
The "self-documenting variable names. can not be stressed enough. Understanding your problems better now this would help you to be less confusing when writing code. I will keep changing variable names until you grasp the concept. The repetition should help.

In your "print" function you have the line: << setw(20) << bonus(ary, r). In order to print this return value of the function you need to include the header file "<string>" for this to work. What you do not see is the return value of the function is stored in a tempary variable made by the compiler which the "out" or "cout" uses to print the value. Without the "<string>" header file "out" or "cout" does not know what to do with this variable. So I put #include <string> after <iomanip>.

A personal note: I found that putting the include files in alphabetical order helps to remind you if you have missed something. My exception here is:
1
2
#include <iostream>
#include <iomanip> 

Since there is no point for including "iomanip" without "iostream" it seemed the most logical order. technically speaking the order of the include files should make no difference. On a rare occasion it does.

Your "read function could use a couple of changes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int read(float ary[][COL])
{
	int row = 0;

	for (int id; inf >> id; row++)
	{
		if (row == MAXROWS)
		{
			cout << "Table Overflowed\n";
			break;
		}

		ary[row][0] = id;

		for (int c = 1; c < COL; c++)
		{
			inf >> ary[row][c];
		}
	}
	               // <--- Added blank line.
	return row;
}

The if statement is the biggest change. You have copied from what dutch posted early on, but you did not get all of it.

Without the {}s and "break" statement if the if statement ever becomes true you will print the error message, but continue on with the for loops and that is not what you want.

Your "print" function should start more like this for now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void print(float ary[][COL], const int ROWS)
{
	out << fixed;

	header(); // <--- Moved here.

	for (int row = 0; row < ROWS; row++)
	{
		out << fixed << setprecision(0) << setw(10) << ary[row][0]
			<< setprecision(2) << setw(20) << ary[row][13]
			<< setw(20) << sum(ary, row)
			<< setw(25) << AverageMinusLowest(ary, row)
			<< setw(20) << bonus(ary, row)
			<< setprecision(0) << setw(20) << worst(ary, row) // <--- setw value may need to be reduced.
			<< endl;
	}
}

This should work better for you as a start. There will be more that is needed in this function.

The "average" function is OK for the most part, but could be reduced to this:
1
2
3
4
5
6
7
8
9
10
11
12
float Average(float ary[][COL], const int ROW)
{
	const float YEAR = 12.0;
	float sum = 0;

	for (int col = 1; col < COL - 1; col++)
	{
		sum += ary[ROW][col];
	}

	return sum / YEAR;
}

By putting the line avg= sum/year; This may work, but it is not the best way to do it. I have seen code done your way produce the wrong answer.

After thinking about it the function could be shortened to just this:
1
2
3
4
5
6
float Average(float ary[][COL], const int ROW)
{
	const float YEAR = 12.0;

	return (sum(ary, ROW) / YEAR);
}

You already have the function that sums the row you do not need to duplicate code that you already have just use it.

First the function sum is called then divided by YEAR before the answer is returned.

It is always a good idea to use what you have rather then duplicating code. The same concept can be used in other functions.

For this function you could do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
float AverageMinusLowest(float ary[][COL], const int ROW)
{
	const float YEAR = 11.0;
	float small = ary[ROW][1], sum = 0;

	for (int col = 1; col < COL - 1; col++)
	{
		if (ary[ROW][col] < small)
		{
			small = ary[ROW][col];
		}

		sum += ary[ROW][col];
	}

	return ((sum - small) / YEAR);
}


Or shortened:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
float AverageMinusLowest(float ary[][COL], const int ROW)
{
	const float YEAR = 11.0;
	float small = ary[ROW][1], arySum = sum(ary, ROW);

	for (int col = 1; col < COL - 1; col++)
	{
		if (ary[ROW][col] < small)
		{
			small = ary[ROW][col];
		}
	}

	return ((arySum - small) / YEAR);
}

I had to change the variable name "sum" because it was a conflict with the function call "sum".

"bonus" can be done like this:
1
2
3
4
5
6
7
string bonus(float ary[][COL], int rows)
{
	if (Average(ary, rows) - ary[rows][COL - 1] >= (ary[rows][COL - 1] * .1))
		return "YES";

	return "NO";
}

When the if statement is true "yes" is returned and the rest of the function is skipped. When the if statement is false the only thing left to return is "no". Just because you have an if statement the else statement is not always required.

The worst function I am still trying to figure out, but I do see the way you are using it is wrong. The column for "Worst Salesman" should only have one ID number in it or should be printed as one line after the table. But the instructions allude to it being part of the table.

In the "" function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
float TotalMonthly(float ary[][COL], int rows)
{
	float total{};

	for (int c = 1; c < COL - 1; c++)
	{
		for (int r = 0; r < rows; r++)
		{
			total += ary[r][c];
		}
	}

	return total;
}

I think this is a better start although I have not worked with it yet to know if it is correct. What I can see is the you are returning "total" to soon. This should be done after the for loops not inside the outer for loop. And "total" should be defined outside the for loops so you have something to return at the end.

As for "PrintTotalMonthly" I have not worked to that part yet, so I do not know exactly what it is printing or when.

Over all good job. You have made improvements and advancements. Let's hope you can remember them and nor fall backwards.

In the mean time I will keep working on what you have done and let you know what I have come up with.

Andy
Pages: 123