2D - Array - User input - Nested For Loops

Jul 22, 2018 at 6:43am
I am calling a function getsales - asking for the elements to fulfill a 2D array using FOR loops.

I was getting errors compiling for quarter and column count not being declared in the section *thus their location / "double definition?"*

I am only asked for a single input from the quarter section, and the table display is with random numbers.





getSales(SalesType table, int& numOfYears)
{
cout << "Please input the number of years (1-" << MAXYEAR << ")" << endl;
cin >> numOfYears;

int quarter = 0;
int columncount = 0;

for (int count = 0, displaycount =1; count < numOfYears; count++, displaycount++)
{
cout << "Input year " << displaycount << " (e.g. 2004)" << endl;
cin >> table[count][0];

for (int quarter = 0, columncount = 1; quarter < MAXCOL; quarter++, columncount++);
{
cout << "Input the sales figures for the " << columncount << " Quarter: Year " << table[count][0] << endl;
cin >> table[count][quarter];
}
cout << endl;
}
// Fill in the code to read and store the next value
}
Jul 22, 2018 at 1:16pm
Hello b3y0nd,

Welcome to the forum.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

Your function looks nice, but without the rest of the program to see what you did the function alone lacks information.

What is "SalesType"? And why is "table"passed as a regular variable instead of an array?

Other than "table" being a regular variable that you are trying to access as an array that is a big problem I need more information to see what you are doing.

This article may be of some use to you http://www.cplusplus.com/forum/articles/20881/

Happy to help you figure this out when I have more to work with.

Hope that helps,

Andy
Jul 22, 2018 at 5:03pm
I will look into posting the code. Just checked the forum to see if I got a response, figured I would copy paste this code in.

// This program will read in the quarterly sales transactions for a given number
// of years. It will print the year and transactions in a table format.
// It will calculate year and quarter total transactions.



#include <iostream>
#include <iomanip>
using namespace std;

const int MAXYEAR = 10;
const int MAXCOL = 5;

typedef int SalesType[MAXYEAR][MAXCOL]; // creates a new 2D integer data type

void getSales(SalesType, int&); // places sales figures into the array
void printSales(SalesType, int); // prints data as a table
void printTableHeading(); // prints table heading

int main()
{
int yearsUsed; // holds the number of years used
SalesType sales; // 2D array holding the sales transactions

getSales(sales, yearsUsed); // calls getSales to put data in array
printTableHeading(); // calls procedure to print the heading
printSales(sales, yearsUsed); // calls printSales to display table

return 0;
}

//*****************************************************************************
// printTableHeading
//
// task: This procedure prints the table heading
// data in: none
// data out: none
//
//*****************************************************************************

void printTableHeading()
{
cout << setw(30) << "YEARLY QUARTERLY SALES" << endl << endl << endl;

cout << setw(10) << "YEAR" << setw(10) << "Quarter 1"
<< setw(10) << "Quarter 2" << setw(10) << "Quarter 3"
<< setw(10) << "Quarter 4" << endl;
}

//*****************************************************************************
// getSales
//
// task: This procedure asks the user to input the number of years.
// For each of those years it asks the user to input the year
// (e.g. 2004), followed by the sales figures for each of the
// 4 quarters of that year. That data is placed in a 2D array
// data in: a 2D array of integers
// data out: the total number of years
//
//*****************************************************************************

void getSales(SalesType table, int& numOfYears)
{
cout << "Please input the number of years (1-" << MAXYEAR << ")" << endl;
cin >> numOfYears;

int quarter = 0;
int columncount = 0;
int val=0;

for (int count = 1, displaycount =1; count <= numOfYears; count++, displaycount++)
{
cout << "Input year " << displaycount << " (e.g. 2004)" << endl;
cin >> val;
table[count][0] = val;

for (int quarter = 0, columncount = 1; quarter < MAXCOL; quarter++, columncount++);
{
cout << "Input the sales figures for the " << columncount << " Quarter: Year " << table[count][0] << endl;
cin >> val;
table[count][quarter] = val;
}
cout << endl;
}
// Fill in the code to read and store the next value
}

//*****************************************************************************
// printSales
//
// task: This procedure prints out the information in the array
// data in: an array containing sales information
// data out: none
//
//*****************************************************************************

void printSales(SalesType table, int numOfYears)
{
for (int count = 0; count < numOfYears; count++)
{
cout << table[count];
for (int quarter = 0; quarter < MAXCOL; quarter++)
{
cout << table[count][quarter] << "\t";
}
cout << endl;
}
}
Jul 22, 2018 at 6:25pm
Hello b3y0nd,

Again PLEASE USE CODE TAGS. Along with proper indenting it makes your code easier to read.

The header files are OK as best as I can tell. They are the same as what I used to test the original function.

