So I am having a problem with passing my arrays to my functions and I cant seem to get it to work
I have this so far...
int getProfit();
int getTotal();
int main(){
int profits[12];
string monthNames[12] = {"January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int quarterProfits[4];
cout << "Welcome to my comic store!\n" << endl;
getProfit();
getTotal();
}
int getProfit(){
for(int i = 0; i < 12; i++){
cout << "Enter the profit for month " << i + 1 << ": " << endl;
cin >> profits[i];
if(profits[i] < 0){
cout << "Invalid profit! Please enter the profit for month " << i + 1 << ": "<< endl;
cin >> profits[i];
}
}
}
int getTotal(){
int profitTotal = 0;
for(int i = 0; i < 12; i++){
profitTotal = profitTotal + profits[i];
}
return profitTotal;
}
So right now I am trying to pass my profits array to my getTotal function but nothing I try seems to work.
I think the problem may be that I am getting my profits array from another function (getProfit), but i'm not sure.
Any improvements or suggestions are welcome. Thanks!
The problem is that you are not declaring profits as a parameter, a function does not know about its environment only about its parameters and what it is supposed to do, so, you have to send the array as a parameter
/*
call it in the main function as
getProfit(profits); (don't forget modify the prototype)
Note: do it same in getTotal
*/
int getProfit(int *profits) {
for(int i = 0; i < 12; i++) {
cout << "Enter the profit for month " << i + 1 << ": " << endl;
cin >> profits[i];
while (profits[i] < 0) {//if only checks once
cout << "Invalid profit! Please enter the profit for month " << i + 1 << ": ";
cin >> profits[i];
}
}
}
See this page for further information about pointers and arrays
Related
For my assignment, I cannot allow a user to enter a negative value for rainfall in the array. I'm suppose to restart the loop over again as if they didn't enter anything to start off with and have them try again.
When I try it, I enter a negative value the first time, it restarts it for January, but after that I can enter more negatives and it just keeps asking me to keep entering for the rest of the months. I want it to keep restarting if I keep giving it negative numbers, until I start entering positive numbers. Then, that's when I display the total and average.
{
const int SIZE = 12;
string months[SIZE] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
string Month[SIZE];
double Rainfall[SIZE];
int counter;
double totalRainfall = 0.0;
double averageRainfall = 0.0;
for (counter = 0; counter < SIZE; counter++)
{
cout << "Enter the total rainfall for " << months[counter] << ": ";
cin >> Rainfall[counter];
if (Rainfall[counter] < 0.0)
{
cout << "Sorry, can't be a negative!" << endl;
do
{
for (counter = 0; counter < SIZE; counter++)
{
cout << "Enter the total rainfall for " << months[counter] << ": ";
cin >> Rainfall[counter];
}
} while (Rainfall[counter] < 0.0);
}
averageRainfall = totalRainfall / SIZE;
cout << "Total rainfall for the whole year was: " << totalRainfall << setprecision(3) << endl;
cout << "The average inches of rainfall was: " << averageRainfall << setprecision(3) << endl;
system("pause");
return 0;
}
}
Here is a basic working example to what you are trying to accomplish. Rather than adding and then checking, I checked first before I add the value into the array. I created a simple function to make sure that the input is a valid number. If its not, simply reset the counter back to 0 and the for loop will start from the beginning.
Edit: add a try and catch block to make sure input is a proper double
#include <iostream>
#include <string>
bool is_valid_num(std::string str){
//check if its a number
for(char c : str){
if((c < 48 || c > 57 ) && c != 46) return false;
}
//if you want it to also not be equal to 0
// if(std::stoi(str) < 0) return false;
return true;
}
int main() {
const int SIZE = 12;
std::string months[] = { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
std::string temp_input;
double rainfall[12];
double total_rainfall = 0.0;
for(int i = 0; i < SIZE; i++){
std::cout << "enter rainfall for " << months[i] << ": ";
std::cin >> temp_input;
//restart back to january
if(!(is_valid_num(temp_input))) i = -1;
rainfall[i] = std::stod(temp_input);
total_rainfall += std::stod(temp_input);
}
std::cout << "avg rainfall: " << total_rainfall / 12.0 << "\n";
std::cout << "total rainfall " << total_rainfall << "\n";
}
Well that's your while loop where you are stuck, when second time you put negative values you are already in while loop so it wont print sorry.... rather it will restart while loop from counter = 0,
rather do this
if (Rainfall[counter] < 0.0)
{
cout << "Sorry, can't be a negative!" << endl;
counter--;// either put zero if you want to restart whole loop else decrement
continue;
}
I'm having trouble with this homework program and now I'm stuck in what I should do. The program reads in a list of 12 doubles from a file. Each double represents the total rainfall in inches for the 12 months of the year in month order. The 12 doubles should be written into an array. The requirements are below.
This is the code that I have right now and I'm have no idea on what needs to go into the Function declarations displayRainfall, bubbleSort, and swap and what else needs to go into main:
// Headers
#include <iostream> // cout, cin
#include <cstdlib> // exit()
#include <string> // strings
#include <fstream> // file processing
#include <iomanip> // stream manipulation
using namespace std;
// Global variables
const int MAX_MONTHS = 12; // months for rainfall
const string FILENAME = "TotalMonthlyRainfall2014.txt"; // The name of the file that is read
// Function declarations
int loadMonthlyRainfall (double rain[MAX_MONTHS], string fileName, int maxMonths);
void displayRainfall(string months[MAX_MONTHS], double rain[MAX_MONTHS], int monthCount);
void bubbleSort(double rain[MAX_MONTHS], int size);
void swap(int& a, int& b);
int main()
{
int monthCount = 0;
string months[MAX_MONTHS] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
double rain[MAX_MONTHS];
loadMonthlyRainfall(rain, FILENAME, MAX_MONTHS);
// Make sure we place the end message on a new line
cout << endl;
// The following is system dependent. It will only work on Windows
system("PAUSE");
return 0;
}
int loadMonthlyRainfall(double rain[MAX_MONTHS], string fileName, int maxMonths)
{
ifstream inFile; // Input file stream
int numMonths = 0;
// Open file
inFile.open(fileName);
if (!inFile)
{
throw "Can not open file";
}
//
for (int r = 0; r < MAX_MONTHS; r++)
{
inFile >> rain[r];
}
// Close the file
inFile.close();
for (int r = 0; r < MAX_MONTHS; r++)
{
cout << rain[r] << " ";
}
cout << endl;
return numMonths;
}
void displayRainfall(string months[MAX_MONTHS], double rain[MAX_MONTHS], int monthCount)
{
}
void bubbleSort(double rain[MAX_MONTHS], int size)
{
}
void swap(int& a, int& b)
{
}
The program should do the following with the data:
Calculate the average rainfall for the year.
Determine which month had the lowest amount of rainfall.
Determine which month had the highest amount of rainfall.
Sort the array of rainfall in descending order (highest rainfall first) using a bubble sort.
Neatly display the average, minimum, and maximum rainfall. Be sure to display the month of the minimum and maximum rainfalls. Then display a table of month and rainfall amount from the sort.
Each of the monthly rainfall, average, minimum, and maximum
rainfalls should be displayed to two decimal places.
The output should look something like this:
Monthly Rainfall for 2014
Minimum: September 0.06
Maximum: August 4.34
Monthly Average for Year: 1.77
Sorted by Total Rainfall
Month Inches
August 4.34
May 3.40
June 3.26
November 2.13
October 2.09
April 1.74
March 1.45
December 1.13
July 0.98
February 0.41
January 0.33
September 0.06
Call bubbleSort(rain, MAX_MONTHS); in main with these changes :
void displayRainfall(string months[MAX_MONTHS], double rain[MAX_MONTHS], int monthCount)
{
//title
cout << "Monthly Rainfall for 2014" << endl;
//print minimum rainfall
cout << "Minimum: " << months[MAX_MONTHS-1] << " "<< rain[MAX_MONTHS-1] << endl;
//print maximum rainfall
cout << "Maximum: " << months[0] << " "<< rain[0] << endl;
//get and print average rainfall
double avg = 0.0;
for (int i = 0; i < MAX_MONTHS; i++)
{
avg+=rain[i];
}
avg = avg/MAX_MONTHS;
cout << "Monthly Average for Year: " << avg << endl;
//print ordered rainfall by month
cout << "Sorted by Total Rainfall" << endl;
cout << "Month" << setw(10) << "Inches" << setw(10) << endl;
for (int i = 0; i < MAX_MONTHS; i++)
{
cout << setw(10) <<months[i] << setw(10) << rain[i] << endl;
}
}
void bubbleSort(double rain[MAX_MONTHS], int size)
{
string months[MAX_MONTHS] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
//sort rainfall descending
for (int i = 1; i < size; i++)
{
for (int j = 0; j < size - i; j++)
{
if (rain[j] < rain[j+1])
{
swap(rain[j], rain[j+1]);
swap(months[j], months[j+1]);
}
}
}
//called inside bubbleSort because months and rain are sorted in scope
displayRainfall(months, rain, 0);
}
void swap(int& a, int& b)
{
int& temp = a;
a = b;
b = temp;
}
I've come across a little problem, how do I print the winning candidate's name? See the instructions here are, input five names, their number of votes and percentage of votes, whoever has the highest wins. I don't know if I did my code right, but it works.. well except for the name part. I've tried everything from a lot of for loops to transfer the array or what.
I'm almost done with the code.
Here's the code
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char candidates[50];
int votes[5]={0};
float percent[5]={0};
int a,b,c,d,e,i;
int maxx;
int champ=0;
char winner[50];
cout << "Enter the candidates' last names: ";
cout << endl;
for(a=1;a<=5;a++)
{
cout << a << ". ";
cin >> candidates;
}
cout << endl;
cout << "Enter their number of votes: " << endl;
for(b=1;b<=5;b++)
{
cout << b << ". ";
cin >> votes[b];
}
cout << endl;
cout << "percentage of votes: " << endl;
for(c=1;c<=5;c++)
{
cout << c << ". ";
percent[c]=votes[c]*0.2;
printf("%.2f\n", percent[c]);
}
cout <<"Candidates\t\tVotes\t\t% of Votes" << endl;
for(int k=1;k<=5;k++)
{
cout << candidates[k] << "\t\t\t" << votes[k] << "\t\t\t";
printf("%.2f\n", percent[k]);
}
maxx=percent[0];
for(d=1;d<=5;d++)
{
if(maxx<percent[d]);
{
//what happens here?
}
}
return 0;
}
You should keep a 2d array of characters or array of string for storing candidate names instead of a 1-d array.
char candidates[5][10]; //
for(int i = 0; i < 5; i++)
{
cin >> candidates[i];
}
Then keep a variable to store index for winning candidate
int winIndex = 0;
int winPercent = 0;
for(int i = 0; i < 5; i++)
{
if(percent[i] > winPercent)
{
winPercent = percent;
winIndex = i;
}
}
Finally print name of winning candidate;
cout << candidates[winIndex];
In object oriented approach, you may create a class with following information
class Candidate
{
string name;
int votes;
float percent;
};
Use string candidates[50]; instead of char candidates[50];
then cin >> candidates[a];
I want the program to work so that I can turn any worded month to its equivalent number.
#include <iostream>
using namespace std;
int main()
{
char month[20];
int INT_month;
cout << "Enter a month: (ex. January, February)";
cin >> month; // Let's say the input is February
if (month == "February")
INT_month = 2;
cout << "The month in its' integral form is " << INT_month << endl;
// INT_month = 2130567168 // WHY DOES IT DO THIS????
return 0;
}
One way to do it is creating a vector of month names, and using the look-up index plus one as the month number:
vector<string> months = {
"january", "february", "march", ...
};
string search = "march";
auto pos = find(months.begin(), months.end(), search);
if (pos != months.end()) {
cout << "Month number: " << distance(months.begin(), pos) + 1 << endl;
} else {
cerr << "Not found" << endl;
}
This prints 3 (demo on ideone).
I am working on a grade book project that has 5 students that I want to read the names in for and then with an inner loop grab 4 grades for each student. Something is not working on this loop. This what I am getting:
Please enter the name for student 1: Dave
Please enter the grade number 1 for Dave: 100
Please enter the grade number 2 for Dave: 100
Please enter the grade number 3 for Dave: 100
Please enter the grade number 4 for Dave: 10
Please enter the name for student 2: James
Please enter the grade number 5 for James: 100
Please enter the name for student 3: Sam
Please enter the grade number 5 for Sam: 100
Please enter the name for student 4: Jack
Please enter the grade number 5 for Jack: 100
Please enter the name for student 5: Mike
Please enter the grade number 5 for Mike: 100
It should grab 4 grades before it jumps to the next student. I have not been able to figure this out for the last couple hours. Here is the code I have so far:
#include <iostream>
#include <string>
using namespace std;
const int STUDENTS = 5; //holds how many students we have
const int SCORES = 4;
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS);
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
getNames(names, student1, student2, student3, student4, student5, SCORES, STUDENTS);
// Make sure we place the end message on a new line
cout << endl;
// The following is system dependent. It will only work on Windows
system("PAUSE");
return 0;
}
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS)
{
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
if (i == 0)
{
int count1 = 0;
for (count1; count1 < SCORES; count1++)
{
cout << "Please enter the grade number " << count1+1 << " for " << names[i] <<": ";
cin >> student1[count1];
cout << endl;
}
}
else if (i == 1)
{
int count2 = 0;
for (count2; count2 < SCORES; count2++);
{
cout << "Please enter the grade number " << count2+1 << " for " << names[i] <<": ";
cin >> student2[count2];
cout << endl;
}
}
else if (i == 2)
{
int count3 = 0;
for (count3; count3 < SCORES; count3++);
{
cout << "Please enter the grade number " << count3+1 << " for " << names[i] <<": ";
cin >> student3[count3];
cout << endl;
}
}
else if (i == 3)
{
int count4 = 0;
for (count4; count4 < SCORES; count4++);
{
cout << "Please enter the grade number " << count4+1 << " for " << names[i] <<": ";
cin >> student4[count4];
cout << endl;
}
}
else
{
int count5 = 0;
for (count5; count5 < SCORES; count5++);
{
cout << "Please enter the grade number " << count5+1 << " for " << names[i] <<": ";
cin >> student5[count5];
cout << endl;
}
}
}
}
Thanks for any help on this!
There's some pretty rough stuff going on in here, but the problem is that you have a semi-colon on all your inner loops except the first one:
for (count2; count2 < SCORES; count2++);
Remove the semi-colon, and the stuff in the braces will become part of the loop.
I'm going to suggest you make your code a little tidier and less error-prone by chucking all those function arguments into their own array when you enter the function, like this:
double *scores[5] = { student1, student2, student3, student4, student5 };
Then you take OUT all that repetition - the copy/paste is what caused your problems to begin with:
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
for (int s = 0; s < SCORES; s++)
{
cout << "Please enter the grade number " << s+1 << " for " << names[i] <<": ";
cin >> scores[i][s];
cout << endl;
}
}
Why can't you use two nested loops like
for (int studix=0, stduix<STUDENTS; studix++) {
//...
for (int gradix=0; gradix<SCORE; gradix++) {
//...
}
//....
}
BTW, the condition could be a more complex one, e.g. with the internal loop being
bool goodgrade=true;
for (int gradix=0; goodgrade && gradix<SCORE; gradix++) {
// you could modify goodgrade or use break; inside the loop
}
Don't forget the possible use of continue and break inside a loop.
And please, take time to read some good C++ programming book
Building on Basile's answer and my comments:
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
double *gradeArray[STUDENTS];
gradeArray[0] = student1;
gradeArray[1] = student2;
gradeArray[2] = student3;
gradeArray[3] = student4;
gradeArray[4] = student5;
for (int studix=0, stduix<STUDENTS; studix++) {
// get the name of the student
for (int gradix=0; gradix<SCORE; gradix++) {
// put the grades in gradeArray[studix][gradix]...
}
//....
}
Yes, I know about 2 D arrays, but I am trying to make explicit how this can be done with "five individual arrays". Clumsy, but I believe this works.