C++ Arrays in a Beginner Application - c++

I need to write a program that allows the user to enter 12 double values representing store sales for each month of one year. After all 12 values are entered, I need to display each month’s sales amount and a message indicating whether it is higher, lower, or equal to the average month’s sales amount. I can get the program to list the month by number and average the sales, but I am unable to get it to list the months by NAME and as well as compare each month to the average and display whether it is higher, lower, or equal to the average amount. I've looked through the forums here and at cplusplus.com but am not getting anywhere. I'm not looking for finished code, but any advice is appreciated. My code:
#include"stdafx.h"
#include<iostream>
using namespace std;
int main()
{
const int MONTHLY_SALES = 12;
const char month[12] = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'};
double totalSales = 0;
double storeSales[12];
double AVERAGE;
int x;
for(x = 0; x < MONTHLY_SALES; ++x)
{
cout << "Enter the sales for month #" << (x + 1) << " ";
cin >> storeSales[x];
}
cout << endl << "The sales for each month are:" << endl;
for(x = 0; x < MONTHLY_SALES; ++x)
{
totalSales += storeSales[x];
cout << storeSales[x] << " ";
}
cout << endl;
AVERAGE = totalSales / MONTHLY_SALES;
cout << "The average sales is " << AVERAGE << endl;
return 0;
}
Thanks for any and all help!

Firstly, your compiler should not have let you get away with that definition of month. You need to declare the array as const char* and use double quotes, since these are strings:
const char *month[12] = {"Jan", "Feb", ... , "Dec" };
You can then get the month name using month[x] where x is an integer between 0 and 11.
As for the averages, something simple like this in another loop:
int diff = storeSales[x] - AVERAGE;
if( diff < 0.0 ) {
// below average
} else if( diff > 0.0 ) {
// above average
} else {
// equal
}
Bear in mind also that you are dealing with double values, so in some cases an average that appears to be the same value (rounded) as something else might in fact be above or below.

Related

Having trouble about 6 errors in my array code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I can't seem to correctly run the code. Would be of a great help in finding the 6 errors. I am stuck and somehow no idea where to find the error for my simple array code.
Here are the errors I get.
// This program uses two arrays to record the names of 6 types of pizza
// and the sales numbers for each of these types
// The program then finds the best and the worst selling pizzas
#include <iostream>
#include <string>
using namespace std;
int main()
{
constint ARR_SIZE = 6; // Declare the array size and set it to 6
// Declare the array of pizza names and record values in it
int name[ARR_SIZE] = [ "Pepperoni", "Prosciutto", "Vegetarian",
"Sausage",
"Supreme",
"Mozzarella" ];
int sales[ARR_SIZE]; // Declare the sales array
int worstseller_number, bestseller_number; // The subscripts of the best- and worstseller
string worstseller_name, bestseller_name; // The sale numbers of the best- and worstseller
for (int i = 1; i < ARR_SIZE; i++) // A loop to enter all sales numbers
{
cout << "Enter sales for " << name[i] << ": ";
cin >> sales[i];
}
// Make the first element in name[] the bestseller and the worstseller name
worstseller_name = bestseller_name = name[0];
// Make the first element in sales[] the bestseller and the worstseller sales amount
worstseller_number = bestseller_number = sales[0];
for (int i = 0; i <= ARR_SIZE; i++) // Loop through all elements in sales[]
{
if (sales[i] < worstseller_number) // If an element is less than the lowest...
{
worstseller_number = i; // make the lowest sales equal to its sales
worstseller_name = name[i]; // make the worstseller name equal to its name
}
if (sales[i] < bestseller_number) // If an element is higher than the highest...
{
bestseller_number = sales[i]; // make the highest sales equal to its sales
bestseller_name = name[i]; // make the bestseller name equal to its name
}
}
cout << "The bestselling pizza is " << bestseller_name << " with the sales of "
<< bestseller_number << endl; // Display the best selling pizza
cout << "The worst selling pizza is " << worstseller_name << " with the sales of "
<< worstseller_number << endl;
} // display the worst selling pizza
First of all it should be const int ARR_SIZE = 6; Next, your array elements are strings but you are defining the array as int. Another error is that when you declare an array, it should be enclosed within curly brackets instead of square brackets. There was a mistake in the logic when you were trying to accept the sales and calculate the min and max which I have fixed. The first for loop should start from i=0 and the second for loop should go till i<ARR_SIZE
Try this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int ARR_SIZE = 6; // Declare the array size and set it to 6
// Declare the array of pizza names and record values in it
string name[ARR_SIZE] = {"Pepperoni", "Prosciutto", "Vegetarian",
"Sausage",
"Supreme",
"Mozzarella"};
int sales[ARR_SIZE]; // Declare the sales array
int worstseller_number, bestseller_number; // The subscripts of the best- and worstseller
string worstseller_name, bestseller_name; // The sale numbers of the best- and worstseller
for (int i = 0; i < ARR_SIZE; i++) // A loop to enter all sales numbers
{
cout << "Enter sales for " << name[i] << ": ";
cin >> sales[i];
}
// Make the first element in name[] the bestseller and the worstseller name
worstseller_name = bestseller_name = name[0];
// Make the first element in sales[] the bestseller and the worstseller sales amount
worstseller_number = bestseller_number = sales[0];
for (int i = 0; i <ARR_SIZE; i++) // Loop through all elements in sales[]
{
if (sales[i] < worstseller_number) // If an element is less than the lowest...
{
worstseller_number = sales[i]; // make the lowest sales equal to its sales
worstseller_name = name[i]; // make the worstseller name equal to its name
}
if (sales[i] > bestseller_number) // If an element is higher than the highest...
{
bestseller_number = sales[i]; // make the highest sales equal to its sales
bestseller_name = name[i]; // make the bestseller name equal to its name
}
}
cout << "The bestselling pizza is " << bestseller_name << " with the sales of "
<< bestseller_number << endl; // Display the best selling pizza
cout << "The worst selling pizza is " << worstseller_name << " with the sales of "
<< worstseller_number << endl;
} // display the worst selling pizza

