Jamie and Alex have been tracking how much chocolate each of
Jamie and Alex have been tracking how much chocolate each of them gets each Halloween for the past three years. Jamie has gotten 24, 32, and 21 pieces of chocolate and Alex has gotten 27, 17, and 22 pieces. Initialize a two dimensional array that holds all the chocolate values and uses year as columns and the person as rows. Write functions called totalChocolateByPerson(), totalChocolateByYear(), and maxChocolate(), that print out the total amount of chocolate each person has collected, the total chocolate collected each year, and the person and year that the most chocolate was collected.
Expected output:
Jamie has gotten a total of __ pieces of chocolate.
Alex has gotten a total of __ pieces of chocolate.
There were __ pieces of chocolate collected in year 1.
There were __ pieces of chocolate collected in year 2.
There were __ pieces of chocolate collected in year 3.
______ collected the most chocolate in year __.
Solution
#include<iostream>
using namespace std;
#define JAMIE 0
#define ALEX 1
int totalChocolateByPerson(int data[2][3],int person);
int totalChocolateByYear(int data[2][3],int year);
void maxChocolate(int data[2][3]);
int main()
{
int data[2][3] = { { 24, 32, 21 },
{ 27, 17, 22 }};
cout<<\"Jamie has gotten a total of \"<<totalChocolateByPerson(data,JAMIE)<<\" pieces of chocolate\"<<endl;
cout<<\"Alex has gotten a total of \"<<totalChocolateByPerson(data,ALEX)<<\" pieces of chocolate\"<<endl;
cout<<\"There were \"<<totalChocolateByYear(data,0)<<\" pieces of chocolate collection in year 1\"<<endl;
cout<<\"There were \"<<totalChocolateByYear(data,1)<<\" pieces of chocolate collection in year 2\"<<endl;
cout<<\"There were \"<<totalChocolateByYear(data,2)<<\" pieces of chocolate collection in year 3\"<<endl;
maxChocolate(data);
return 0;
}
int totalChocolateByPerson(int data[2][3],int person)
{
int sum = 0;
for(int i = 0; i < 3; i++)
{
sum += data[person][i];
}
return sum;
}
int totalChocolateByYear(int data[2][3],int year)
{
int sum = 0;
for(int i = 0; i < 2; i++)
{
sum += data[i][year];
}
return sum;
}
void maxChocolate(int data[2][3])
{
int max = 0;
int year, person;
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 3; j++)
{
if(data[i][j] > max)
{
max = data[i][j];
year = j + 1;
person = i;
}
}
}
if(person == 0)
cout<<\"JAMIE \";
else
cout<<\"ALEX \";
cout<<\"collected the most chocolate in year \"<<year<<endl;
}