I'm sort of having a hard time with my program, and I would really appreciate any help. Forgive me for my really bad code, I'm new.
#include <iostream>
#include <string.h>
using namespace std;
//functions
string getFirstName();
string getLastName();
int getScores();
double calculateSum(double sum, double score);
double calculateAvg(double avg, double sum);
char calculateGrade(double score, char grade);
void displayResults(string firstname, string lastname, double avg, char
grade);
int main(){
//variables
string firstname;
string lastname;
int score;
double sum;
double avg;
char grade;
//functions and parameters
firstname = getFirstName();
lastname = getLastName();
score = getScores();
sum = calculateSum(sum, score);
avg = calculateAvg(avg, sum);
grade = calculateGrade(score, grade);
displayResults(firstname,lastname,avg,grade);
while (true)
{
firstname = getFirstName();
cin >> firstname;
if (firstname == "done")break;
lastname = getLastName();
cin >> lastname;
sum=0.0;
for (int i = 0; i<10; i++)
{
double score;
cin >> score;
sum - calculateSum(sum, score);
sum+=score;
//sum = sum+score;
}
avg = calculateAvg(avg, sum);
avg = sum/10.0;
displayResults(firstname,lastname,avg,grade);
}
return 0;
}
string getFirstName()
{
string firstname;
cout<<"Enter first name: " << endl;
cin >>firstname;
return firstname;
}
string getLastName()
{
string lastname;
cout<<"Enter last name: ";
cin >>lastname;
return lastname;
}
int getScores()
{
int score;
cout <<"Input score: ";
cin >>score;
return score;
}
double calculateSum(double sum, double score)
{
sum+=score;
return sum;
}
double calculateAvg(double avg, double sum)
{
avg = sum/10.0;
return avg;
}
char calculateGrade(double score, char grade)
{
if (score >= 90)
grade = 'A';
else if (score >=80)
grade = 'B';
else if (score >=70)
grade = 'C';
else if (score >=60)
grade = 'D';
else
grade = 'F';
return grade;
}
void displayResults(string firstname, string lastname, double avg, char
grade)
{
cout<<firstname<< lastname<<": "<<avg << grade;
}
I don't really understand loops, or how they work, so what I have written down for my loop was just given to us by our professor, so if anyone could please explain/dissect it then I would really appreciate it! I want to know how to do this, not just have answers handed to me.
So, I'm not sure why my program won't properly execute. I've listed the call functions and all of the functions seem to be correct. My loops are inside of the main as well, but I don't know why they're not working. Also, when I run it, I don't have any errors.
It seems to be stuck on the enter first name and enter last name part, but I'm not sure why.Again, I'd really appreciate any help, thank you!
You code was full of bugs, but I will lead you through it step by step.
First things first, we will need to check what each function does :
1- string getFirstName(); Prompt the user to enter his/her first name. Working
2- string getLastName(); Prompt the user to enter his/her last name. Working
3- int getScores(); Prompt the user to enter his/her score. Working
4- double calculateSum(double sum, double score); Adds both the sum and the score. What you did in your implementation of the function :
{
sum+=score;
return sum;
}
Will only be valid if you pass variable sum by reference. There is no need to get into this now. An easier way to do it is to do so :
{
double add = sum + score;
return add;
}
Next up :
5- double calculateAvg(double avg, double sum); Divides sum by 10 to get the average, there's no need to pass avg as a parameter as that's what we are going to return.
The function should be written as double calculateAvg(double sum);
6- Same goes char calculateGrade(double score, char grade);. There's no need to pass grade. It will be written aschar calculateGrade(double score);.
7- Last one : void displayResults(string firstname, string lastname, double avg, char grade); Working
Ok, now to the main() function :
You'll need to declare all of your variables like so
string firstname;
string lastname;
double score;
double sum ;
double avg ;
char grade;
No need to use our functions here, we are going to use them inside our while loop.
Into the while loop :
There's no need to use cin>> with any of variables cause that's what our functions is doing for us.
When the user enters done as his/her first name exit the loop.
Else, create a for loop that iterates 10 times asking the user to input his/her score, add this score to the sum and then after the for loop ends calculate both the average and the grade and print them out.
The final working version of your code should look like this, if you still have any further questions don't hesitate to ask.
#include <iostream>
#include <string.h>
using namespace std;
//functions
string getFirstName();
string getLastName();
int getScores();
double calculateSum(double sum, double score);
double calculateAvg(double sum);
char calculateGrade(double score);
void displayResults(string firstname, string lastname, double avg, char grade);
int main(){
//variables
string firstname;
string lastname;
double score;
double sum ;
double avg ;
char grade;
while (true)
{
firstname = getFirstName();
if (firstname == "done")
break;
lastname = getLastName();
sum=0.0;
for (int i = 0; i<10; i++)
{
score = getScores();
sum = calculateSum(sum, score); //sum = sum+score;
}
avg = calculateAvg(sum);
grade = calculateGrade(avg);
displayResults(firstname,lastname,avg,grade);
}
return 0;
}
string getFirstName()
{
string firstname;
cout<<"Enter first name: ";
cin >>firstname;
return firstname;
}
string getLastName()
{
string lastname;
cout<<"Enter last name: ";
cin >>lastname;
return lastname;
}
int getScores()
{
int score;
cout <<"Input score: ";
cin >>score;
return score;
}
double calculateSum(double sum, double score)
{
int add = sum + score;
return add;
}
double calculateAvg(double sum)
{
double avg = sum/10.0;
return avg;
}
char calculateGrade(double score)
{
char grade;
if (score >= 90)
grade = 'A';
else if (score >=80)
grade = 'B';
else if (score >=70)
grade = 'C';
else if (score >=60)
grade = 'D';
else
grade = 'F';
return grade;
}
void displayResults(string firstname, string lastname, double avg, char grade)
{
cout<<firstname<< lastname<<" - Average : "<<avg << " - Grade : "<< grade<<endl;
}
The loop is just a way of executing the same piece of code over and over again. By putting code in a loop, you do not have to copy and paste it. Any variable changes which happen during one run through a loop are still present during the next.
In your code:
for (int i = 0; i<10; i++)
{
...
}
is your loop. The "..." is code which will be executed over and over.
The big question which needs to be asked with a loop is: How does a loop know how many times to run your code before it exits?
This is what the:
int i = 0; i<10; i++
is about. Though it looks strange it is actually 3 separate commands. The commands are separated by the semi-colon ';'
int i=0
i<10
i++
Command (1) initialize the loop. You are simply setting the variable i, which an integer, to 0.
Command (2) condition to continue looping. If command (2) is true then the loop will execute (and execute again). Your code is saying execute the loop whilst i is less than 10.
Command (3) calculations executed once per loop. We know in Command (1) that you set i to 0. We know in Command (2) that the loop will run while i is less than 10. 0 is less than 10, so the loop will execute... forever. We don't want this, so during Command (3) we increase i. We count the number of times we run the loop.
So your loop will run 10 times in a row, the code inside it and then exit.
Related
asking desire number to become the for loop(how many employee if input is 4 then 4 loop if 3 3 loops), salary formula not working, if else statement for string name to not accept number and vice versa integer to not accept letters. another one of my problem is how can I name the loop for example the question is name hours and rate then the cout should do 1. name hours rate, 2.name hours rate 3.name hours rate... the code is working.. just need some imporvements.
#include <iostream>
#include <cstdlib>
using namespace std;
void displayRules()
{
cout<<"====================="<<endl;
cout<<" EMPLOYEE-SALARY "<<endl;
cout<<"====================="<<endl;
cout<<" "<<endl;
}
int main()
{
char ans;
do
{
system("cls");
displayRules();
struct Employee
{
string name;
double hours;
double rate;
double salary;
Employee *next;
Employee *prev;
};
Employee *head;
head=NULL;
Employee *newEmployee;
Employee *EmpPointer;
Employee *nextEmpPointer;
Employee *prevEmpPointer;
string inpname;
int inpN;
double inphours;
double inprate;
double salary;
salary = (inprate*inphours);
for(int ctr=0; ctr<3; ctr++)
{
cout<<endl;
cout<<"Enter Name: \t\t";
cin>> inpname;
cout<<"Enter # Hours Worked: \t";
cin>> inphours;
if (inphours<0)
{
cout << "Invalid Input! Program Stopped. ";
return 0;
}
cout<<"Enter Rate per Hour: \t";
cin>> inprate;
if (inprate<0)
{
cout << "Invalid Input! Program Stopped. ";
return 0;
}
newEmployee = new Employee;
newEmployee->name=inpname;
newEmployee->hours=inphours;
newEmployee->rate=inprate;
newEmployee->next=NULL;
if (head==NULL)
head=newEmployee;
else
{
EmpPointer=head;
while (EmpPointer->next)
EmpPointer=EmpPointer->next;
EmpPointer->next=newEmployee;
}
}
cout<<endl;
Employee *displayPointer;
displayPointer=head;
system("cls");
cout<<"------------------------------------------------------------"<<endl;
cout<<" =Summary of PAYROLL= "<<endl;
cout<<"------------------------------------------------------------"<<endl;\
cout<<"Employee Name\t"<<"# Hours Worked\t"<<"Rate/Hour\t"<<"Salary\t"<<endl;
while (displayPointer)
{
cout<<displayPointer->name<<"\t\t";
cout<<displayPointer->hours<<"\t\t";
cout<<displayPointer->rate<<"\t\t";
cout<<displayPointer->salary<<endl;
displayPointer=displayPointer->next;
}
cout<<"------------------------------------------------------------"<<endl;
cout<<endl;
cout << "Would you like to run the program again? (Y/N) ";
cin>>ans;
}
while (ans == 'y' or ans == 'Y');
return 0;
}
Note: The salary wasn't being calculated so I fix that.
I broke your code into small functions in which each function only does one thing and one thing only (Single Responsibility Principle).
Also, I introduce function templates that allows you to reuse a function when you provide the type.
Finally, the code is missing a clean up of pointers to prevent memory leaks. Each time you use the keyword new to obtain a pointer to memory, you need later to check if the pointer contains null and if doesn't then use the keyword delete to free that memory, else you end with memory leaks in your code. Therefore, I leave you with the task to write the function that should iterate your employee list and free the memory to prevent memory leaks.
I hope this is useful.
#include <iostream>
#include <cstdlib>
using namespace std;
struct Employee {
string name;
double hours;
double rate;
double salary;
Employee *next;
Employee *prev;
};
void displayRules() {
cout<<"====================="<<endl;
cout<<" EMPLOYEE-SALARY "<<endl;
cout<<"====================="<<endl;
cout<<" "<<endl;
}
// Here we create a function template to make this code more reusable
template <typename T>
T consoleInput(const std::string& prompt) {
T value;
std::cout << prompt;
std::cin >> value;
return value;
}
// Lets create our own assert to exit the app.
void assertGreaterEqualThanZero(const double value, const std::string& prompt){
if (value < 0) {
cout << prompt;
exit(1);
}
}
// Small functions that do one thing only makes coding easy to debug
Employee* createEmployee(string name, int hours, int rate) {
Employee *newEmployee = new Employee;
newEmployee->name=name;
newEmployee->hours=hours;
newEmployee->rate=rate;
newEmployee->salary = (rate * hours);
newEmployee->next=NULL;
// You need to set and maintain ->prev
// if you are thinking on using a double linked list
// else remove it from the structure since is unused.
return newEmployee;
}
// This is a helper function to add new employees to a list
Employee* addToEmployeeList(Employee* list, Employee* newEmployee){
if (list==NULL) {
list = newEmployee;
} else {
Employee *EmpPointer = list;
while (EmpPointer->next)
EmpPointer=EmpPointer->next;
EmpPointer->next=newEmployee;
}
return list;
}
// The only purpose of this function is to print the list provided
void printEmployeList(Employee* employeeList){
Employee *currentEmployee = employeeList;
system("cls");
cout<<"------------------------------------------------------------"<<endl;
cout<<" =Summary of PAYROLL= "<<endl;
cout<<"------------------------------------------------------------"<<endl;
while (currentEmployee){
cout<<"Employee Name\t"<<"# Hours Worked\t"<<"Rate/Hour\t"<<"Salary\t"<<endl;
cout<<currentEmployee->name<<"\t\t";
cout<<currentEmployee->hours<<"\t\t";
cout<<currentEmployee->rate<<"\t\t";
cout<<currentEmployee->salary<<endl;
cout<<"------------------------------------------------------------"<<endl;
currentEmployee=currentEmployee->next;
}
}
// I leave you with this piece that is missing.
// TODO: create function that delete each employee in the list,
// then deletes the list in order to prevent memory leaks
int main() {
char ans;
do {
system("cls");
displayRules();
Employee *employeeList;
employeeList=NULL;
for(int ctr=0; ctr<3; ++ctr) {
// Lets declare and instantiate when we need it.
string name = consoleInput<string>("Enter Name: \t\t");
// No need to use inp (as inphours) in front of your variables
// It makes it harder to read. Just put hours as a name.
double hours = consoleInput<double>("Enter # Hours Worked: \t");
assertGreaterEqualThanZero(hours, "Invalid Input! Program Stopped.");
double rate = consoleInput<double>("Enter Rate per Hour: \t");
assertGreaterEqualThanZero(rate, "Invalid Input! Program Stopped. ");
Employee *newEmployee = createEmployee(name, hours, rate);
employeeList = addToEmployeeList(employeeList, newEmployee);
}
cout << endl;
printEmployeList(employeeList);
cout << "Would you like to run the program again? (Y/N) ";
cin>>ans;
} while (ans == 'y' or ans == 'Y');
return 0;
}
#include <iostream>
using namespace std;
int main ()
{
int quantity;
again:
cout<<"Enter the quantity: ";
cin>>quantity;
If(quantitiy == '1' )
{
total = quantity*price
}
else
{
goto again;
}
return 0;
}
How could I declare all the numbers in one if statement?
Pretty much everything in your code is wrong and needs fixing. Use a do..while loop instead of goto. Correct your typos on If and quantitiy. Declare and initialize the missing total and price variables. Add the missing ; on the total assignment. And '1' and 1 are two completely different types and values.
Try something more like this instead:
#include <iostream>
using namespace std;
int main ()
{
int quantity;
double price = ...; // for you to decide, unless you ask the user...
double total = 0;
do {
cout << "Enter the quantity: ";
cin >> quantity;
}
while (quantity != 1);
total = quantity*price;
return 0;
}
Of course, it really doesn't make sense to prompt the user for a quantity and then only accept 1. You probably want something more like this:
#include <iostream>
using namespace std;
int main ()
{
int quantity;
double price = ...; // for you to decide, unless you ask the user...
double total = 0;
do {
cout << "Enter the quantity (0 to stop): ";
cin >> quantity;
if (quantity == 0) break;
total += (quantity * price);
}
while (true);
return 0;
}
I'm currently working on an assignment and it's meant to take the concept of a car body shop offering different trim packages at different prices, the program is meant to use a pretest loop to stop the function if a user inputs a code that isn't already on the array, and then the user inputs the base price of their car and the program is meant to add the base price, the trim price and a 15% sales tax and give the new user their total cost. If I only had to create a function that displayed array's I think I'd have no trouble but I'm currently tearing my hair out trying to wrap my head around how to get all the different functions to work together
currently my algorithm is
1)enter the base price of car
2.) Enter the trim package code
3.) searchIndex=0
while OptionPackageCodeArray =[search index]
searchIndex++
end loop
if searchIndex<5
input packageCode
OptionPackageCode[searchIndex] = packageCode
else
Display error "This code does not exist"
end if
4.) Determine totalCost
PackageCostArray[searchIndex] + basePrice = costwithPackage
totalCost = costwithPackage*0.15
5.) display total cost
"The price of your car with Trim is" : totalCost
end loop
and the actual C++ I have written so far is
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare variables
double basePrice = 0.00;
string OptionPackageCodeArray[] = {"BB", "SP", "NP", "HE", "UC"};
double PackageCostArray [] = {1500.00, 3250.00, 4575.00, 7500.00, 5220.00};
double totalCost = 0.00
//prompt for base price
cout << "Enter base price:";
cin>>basePrice;
cout <<"enter package code: BB, SP, NP, HE, UC";
cin >> OptionPackageCodeArray;
}
however I'm stuck at this point
if anybody has any suggestions I'd be happy to take them.
you just write the code step by step. you can read blow code for reference.
double basePrice = 0.00;
static const int num = 5;
string OptionPackageCodeArray[num] = {"BB", "SP", "NP", "HE", "UC"};
double PackageCostArray [num] = {1500.00, 3250.00, 4575.00, 7500.00, 5220.00};
double totalCost = 0.00;
while(true)
{
//prompt for base price
cout << "Enter base price:";
cin>>basePrice;
std::string package;
cout <<"enter package code: BB, SP, NP, HE, UC"<<std::endl;
cin >> package;
int i = 0;
for (; i < num; i++)
{
if (OptionPackageCodeArray[i] == package)
{
break;
}
}
if (i == num)
{
break;
}
else
{
std::cout<<(basePrice + PackageCostArray[i]) * 0.15<<std::endl;
}
}
I am currently studying c++ but I fell behind a little bit, so I apologize if my question is obvious.
I have to create a program that asks for a student's name, GPA, Year of admission, and get a random 5 digit number generated for that person. The number of students will not exceed 42.
My program compiled (somehow) and I am able to get the error for invalid menu selection, however, whenever I give a valid selection (currently 1) nothing happens.
Maybe I am missing something, this is why I need help.
Here is my code.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//print all the menu options
void print_menu()
{
cout<<"\nRCNJ Registrar Menu:"<<"\n"
<<"\n"
<<"[1] Add a student"<<"\n"
<<"[2] Display all students"<<"\n"
<<"[3] Display by year"<<"\n"
<<"[4] Display statistics"<<"\n"
<<"[5] Quit"<<"\n";
}
//get and return the student's name
void get_name(string& student_name) //call student_name after that.
{
cout<<"Please enter the sudent's name: ";
cin >> student_name;
cout<<"\n";
}
//validate and return gpa
double get_gpa()
{
double student_gpa = 0;
cout<<"Please enter the GPA: ";
cin >>student_gpa;
cout<<"\n";
while (student_gpa > 4 || student_gpa < 0)
{
cout<<"Please enter a valid GPA for the student (0.00 - 4.00): ";
cin >> student_gpa;
cout<<"\n";
}
return student_gpa;
}
//validateand return year
int get_year()
{
int student_year = 0;
cout<<"Please enter the year: ";
cin >> student_year;
cout<<"\n";
while (student_year >2016 || student_year <1972)
{
cout<<"Please enter a valid year (min 1972, max 2016): ";
cin >> student_year;
cout<<"\n";
}
return student_year;
}
//generate the student's R#
int generate_number()
{
int r_number;
srand (time(NULL));
r_number = rand() % 89999 + 10000;
return r_number;
}
//save info. Include get_name, get_gpa, get_year
void input_new_student()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int s_name, s_gpa, s_year, r_num;
get_name(student_name);
get_gpa();
get_year();
generate_number();
}
//display all students in the proper format
void print_all()
{
}
//get a year as selection and print all students that are the same year
void print_by_year()
{
}
//display statistics based on entered students
void print_statistics()
{
}
//validate and return the menu option selected by the user.
//it should call print_menu defined earlier
int get_selection(int menu_choice)
{
menu_choice = 0;
cout<<"\n"
<<"Selection: ";
cin >> menu_choice;
cout<<"\n";
while (menu_choice > 5 || menu_choice< 1)
{
cout<<" Menu choice is invalid. Please re-enter (1 - 5): ";
cin>> menu_choice;
cout<<"\n";
}
return menu_choice;
}
int main()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int menu_choice;
int s_name=0;
int s_gpa=0;
int s_year=0;
int r_num=0;
string nameArray[42];
s_name++;
double gpaArray[42];
s_gpa++;
int yearArray[42];
s_year++;
int ramapoArray[42];
r_num++;
print_menu();
get_selection(menu_choice);
switch (menu_choice)
{
case 1:
input_new_student();
nameArray[s_name] = student_name;
gpaArray[s_gpa] = student_gpa;
yearArray[s_year] = student_year;
ramapoArray[r_num] = r_number;
break;
}
return 0;
}
I dont have permission to comment, hence adding it here.
In you main(),
get_selection(menu_choice);
switch (menu_choice)
You return menu_choice, but there is none to take the value, you end you using garbage value as it is uninitialized.
So two ways you can do it, either by passing the address/reference of menu_choice or by return value. try either of these it should work, though I have not gone through the rest of your program.
As suggested by others, try a debugger e.g. gdb?
for a class assignment I have to write a class definition. Its called Employee class, something really basic for my first c++ class.
My problem is in the first forloop, when I try to adjust the salary based on the new percentage.
The variables inside the class don't change after that. I don't know what could be wrong anymore.
The code is:
#include <iostream>
#include <string>
using namespace std;
class Employee
{
private:
int emplSalary;
string employeeName;
public:
Employee();
Employee(string name,int salary);
string getName();
int getSalary();
void newSalary(int percent);
void input();
void output();
};
Employee::Employee()
{
emplSalary=0;
employeeName="";
}
Employee::Employee(string name,int sal)
{
employeeName=name;
emplSalary =sal;
}
string Employee::getName()
{
return employeeName;
}
int Employee::getSalary()
{
return emplSalary;
}
void Employee::newSalary(int percent)
{
emplSalary= emplSalary *(1+(percent/100));
cout<<"I calculated"<<endl;
/*
if(percent < 0)
{
cout<<"Invalid Percentage";
cout<<"I calculated"<<endl;
}
else
{
emplSalary= emplSalary *(1+(percent/100));
cout<<"I calculated"<<endl;
}
*/
}
void Employee::input()
{
cout << "Enter Name: ";
cin>> employeeName;
cout<<"\n";
cout<<"Enter Salary: " ;
cin>>emplSalary;
cout<<"\n";
}
void Employee::output()
{
cout << "Name: " << employeeName <<" : "<< "Salary: " << emplSalary << endl;
cout<<"\n";
}
int main()
{
const int NUMBER_EMPLOYEE =1;
Employee employees[NUMBER_EMPLOYEE];
int percent;
cout<<"Welcome to Employee program. Enter Name and Salary when prompted."<<endl;
cout<<"\n";
cout<<"\n";
for (int i=0; i<NUMBER_EMPLOYEE; i++)
{
employees[i]=Employee();
employees[i].input();
cout<<"What percentage to raise the salary: ";
cin>>percent;
employees[i].newSalary(percent);
}
for (int i=0; i<NUMBER_EMPLOYEE; i++)
{
employees[i].output();
}
return EXIT_SUCCESS;
}
and the output is:
Welcome to Employee program. Enter Name and Salary when prompted.
Enter Name:
Enter Salary:
What percentage to raise the salary: I calculated
Name: : Salary: 0
The problem is in this line:
emplSalary= emplSalary *(1+(percent/100));
Because percent is an int, you are doing all integer math.
Suppose percent was 50.
The innermost part of your expression ends up being 50/100, which is 0 in integer math.
(You intended for the result to be 0.50).
To fix this, change the type of percent to be double.
Alternately, you can change 100 to be 100.0 (making it a double):
emplSalary= emplSalary *(1+(percent/100.0));
emplSalary= emplSalary *(1+(percent/100));
This line, if your percent is less than 99, percent/100 will be zero, that's why it has no affect to your result. You may want to use double type for your emplSalary and percent.
emplSalary= emplSalary *(1+(percent/100));
You're performing integer arithmetic there (emplSalaray and percent are both of type int). This means that percent / 100 will (unless percent is greater 99) always evaluate to 0. So the equation ends up being emplSalary = emplSalary * 1.
First, note that when the original salary is zero (which is what happens when you write employees[i]=Employee() and the default constructor sets the salary to 0), raises of any percentage will always remain zero,
Second, note that dividing an int by another int will perform integer arithmetic, so the quotient gets truncated. Raises between 0 and 100 percent will therefore be rounded to 0%. Divide by 100.0 instead of 100 to resolve that problem.