Trouble with passing array to a function

I am supposed to use a string array to output the line "Enter rainfall for x", x being the name of a month, and having the input be sent to a separate array for calculations. Currently, when I run my code I am seeing "Enter rainfall for 1", "Enter rainfall for 2", etc. instead of "Enter rainfall for January", "Enter rainfall for February". Aside from this, the code also needs to show the total, average, and lowest and highest months of rainfall. I am able to have the program output the correct total and average however, the highest and lowest month just outputs a random number instead of a month name.
I have attempted to create prototypes and call an array to a function but I think the issue might be contributed to the fact that I am having issues with my string array. I have tried using a for loop, I've tried changing my syntax to no avail. I don't currently get any errors in the debugging process only see incorrect output instead of a string output.
#include <iostream>
#include <string>
using namespace std;
// Function Prototypes
void getMonthlyRainfall(double[], int);
double getTotal(const double[], int);
double getHighestAmount(const double[], int);
double getLowestAmount(const double[], int);
int main()
{
const int MONTHS = 12;
string monthNames[MONTHS] = { "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November",
"December" };
double rainfall[MONTHS], // Array
total,
average,
lowestAmount,
highestAmount;
//Get rainfall input from user
getMonthlyRainfall(rainfall, MONTHS);
// Get the total amount of rain for the year
total = getTotal(rainfall, MONTHS);
// Get the average rainfall
average = total / MONTHS;
// Get the month with the lowest rainfall
lowestAmount = getLowestAmount(rainfall, MONTHS);
// Get the month with the highest rainfall
highestAmount = getHighestAmount(rainfall, MONTHS);
cout << "Total rainfall: " << total << endl;
cout << "Average rainfall: " << average << endl;
cout << "Least rainfall in: " << getLowestAmount << endl;
cout << "Most rainfall in: " << getHighestAmount << endl;
return 0;
}
void getMonthlyRainfall(double rain[], int size)
{
int index;
for (index = 0; index < 12; index++)
{
cout << "Enter rainfall for " << (index + 1) << ": ";
cin >> rain[index];
}
}
double getTotal(const double numbers[], int size)
{
double total = 0; // Accumulator
for (int count = 0; count < size; count++)
total += numbers[count];
return total;
}
double getHighestAmount(const double numbers[], int size)
{
double highest; // Holds highest value
// Get array's first element
highest = numbers[0];
// Step through array
for (int count = 0; count < size; count++)
{
if (numbers[count] > highest)
highest = numbers[count];
}
return highest;
}
double getLowestAmount(const double numbers[], int size)
{
double lowest; // Holds lowest value
// Get array's first element
lowest = numbers[0];
// Step through array
for (int count = 0; count < size; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}
return lowest;
}
As I stated the first output should say the actual name of a month and it should be in order. For instance, the prompt should first ask the user to input total rainfall for the month of January, the user inputs a number. The prompt then goes on to ask the user input a number for February, so on and so forth until December. I am instead seeing the prompt ask the user to input total rainfall for "1", user inputs a number, the prompt then asks user to input rainfall for "2" until it gets to 12. The program does the calculations and outputs correct total and average but when it is supposed to output "Month with highest (or lowest) rainfall: (Month name)" it instead gives me a random number such as 01201686.
So to sum up, the string array outputs month name and the user input is stored in a separate array for calculations. Those calculations are outputted for total and average but the rainfall totals need to be compared to the month with the corresponding entity and the output for highest and lowest then needs to be a string not a number.
It's a simple confusion over names. You have the name of the function (which will print as a 'random' number) instead of the name of the variable you are using.
cout << "Least rainfall in: " << getLowestAmount << endl;
should be
cout << "Least rainfall in: " << lowestAmount << endl;
As for your first quesiton, change
cout << "Enter rainfall for " << (index + 1) << ": ";
to
cout << "Enter rainfall for " << monthNames[index] << ": ";
Obviously the first version prints a number (index + 1 is a number). To get the month name you have to use the number as an index to your array of month names.
To make this work you also will need to make monthNames available in the getMonthlyRainfall function (at the moment it's only visible in main). You should pass monthNames to the getMonthlyRainfall function like this
void getMonthlyRainfall(double[], string[], int);
and
//Get rainfall input from user
getMonthlyRainfall(rainfall, monthNames, MONTHS);
and
void getMonthlyRainfall(double rain[], string monthNames[], int size)
{
...
EDIT
So to output both lowest monthly rainfall and the name of the month with the lowest rainfall you should change your getLowestAmount function to return the index of the month with the lowest rainfall. You should also change the name of this function because it's now doing something different from the original function and the old name does not accurately describe the new function, but for clarity I'll leave it the same. You can decide on a new name later.
// this function returns a month index, not a rainfall amount,
// so it's return type is int not double
int getLowestAmount(const double[], int);
Here's the updated function
int getLowestAmount(const double numbers[], int size)
{
double lowest; // Holds lowest value
int lowestIndex; // Holds the index of the lowest value
// Get array's first element
lowest = numbers[0];
lowestIndex = 0;
// Step through array
for (int count = 0; count < size; count++)
{
if (numbers[count] < lowest)
{
lowest = numbers[count];
lowestIndex = count;
}
}
return lowestIndex;
}
See the function is the same except I've added lowestIndex and that's the value I return.
Now in main you can use the lowest index to print both values that you want to see
// Get the month with the lowest rainfall
lowestIndex = getLowestAmount(rainfall, MONTHS);
...
cout << "Least rainfall in: " << monthNames[lowestIndex] <<
" is " << rainfall[lowestIndex] << endl;

C++ program on how much a person would earn over time if salary is one penny per day (Not an IT student)

I have a project to write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
This is my code so far and I can't seem to get it to work properly (not an
IT student)
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip.h>
int main()
{
int days;
double pennies = 0.01;
double total = 0.0;
double fixed;
double showpoint;
cout << "For how many days will the pay double?";
cin >> days;
cout << endl << "Day Total Pay\n";
cout << "------------------------\n";
for (int count = 1; count <= days; count++)
{
cout << count << "\t\t$\t" << (pow(2, pennies)) << endl;
}
cout << setprecision(2) << fixed << showpoint;
cout << "--------------------------------\n";
cout << "Total $\t" << total << endl;
getch();
return 0;
}
I've tried to explain the changes I have made, but if you need to know more please ask
// Headers for standard library features don't have .h on the end (normally)
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip>
int main()
{
int days = 0;
// double pennies = 0.01; Not needed.
double total = 0.0;
// If you don't initialise variables it will cause a crash or undefined behaviour.
// double fixed;
// double showpoint;
while (days < 1) // This prevents negative or 0 day contracts.
{
// You need to use the full name to cout or that abomination of a command using namespace std
std::cout << "For how many days will the pay double?";
std::cin >> days;
}
std::cout << std::endl << "Day Total Pay\n";
std::cout << "------------------------\n";
// looping from 0 while less than days is more "normal".
for (int count = 0; count < days; count++)
{
double payForTheDay = (pow(2, count));
std::cout << count << "\t\t$\t" << payForTheDay << std::endl;
total += payForTheDay; // You need to increment the total.
}
// Not sure what this is about
// std::cout << std::setprecision(2) << fixed << showpoint;
std::cout << "--------------------------------\n";
std::cout << "Total $\t" << total << std::endl;
getch();
return 0;
}
Try to replace (pow(2, pennies)) with (pennies * pow(2, (count - 1)))...
Notes:
Shouldn't pennies actually be named dollars?
To calculate the total, just increase it by the daily salary for each day (e.g. inside the loop where you output each table row).
So look at the basic of the problem. It is basically a geometric progression.
In a geometric progression sum of n numbers is;
Sn=a1((1-r^n)/(1-r))
[a1=first element(in your case 1);r=2(in this case)]
Use the formula to get number of pennies for n days.
Now convert it into dollar value.
If you need full code comment here.
Quite late, but using bitwise shift is the best thing for 2^n in my opinion. It's fast and easy to use.
int days; // = amount of days for payment;
// Add input/output logic
if (days<1) {
// Do invalid input logic
}
// Use long long if days>31
for (int K=0; K<days; K++)
cout<<"Day "<<K<<": "<<(1<<K)<<"\n;
Here 1<<K is 2^K
Alternatively, you can use a variable to save the payment
and shift it by 1 each iteration.

Sorting both a string array and a double array from highest to lowest(parallel arrays) and aligning the text

Alright I'll bite, this program does sort the number from highest to lowest but it'll only sort if the numbers are arranged in order from highest to lowest;not if it's sporadic. Here are two example of what I mean.
Example 1: 12,11,10,9,8,7,6,5,4,3,2,1.
Example 2: 32,25,24,31,10,11,15,16,8,19,18,5.
You see how in example 2 that some of the numbers are in order like 32 25 24 but some of the others are not. This is my main problem. My secondary problem is aligning the text vertically so that it looks neat. Should I use setw left, right for this? Please give feedback.
Note 1: The IDE that I'm using is codeblocks.
Note 2: Keep in mind that whatever number the user inputs for a particular month has to be vertically parallel to each.
Note 3: I'm pretty sure the problem is with my selection sort. So you really should be looking at the function void selectionsort since that is the function that is doing all the sorting. I just don't know where I went wrong with my sorting though. Everything else seems to be in order.
/* This program lets the user enter the total rainfall
for each month into an array of doubles. The program also
calculates and displays the total rainfall for a year, the average
monthly rainfall, and the months with the highest and lowest amounts.
The program also displays the list of months, sorted in order of
rainfall from highest to lowest.*/
/* This program does not accept negative numbers for monthly rainfall
figures.*/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void SelectionSort(string[], double[], int);// Function Protoype.
int main()
{
const int SIZE = 12; /* A constant integer that represent the total
amount of months in a year. */
double totalRainfallPerMonth[SIZE]; /* Loop this array to force the user
to enter variables for each
element in this array. */
double totalRainfallPerYear = 0; /* The total amount of rainfall
(in inches) per year. */
// An array of every month.
string monthArray[SIZE]={"January", "February", "March", "April", "May",
"June", "July","August", "September",
"October", "November", "December"};
double average; // A variable that holds the average monthly rainfall.
int i; // Will be used as a counter for any loop.
cout << fixed << showpoint << setprecision(2); // Set decimal notation.
for(i=0; i<=11; i++)
{
// Prompt the user to enter values.
cout << "Please enter the total rainfall(in inches) for ";
cout << monthArray[i] << ": ";
cin >> totalRainfallPerMonth[i];
while(totalRainfallPerMonth[i] < 0) /* If the user enters a negative
value */
{
cerr << "No negative values allowed. "; // Display error message.
cout << "Please try again. ";
cin >> totalRainfallPerMonth[i];
}
}
for(i=0; i<=11; i++)
{
// Calculate the total rainfall for a year.
totalRainfallPerYear += totalRainfallPerMonth[i];
}
// Display the total rainfall for a year.
cout << "\nThe total rainfall this year is " << totalRainfallPerYear;
cout << " inches of rain. " << endl;
// Calculate the average monthly rainfall.
average = totalRainfallPerYear / SIZE;
// Display the average
cout << "\nThe average monthly rainfall per month is ";
cout << average;
cout << " inches of rain. " << endl << endl << endl;
cout << "\n" << "Month " << "\t";
cout << " Rainfall(in inches)" << endl;
cout << "-----------------------------------";
SelectionSort(monthArray, totalRainfallPerMonth, SIZE); /* Call in the
function. */
return 0;
}
void SelectionSort(string month[], double rain[], int SIZE)
{
int i;
int j;
int min;
for (i = 0; i < SIZE - 1; i++)
{
min = i; // The intial subscript or the first element.
for (j = i + 1; j < SIZE; j++)
{
if (rain[j] > rain[min]) /* if this element is greater,
then it is the new minimum */
{
min = j;
// swap both variables at the same times
double tempDouble = rain[i];
rain[i] = rain[j];
rain[j] = tempDouble;
string tempString = month[i];
month[i] = month[j];
month[j] = tempString;
}
}
}
for(i=0; i<=11; i++)
{
/* Display the amount of rainfall per month from highest to
lowest */
cout << "\n" << month[i] << "\t" << rain[i] << endl;
}
}
There is in fact an error in your selection sort implementation: you are swapping elements too early and too often.
Only after you have performed a full sweep over the whole remaining array and therefore have determined the global minimum (I keep that term in order to be consistent with the variable name and the comments in the code, although in fact you are looking for the maximum) you should perform a single swap of the first element of the remaining array with the minimum element.
The corrected code (only the main loop of the sorting function shown) should look like this:
for (i = 0; i < SIZE - 1; i++)
{
min = i; // The intial subscript or the first element.
for (j = i + 1; j < SIZE; j++)
{
if (rain[j] > rain[min]) /* if this element is greater,
then it is the new minimum */
{
min = j;
}
}
// swap both variables at the same times
double tempDouble = rain[i];
rain[i] = rain[min];
rain[min] = tempDouble;
string tempString = month[i];
month[i] = month[min];
month[min] = tempString;
}

How do I get this code to work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Struggling with this, can't seem to get it to work. Here is what I need to do:
1.Ask the user how many weeks were in the landscaping season this year.
2.Dynamically create an array of double floating point data that can be used to store the sales for each week of the season.
3.Using a for loop, have the user enter in the sales data for the season.
4.Pass the array (and its size) into a function that will display all the sales for the weeks in a nice table.
5.Call another function that will take in the array as an argument and will total the sales for the season (returning the total to the main function).
6.Have the program tell the user the total sales for the season and the average sales per week.
7.After this delete the allocated memory and set the pointer to 0.
Any assistance helps always I don't quite understand functions, or pointers. and I've read about both a lot!!
#include <iostream>
#include <iomanip>
using namespace std;
int Weeks = 0;
double total;
double sales;
void SalesTable(int);
double Total (int, double[]);
double average;
int main()
{
double Season[Weeks];
cout << "How many weeks were in the landscaping season this year: ";
cin >> Weeks;
for (int i = 1; i<Weeks+1; i++)
{
cout << "Enter sales data for week " << i <<": ";
cin >> sales;
}
Season[Weeks]=sales;
SalesTable(Weeks);
Total(Weeks, Season);
average = total/Weeks;
cout << "The total sales for the season are: "<<setprecision(2)<<showpoint<<fixed<<total<< endl;
cout << "The average weekly sales were: "<<setprecision(2)<<showpoint<<fixed<<average;
return 0;
}
void SalesTable(int Weeks)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << sales <<endl;
}
}
double Total(int Weeks, double Season[])
{
for(int i = 1; i<Weeks+1; i++)
{
total += Season[Weeks];
}
return total;
}
Ok , using pointer to double it will do what you need :
int Weeks = 0;
double total;
double sales;
void SalesTable(int, double*);
double Total (int, double*);
double average;
int main ()
{
double *Season;
cout << "How many weeks were in the landscaping season this year: ";
cin >> Weeks;
Season = new double [ Weeks ];
for (int i = 1; i<Weeks+1; i++)
{
cout << "Enter sales data for week " << i <<": ";
cin >> sales;
Season[i-1]=sales;
}
SalesTable(Weeks, Season);
Total(Weeks, Season);
average = total/(double)Weeks;
cout << "The total sales for the season are: "<<showpoint<<fixed<<total<<endl;
cout << "The average weekly sales were: "<<showpoint<<fixed<<average;
delete[] Season;
return 0;
}
void SalesTable(int Weeks,double *Season)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << Season[i-1]<<endl;
}
}
double Total(int Weeks, double *Season)
{
for(int i = 1; i<Weeks+1; i++)
{
total += Season[i-1];
}
return total;
}
Since I can't comment yet, I'll post a new answer:
The code provided by T-D still doesn't work because of this: the print out for each sales week is always the same because it isn't accessing the elements inside of the Seasons array.
void SalesTable(int Weeks)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << Season[i - 1] << endl;
}
}
Also, to dynamically create an array which allows the user to control the size of the array at runtime use the following code:
double *season = new double[Weeks];
And because you dynamically created the array, you have to manually release its resources:
delete[] season;