"using namespace std" should be avoided at all times. It WILL get you in trouble some day. There are many posts here on this subjece and this is helpful http://www.lonecpluspluscoder.com/2012/09/22/i-dont-want-to-see-another-using-namespace-xxx-in-a-header-file-ever-again/

I understand your use of the typedef, but I would consider making it a "double" instead of the "int" since the numbers are likely in dollars and cents.

I still have a problem wiith the "getSales" function. The use os global variables in the function and then local variables of the same name will work, but local variables will over shadow the global variables causing a problem. If you need these global variables for later it may be better to define them in main and pass them to the function like you did with "numOfYears". If you need these global variables to hold a number change inside the for loop not inside the () of the for condition. Keep in mind that anything defined in the () after "for" is a local to the for loop and disappears after the for loop ends.

At the end of the "getSales" function you have this comment // Fill in the code to read and store the next value . Not sure what you have in mind here, but you really should not add anything else here. The function should do one thing.

With a slight change to the "typedef", after seeing what you did, and the array in main that I setup for testing I redid the code for "getSales" and added a function to print the array. Thi may not be what you want, but, at least, you can use it for ideas.

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
#include <iostream>
#include <iomanip>

constexpr size_t MAXYEAR{ 10 };
constexpr size_t MAXQUARTER{ 4 };
constexpr size_t MAXROW{ 10 };
constexpr size_t MAXCOL{ 5 };

typedef double SalesType[MAXROW][MAXCOL];

void getSales(SalesType table, int& numOfYears);
void GetSales(SalesType table, int& numOfYears);
void PrintTable(const SalesType table, const int numOfYears);

int main()
{
	SalesType table
	{
		{2000, 10256.25, 15872.49, 20273.91, 25456.85},
		{2001, 11987.61, 16573.42, 21357.75, 26951.95}
	};
	int numOfYears{ 2 };

	//GetSales(table, numOfYears);
	PrintTable(table, numOfYears);

	// The next line may not be needid. If you have to press enter to see the prompt it is not needed.
	//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue";
	std::cin.get();

	return 0;
}

//  <--- This function has problems.
void getSales(SalesType table, int& numOfYears)
{
	std::cout << "Please input the number of years (1 -" << MAXYEAR << "): ";
	std::cin >> numOfYears;

	int quarter = 0;
	int columncount = 1;

	for (int count = 0, displaycount = 1; count < numOfYears; count++, displaycount++)
	{
		std::cout << "\nInput year " << displaycount << " (e.g. 2004): ";
		std::cin >> table[count][0];

		for (int quarter = 1/*, columncount = 1*/; quarter <= MAXQUARTER; quarter++/*, columncount++*/);
		{
			std::cout << "Input the sales figures for the " << columncount << " Quarter Year " << table[count][0] << ": ";
			std::cin >> table[count][quarter];
			columncount++;
		}
		std::cout << std::endl;
	}
	// Fill in the code to read and store the next value
}

// <--- New function does same as above.
void GetSales(SalesType table, int& numOfYears)
{
	std::cout << "Please input the number of years (1 -" << MAXYEAR << "): ";
	std::cin >> numOfYears;

	for (int row = 0; row < numOfYears; row++)
	{	
		std::cout << "\nInput year " << row + 1 << " (e.g. 2004): ";
		std::cin >> table[row][0];  // <--- Used to store the year in column 0.

		for (size_t col = 1; col <= MAXQUARTER; col++)  // <--- Starts at 1 to store the data in the proper column. Starting at 0 would overwrite the year.
		{
			std::cout << "Input the sales figures for the " << col << " Quarter Year " << table[0][0] << ": ";
			std::cin >> table[row][col];
		}
	}
}

// <--- Added for testing.
void PrintTable(const SalesType table, const int numOfYears)
{
	int year{};
	std::cout << std::fixed << std::showpoint << std::setprecision(2);

	for (int row = 0; row < numOfYears; row++)
	{	
		year = table[row][0];

		std::cout << "\n Year " << year << std::endl;
		std::cout << "1st Qtr   2nd Qtr   3rd Qtr   4th Qtr" << std::endl;

		for (size_t col = 1; col <= MAXQUARTER; col++)
		{
			std::cout << std::setw(8) << table[row][col] << "  ";
		}

		std::cout << std::endl;
	}
}

Note: for classes, structs and functions I like to start these names with a capital letter. This shows a difference between a regular variable name and something different.

Notice also that I used the names "MAXQUARTER" and "MAXROW" for better clarity and readability.

I still need to test your complete code. I will let you know what I find.

Hope that helps,

Andy
Jul 22, 2018 at 8:56pm
Hey Andy.

Appreciate the help.

I copied and pasted the code, as I was in a rush out this morning, hoping to get a response before sitting for another frustrating session.

