Hi all, having some trouble with storing user input into this particular 2-dimensional array. I have to get the sales per car type per color type, and print the sum of sales of the car types AND color types separately. Here's what I have so far. Should I declare variables for each type of car/color that the user inputs?
#include <iostream>
#include <string>
#include <iomanip>
usingnamespace std;
constint CAR_TYPES = 2;
constint COLOR_TYPES = 3;
double sales[CAR_TYPES][COLOR_TYPES];
int main(){
for (int i = 0; i<2; i++){}
//Ask the user for car type sales
cout << "Enter 2 car type sales: " << endl;
cin >> sales[i][0];
//Ask the user for amount of sales per color
cout << "Enter 3 color type sales: " << endl;
cin >>sales
system("pause");
return 0;
}
Line 11: The {} at the end of the line terminates the for statement. Therefore your for loop does not do anything.
Line 16: Since you've terminated the for statement, i has gone out of scope and is not valid here. Since the second subscript is 0, you saying that this is the sales for color 0.
Actually, I have this now, but the output still isn't correct. It seems to only be adding input to the total number of fords and the total number of red cars, but the numbers are too high.
lines 6-12 replicate the sales array, which BTW, I don't see in your program.
You're doing the same thing twice.
Line 20: Take a look at your subscripting. You've changed this. It was sales[i][j], now it's sales[j][i]. i represents the car type, which is the first dimension of the array.
Lines 22-50: This works, but is rather brute force. It's also not easily extensible. If you were to add a car brand or a color, you have to recode your program.
#include <iostream>
usingnamespace std;
constint CAR_TYPES = 2;
constint COLOR_TYPES = 3;
constchar * carbrands[] =
{ "Ford",
"Chevy",
};
constchar * colors[] =
{ "Red",
"Blue",
"Green",
};
int main()
{ int sales[CAR_TYPES][COLOR_TYPES];
int total;
int grand_total = 0;
//for loop to ask the user for the number of cars sold.
for (int i = 0; i<CAR_TYPES; i++)
{ for (int j = 0; j<COLOR_TYPES; j++)
{ cout << "How many " << colors[j] << " " << carbrands[i] << "s were sold? ";
cin >> sales[i][j];
}
}
// Print the totals by car type
for (int i=0; i<CAR_TYPES; i++)
{ total = 0;
for (int j=0; j<COLOR_TYPES; j++)
total += sales[i][j];
cout << "Total " << carbrands[i] << "s sold = " << total << endl;
}
// Print the totals by color
for (int j=0; j<COLOR_TYPES; j++)
{ total = 0;
for (int i=0; i<CAR_TYPES; i++)
total += sales[i][j];
cout << "Total " << colors[j] << " cars sold = " << total << endl;
grand_total += total;
}
cout << "Grand total of " << grand_total << " cards sold" << endl;
system("pause");
return 0;
}
This is much more easily extensible. If you want to add more car brands or and/or colors, all you have to do is add an entry to the appropriate table and change the CAR_TYPE or COLOR_TYPE constants accordingly.