The problem was asking for employee numbers 1 through 10 (they gave me the array numbers to enter into the array) give the total sales for each employee by combining the 3 months together. In my addition function it does everything correctly....for the first part... It displays the numbers in the array perfectly but then when it goes to add the arrays and tosses out an element here and there resulting in incorrect totals. In my code I added that it should cout the array numbers that it is adding together after the first set of numbers it doesn't follow the array here is the code:
I followed what you guys were showing me (thank you btw) and I am now adding Employee #1's total to the rest which I do not want to do. I want to enter Employee #1's to each other stop display it then add Employee #2's total from the 3 numbers in the 3 months array stop display (continue until each piece is displayed 1~10) I have entered my new code for revision. I am new to C++ programming and I have not learned about classes yet so I honestly cannot use them.
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void displaySales(int sales[10][3]);
void displayTotalSales(int total[10][3]);
int main ()
{
//declare array Jan Feb Mar
int employ[10][3] = {{2400, 3500, 2000},
{1500, 7000, 1000},
{600, 450, 2100},
{790, 240, 500},
{1000, 1000, 1000},
{6300, 7000, 8000},
{1300, 450, 700},
{2700, 5500, 6000},
{4700, 4800, 4900},
{1200, 1300, 400}};
//displays the sales for the month
displaySales(employ);
displayTotalSales(employ);
system("pause");
return 0;
}
//******Functions*******
void displaySales(int sales[10][3])
{
for(int emp = 0; emp < 10; emp++)
{
cout << "Employee # " << emp + 1
<< ": " << endl;
for (int month = 0; month < 3; month++)
{
cout << " Month " << month + 1
<< ": ";
cout << sales[emp][month] << endl;
} //end for
} //end for
} //end function
void displayTotalSales(int total[10][3])
{
int employ = 1; //employee number
int totalSales = 0; // total sales for the employee
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 3; j++)
{
totalSales += total[i][j];
cout << "Employee # " << employ << ": " << endl;
cout << endl;
cout << "Total sales for the month: " << "$" << total[i][j];
cout << endl;
}
cout << " Total Sales for the three months is: $" << totalSales << endl;
cout << endl;
employ++;
}
}
do {
...
totalSales = (total[i][j] + total[i][j+1] + total[i][j+2]);
j++;
} while (j < 3);
j goes out of bounds after the first iteration.
But seriously: Use classes! and Use containers!
Oh, and your curly brackets are totally messed up.
Its probably not appropriate for me to add this an answer but since there is no way for newbies to comment, I'll just say it here.
I agree with karl regarding learning about objects. when we learned about c and c++ at college we started out with structs and then moved on to classes and its really important to learn this stuff if you're serious about programming.
a class is just a way of describing an object in the real world. it has attributes and behaviours. For example you could have an employee class that could store all their earnings per month and it could have a function within it that allows you to calculate their recent earnings. These small additions to your code will make it easier to read, organise and reuse.
I seriously suggest you spend a few hours googling object oriented concepts and try some c++ examples. they're very easy.
First of all please form your code better! Indenting would make this a hell of a lot easier to understand and help you with.
I get the strong feeling that this is a homework question for a programming class but I'll try and help you with it anyway.
Basically your problem is that you are running over the end of the array, because when j == 2 for example when you use the statement:
totalSales = (total[i][j] + total[i][j+1] + total[i][j+2]);
you are trying to reference j+2 which is actually the 5th element of the array, which does not exist.
I did a 10 second rewrite of your addFunk (please name functions better)
You could try something like this:
void addFunk(int total[10][3])
{
int employ = 1; //employee number
int totalSales = 0; // total sales for the employee
for (int i = 0; i < 10; i++)
{
for ( int j = 0; j < 3; j ++)
{
totalSales += total[i][j];
}
cout << "employee num " << employ << "earned "
<< "$" << totalSales << endl;
totalSales = 0;
employ++;
totalSales = 0;
}
}
Regarding your update to the code, you say:
I am now adding Employee #1's total to the rest which I do not want to do.
The problem is this line:
int totalSales = 0; // total sales for the employee
Look at the comment you've put there: it's per-employee. Therefore, it should go inside the "per-employee loop":
for (int i = 0; i < 10; i++)
{
int totalSales = 0;
// Proceed as before with the per-month work.
Please read up about the "scope" of variables in C++.
Also, being new to C++, or new to programming in general, is not really an excuse to avoid classes. There's nothing particularly advanced about them per se; the code is only as complicated as you make it - and classes exist because using them properly helps organize (read: simplify) your code.
Related
Hello Stack Overflow users,
I have this program that i am trying to create for my collection of movies, and please forgive me for some of my mistakes and oversights since I AM NEW TO C++, but basically my program runs (yay) but when I chose any of the four options this error pops up:
Main Error
I want the first program option to display like this:
Akira 10.0
Blade Runner 10.0
Deadpool 8.8
BUT IT DOESN'T DO THAT it just looks like:
10.0
10.0
8.8
Example of my bad output
My output just displays all of the scores on new lines but no movie titles show up and if I try any of the last three options (highest/lowest/average) it just displays the same error: Same error as above
If you could give me any pointers (or a code example) as what I need to do to make the output appear as the bold one above, that would be amazing!
Again please forgive me for possible simple errors I am making since this is my first time working with vectors.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
// Function Prototypes
void displayList(vector<string>,vector<double>);
void highestRating(vector<double>);
void lowestRating(vector<double>);
void averageRating(vector<double>);
// 1st Vector Defintion
vector<string> movies{ // inside this is a list of 48 strings containing movie names (Ex: "Akira", "Blade Runner" };
// 2nd Vector Definition
vector<double> ratings{ // Inside this is a list of 48 doubles that contain movie scores for each movie
and i wish for it to print out directly right of the movie title, then turn to the next line.
Examples of numbers inside this vector: 9.9, 10.0, 5.5, 7.5 };
// Main
int main()
{
cout << fixed << showpoint << setprecision(1);
// Variable Definitions
const int DISPLAY = 1, HIGHEST = 2, LOWEST = 3, AVG = 4;
int response;
cout << "-------Welcome to C++ Newbie's Movie Collection Database-------" << endl;
cout << "\nEnter 1 to display the whole collection" << "\nEnter 2 to display the 5 highest rated movies by me";
cout << "\nEnter 3 to display the lowest 5 rated movies by me" << "\nEnter 4 to display the average score of the movies in the collection along with some other math" << endl;
cin >> response;
// Menu
do
{
switch (response)
{
case(DISPLAY):
{
displayList(movies, ratings);
break;
}
case(HIGHEST):
{
highestRating(ratings);
break;
}
case(LOWEST):
{
lowestRating(ratings);
break;
}
case(AVG):
{
averageRating(ratings);
break;
}
default:
{
exit(0);
}
}
} while (response == 1 || response == 2 || response == 3 || response == 4);
return 0;
}
// Display List
void displayList(vector <string> movies, vector <double> ratings)
{
for (int val = 0; val <= movies.size(); ++val)
{
cout << movies[val] << "\t";
for (int rat = 0; rat <= ratings.size(); ++rat)
{
cout << ratings[rat] << endl;
}
}
}
// Display highest by me
void highestRating(vector<double> ratings)
{
double max = ratings[0];
for (int i = 0; i <= ratings.size(); i++)
{
if (ratings[i] >= max)
max = ratings[i];
}
cout << "\nThe highest rated movie is " << max << endl;
}
// Display Lowest by me
void lowestRating(vector<double> ratings)
{
double min = ratings[0];
for (int a = 0; a <= ratings.size(); a++)
{
if (ratings[a] <= min)
min = ratings[a];
}
cout << "\nThe lowest rated movie is" << min << endl;
}
// Average Score by me
void averageRating(vector<double> ratings)
{
double average;
double total = 0;
for (int x = 0; x <= ratings.size(); x++)
{
total += ratings[x];
}
average = total / ratings.size();
cout << "\nThe average is " << average << endl;
double forTheFunOfIt = fmod(average, 2.0);
cout << "\nThe Average divided by 2 is " << forTheFunOfIt << endl;
}
To address your first problem in displayList(), you are displaying a movie, and then looping to display all of the ratings. You probably need to display both within the same single loop. Also, if you do this then you need to make sure that both vectors have the exact same sizes to avoid attempting to access beyond the range of your vector, (it is probably best to use a std::map of movies and rating).
Having said that, for your code above maybe try changing displayList() to something like
// Display List
void displayList(vector <string> movies, vector <double> ratings)
{
for (int val = 0; val < movies.size(); val++)
{
cout << movies[val] << "\t" << ratings[val] << std::endl;
}
}
Note, you are not going to want to loop while val <= movies.size(), the indexes to your vector of (for example) 4 movies and 4 ratings will be 0-3, not 0-4. You will encounter an error indicating you are out of range.
Now for your next problem, you are looping in main() on the initial input from the user, but you are never updating the response variable from a user input. This will cause you to fall into an infinite loop! An easy fix for you will be to move cin >> response into the top of your do-while loop.
Moving onto the next couple issues, which is invalid output for your highest, lowest, and average. Again, you should not be looping while the index is less than or equal to the total size of the vector. Instead, you want less than only.
Lastly, you may want to consider passing your vectors as const references
I working on an assignment for my introduction to programming class which is meant to perform operations on an array of grades. Here are the details:
Usinging the following parallel arrays:
const int NUM_GRADES =5;
string Students[NUM_STUDENTS] = {"Tom","Jane","Jo"};
int grades[NUM_STUDENTS][NUM_GRADES] ={{78,98,88,99,77},
{62,99,94,85,93},
{73,82,88,85,78}};
Write a function called displayNumStudentsAtLeastBForSelectedAssignment that takes the student and grade arrays as parameters, allows the user to select a valid assignment and locates and displays the number of the student with at least a grade >= 80 for that assignment in the format in the sample run below.
Here is the code I have written for this function. I am wondering if my logic makes sense as I was working on this all night and have just found a potential solution
//Displays the number of students with at least a B (>=80)
int DisplayNumStudentsAtLeastBForSelectedAssignment(string Students[NUM_STUDENTS], int grades[NUM_STUDENTS][NUM_GRADES])
{
std::cout << "Number of students with atleast a B: " << endl;
std::cout << "Please enter in an assignment number: ";
int assignmentNum;
std::cin >> assignmentNum;
getValidAssignmentNumber(assignmentNum);
int total =0;
for (int x = 0; x < NUM_STUDENTS; x++)
{
if (grades[x][assignmentNum-1]>= 80)
total = total + 1;
}
std::cout << "Number of students with at least B on assignment " << assignmentNum << ": " << total << endl;
}
The function seems to be working properly. Just curious if there is a more efficient way of doing it. Thank you all for the help in advance.
I have class City with following private data: name of city, width,length and height of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.
I should use bubble sort to sort the cities by their length. And when this is done, the program should show the sorted cities in increasing lengths.
The problem is that my data are in private(in public everything works excellent but principle of capsulation is violated!) so I can't do bubble sort.
I tried to do another dynamic array of type double double Lengths[n], which content is lengths of first array. Then I do sorting, but program prints only sorted lengths and this is not my goal.
I should print the names of cities sorted by their lengths.
Code:
class City{
private: char *name;
double width;
double length;
double height;
public:void Output();
City();
~City();
double GetLength()
{
return length;
}
double GetWidth(){ return width; }
double GetHeight(){ return height; }
char GetName(){ return *name; }
};
City::City()
{
char ime[20];
cout << "Name= ";
cin >> ime;
name = new char[strlen(ime) + 1];
for (int i = 0; i <=strlen(ime); i++)
name[i] = ime[i];
cout << "Width= ";
cin >> width;
cout << "Length= ";
cin >> length;
cout << "Height= ";
cin >> height;
}
void City::Output()
{
cout << "Name is: " << name << endl;
cout << " Width is: " << width <<" deg"<< endl;;
cout << " Length is: " << length << " deg"<<endl;
cout << " Height is: " << height <<" m"<<endl;
return;
}
City::~City()
{
cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}
int main()
{
//City town;
//town.Input();
//town.Output();
int n;
City *mA;
cout << "Input number of cities: " << endl;
cin >> n;
mA = new City[n];
for (int j = 0; j < n; j++)
{
mA[j].Output();
}
cout << "Cities from west to east, sorted by their length" << endl;
double *Lengths = new double[n];
for (int j = 0; j < n; j++)
{
Lengths[j] = mA[j].GetLength();
}
int k = 0;//counter
double max = Lengths[0];
for (int j = 1; j < n; j++)
{
if (Lengths[j - 1] >Lengths[j])
{
max = Lengths[j - 1];
Lengths[j - 1] = Lengths[j];
Lengths[j] = max;
}
}
for (int j = 0; j < n; j++)//cycle for output
{
mA[j].Output();
}
delete[]mA;
return 0;
}
As I can't quite comment on your response, I will give you a few bits of advice. First in the line of:
Array[j]=mA[j].GetName() ;
You have a random space which may be a copy change and relatively minor but for reading purposes that is wrong.
Second your naming conventions are really something you should work on. I should be able to read a variable and understand what it means but instead I struggle to understand what a variable named mA means.
Third your else clause does nothing literally. Your not moving any parts of the array if that is your intention my saying this:
mA[j+1];
you are simply targeting the element in the array that is above the iteration. I see you stuck with your idea of making something similar to a parallel array for the bubble sort, and that is fine but you lack any action in the first loop.
This is not bubble sort what so ever as you are simply going through each iteration and checking if the element in Lengths is equal in length to the element in mA and then storing that element in array but your else statement does nothing.
Your loop should look similar to something like this but I'm gonna get rid of the character array and the extra array for some reason as it is unnecessary and lets say you start out with an array of your objects:
if(myObjects[i].GetLength() > myObjects[i+1].GetLength()) //Shortest to longest name or vice versa?
{
//Store myObject[i] in temp spot
//myObject[i] = myObject[i+1]
//myObject[i+1] = temp Storage
}
This will give you a bubble sort of the objects on the first round. Of course your going to have to find out how to iterate through the array in loop to verify all of the elements have been sorted correctly as this will of course take many iterations for bubble sort.
I don't see a direct question but I can assume majority of the question by your story. You have multiple options on how to solve this case. One of the simple ways to solve this is create a function within the object that allows you to get the length of a member of an object for example in your case it would be name of city.
Create a method inside the object that you can call to return a private method's length. Create a loop that calls this method and checks each element side by side until you can't refine it any longer. Is there a specific reason your using char instead of string for name?
I'm not entirely sure of what you're asking.
However, from what I can tell your main issue is that you can't sort because you're trying to compare two private variables from two objects.
If the objects are placed into an Array of type city, you can bubblesort by length however you would be required to use the getters in order to reference the variables that are private during sorting.
For example (not exact syntax)
if(cityArray[0].getLength() < cityArray[1].getLength())
{
//Do Something
}
I am writing a code to calculate the gross pay of seven employees using arrays. Here is what I have so far
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
//Set all constants and variables
const int SIZE = 7; //Size of all arrays
int emID[SIZE] = {1234, 4563, 8765, 4568, 9867, 9235, 7684};
double Hours[SIZE],
Rate[SIZE],
Gross[SIZE];
int index;
Gross[index] = (Hours[index] * Rate[index]);
//Explain Program
cout << "This program calculates an employees gross pay\n";
for (Hours[index];index <= 6; index++)
{
cout << "How many hours did employee " << emID[index] << " work?\n";
cin >> Hours[index];
}
for (Rate[index]; index <= 6; index++)
{
cout << "Enter the pay rate for " << emID[index] << endl;
cin >> Rate[index];
}
for (Gross[index]; index <=6 ; index++)
{
cout << "The gross pay for " << emID[index] << " is " << Hours[index] * Rate[index];
}
}
Unfortunately the program terminates after the first "for" loop. Any suggestions?
There seem to be a few mistakes in your code, which I'm pointing out below.
index is unitialised, and the way you've used it results in Undefined Behavior. I think you meant to initialise to to 0.
You should reset the value of index to 0 between for loops. Currently you would iterate in the first for loop. After that, since index will be > 6, your code will not execute the other two for loops.
Your first term in the for loop declarations is wrong. I think you meant to declare index = 0 there. If not, you should leave it empty.
The line near the beginning where you calculate Gross[index] is wrong and redundant.
I present to you all a program I'm working on for my college programming course. I still have a little ways to go before it completely meets my assignment's requirements, but I've gotten a basic draft of the program error-free (supposedly) and it appears to run… but then it suddenly kicks me into Xcode's debugger and gives me:
Thread 1: EXC_BAD_ACCESS(code=2, address=0x7fff95c1e5f5)
Here's the command line output, up until it kicks me out:
-----------------------
Quarterly_sales_taxator
-----------------------
How many company divisions will we be dealing with? 2
Am I correct in assuming that there are 4 sales quarters? yes
Please enter the sales Company Division #1 brought in for Sales Quarter #1 20
(lldb)
Here's my code:
//
// quarterly_sales_taxator.cpp
// Ch. 7 program #7
//
// Created by John Doe on 11/27/12.
//
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
void read_company_divisions_and_sales_quarters(double **, int, int);
//void write_company_divisions_and_sales_quarters_to_array(double **, int, int); // This will be used later on to read data from a file.
void display_quarterly_sales_array(double **, int, int);
string temp; // A global temporary placeholder variable; I use this several times.
int main()
{
int COMPANY_DIVISIONS,
SALES_QUARTERS = 4;
double **quarterly_sales_form;
cout << "\n\n-----------------------\nQuarterly_sales_taxator\n-----------------------\n\n";
cout << "\nHow many company divisions will we be dealing with? ";
getline(cin, temp);
stringstream(temp)>>COMPANY_DIVISIONS;
while (COMPANY_DIVISIONS < 1 || isdigit(COMPANY_DIVISIONS == false))
{
cout << "\n\n------"
<< "\nError:"
<< "\n------"
<< "\n\nYou have entered an invalid choice."
<< "\nPlease type a number greater than zero. ";
getline(cin, temp);
stringstream(temp)>>COMPANY_DIVISIONS;
}
cout << "\n\nAm I correct in assuming that there are 4 sales quarters? ";
getline(cin, temp);
// Convert to uppercase.
for (int count = 0; count < temp.length(); count ++)
{
temp[count] = toupper(temp[count]);
}
if (temp == "NO" || temp == "NOPE" || temp == "INCORRECT" || temp == "YOU ARE NOT" || temp == "YOU ARE INCORRECT" || temp == "NEGATIVE" || temp == "NEGATORY")
{
cout << "\nOk, then how many sales quarters are we dealing with? ";
getline(cin, temp);
stringstream(temp)>>SALES_QUARTERS;
}
cout << endl << endl;
// This sets up the 2d array.
quarterly_sales_form = new double *[COMPANY_DIVISIONS];
for (int count = 0; count < COMPANY_DIVISIONS; count ++)
{ quarterly_sales_form[COMPANY_DIVISIONS] = new double [SALES_QUARTERS]; }
read_company_divisions_and_sales_quarters(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS);
// write_company_divisions_and_sales_quarters_to_array(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS); // I'll add this feature later.
cout << "\n\nHere's what you entered:\n\n";
display_quarterly_sales_array(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS);
// Since we used a series of pointers, we need to free the allocated space back up.
for (int count = 0; count < COMPANY_DIVISIONS; count ++)
{ delete[] quarterly_sales_form[COMPANY_DIVISIONS]; }
delete[] quarterly_sales_form;
return 0;
}
/*############################################
# read_company_divisions_and_sales_quarters #
############################################*/
void read_company_divisions_and_sales_quarters(double **array, int DIVISIONS, int QUARTERS)
{
for (int count = 0; count < QUARTERS; count++)
{
for (int index = 0; index < DIVISIONS; index++)
{
cout << "\nPlease enter the sales Company Division #" << count+1 << " brought in for Sales Quarter #" << index+1 << " ";
getline(cin, temp);
stringstream(temp) >> array[count][index];
}
}
}
/*################################
# display_quarterly_sales_array #
#################################*/
void display_quarterly_sales_array(double **array, int DIVISIONS, int QUARTERS)
{
for (int count = 0; count < DIVISIONS; count++)
{
cout << "\nCompany division #" << count+1 << ":\n";
for (int index = 0; index < QUARTERS; index++)
{ cout << array[count][index] << ", "; }
}
}
Can some kind soul please tell me what I'm doing wrong?
{ quarterly_sales_form[COMPANY_DIVISIONS] = new double [SALES_QUARTERS]; }
In this line, COMPANY_DIVISIONS should be count.
In addition to what Dan Hulme said, it seems this line
stringstream(temp) >> array[count][index];
should really be
std::istringstream(temp) >> std::skipws >> array[index][count];
In addition to using std::istringstream rather than std::stringstream and making sure that an lvalue is at hand, which isn't strictly needed until the type read becomes more interesting, this also reverses the indices: index runs over COMPANY_DIVISIONS and count over SALES_QUARTERS.
The real question is, of course: Who hands out assignments like this? Pointer manipulations and allocations are best left to low-level library writers. This is C++ not C: we can and should use abstractions. Getting this code exception safe is a major challenge and there is no point in teaching people how to write broken (e.g. exception unsafe) code.