This is the complete program. I will take a look and post, in regards to its functionality and my understanding of the process of code.

Thanks
Jul 22, 2018 at 9:37pm
Hello b3y0nd,

First I worked with the output, I am kind of pickey when it comes to that, Then I worked on the "getSales" function which has always been a problem.

After changing some things around I found the big problem. The inner for loop ends with a semicolon and it should not. what was happening is that the for loop was working properly and the following block of code was only executed once. Removing the semicolon allowed the block of code to be part of the for loop.

In the outer for loop "count" has to start at zero and "quarter" in the inner for loop has to start at 1.

I also found that "quarter" and "coloumncount", the global variables, of the function are not needed. Once the block of code following the inner for loop becomes part of the for loop "coloumncount" can be replaced with "quantity" which is local to the for loop.

Based on the changes I made this is the output I get:

Please input the number of years (1 -10): 2

Input year 1 (e.g. 2004): 2000
Input the sales figures for the 1 Quarter: Year 2000 10256.25
Input the sales figures for the 2 Quarter: Year 2000 15567.91
Input the sales figures for the 3 Quarter: Year 2000 20753.15
Input the sales figures for the 4 Quarter: Year 2000 25642.75


Input year 2 (e.g. 2004): 2001
Input the sales figures for the 1 Quarter: Year 2001 11491.54
Input the sales figures for the 2 Quarter: Year 2001 16657.42
Input the sales figures for the 3 Quarter: Year 2001 21841.73
Input the sales figures for the 4 Quarter: Year 2001 26345.27



                            YEARLY QUARTERLY SALES

    YEAR        Quarter  1       Quarter  2      Quarter  3      Quarter  4
    2000         10256.25         15567.91        20753.15        25642.75
    2001         11491.54         16657.42        21841.73        26345.27

As you can see I made some changes to the output of the "printTableHeading" function and the "printSales" function.

For the most part the program works it just needs a little refinement.

Hope that helps,

Andy
Jul 22, 2018 at 11:40pm
Andy

Thank you much.

Hope to so your links, responses and expertise in future posts of
Jul 23, 2018 at 2:17am
Hey Andy.

I am using Visual Studio for C++.

Do you have another recommendation?


============CODE START===========

#include <iostream>
#include <iomanip>

using namespace std;

const int TOTALYEARS = 100;
int main()
{
int ageFrequency[TOTALYEARS]; //reserves memory for 100 ints
int currentAge;
for (int pos = 0; pos < TOTALYEARS; pos++)
// pos acts as the array subscript
{
ageFrequency[pos] = 0;
}

cout << "Please input an age from one to 100. Input -99 to Stop" << endl;
cin >> currentAge;

while (currentAge != -99)
{
ageFrequency[currentAge - 1] = ageFrequency[currentAge - 1] + 1;
cout << "Please input an age from one to 100. Input -99 to Stop" << endl;
cin >> currentAge;
}

for (int ageCounter = 0; ageCounter < TOTALYEARS; ageCounter++)
if (ageFrequency[ageCounter] > 0)
{
cout << "The number of people " << ageCounter + 1 << " years old is "
<< ageFrequency[ageCounter] << endl;
}

return 0;
}

===================CODE END====================

This was an assignment of mine (basic C++).

I want to create a program that allows the user to insert data passed into an array stored in a file ---- yes?

Then I want the above code --- rewritten --- to open the file and pass it out to be displayed.

would it be easier to save the data to the file as an array? or feed it into the other program as individual pieces and create the array while opening?

Lots of questions -

I am asking this because I am having difficulty "linking" the file to each program, as the examples, as far as I have seen, just use outfile.open("example.txt")
outfile << int;
or something along those lines.

Kind regards
Last edited on Jul 23, 2018 at 2:19am
Jul 23, 2018 at 11:13am
You've been asked several times now to use code tags. Why are you refusing to do so?
Jul 23, 2018 at 12:36pm
Hello b3y0nd,

For this subject you are welcome. I am glad it worked out for you.

For your next question it would be best if you green check this subject, to let everyone know that you are finished, and put your next question in a new subject. This is less confusing for everyone.

Best to head MikeyBoy's advice and refer back to the beginning of message http://www.cplusplus.com/forum/beginner/240178/#msg1069681 I found the second link very useful.

Since your new message will be using a file please include this input file or a sample of it, if it is large, so all can see what you are working with. This way everyone will be using the same information and your answers will be what you need and not a guess.

For part of your question I to use VS 2015 and like it. CodeBlocks is another well used program. I do not have much experience with CodeBlocks as I have not installed it yet. VS is a good IDE that will show you mistakes before you even compile the code. This is very useful.

Start a new subject for your new question and by then I will have some time to load up the program and have some answers.

Hope that helps,

Andy
Topic archived. No new replies allowed.