How do I enter a loop in another loop? - c++

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int employeeNum = 0; int totalEmployees = 0;
double hourlyRate = 0.0; double totalhoursWork = 0.0;
double hoursWork = 0.0; double totalnetPay = 0.0;
double grossPay = 0.0; double averagehoursWork = 0.0;
double netPay = 0.0; double totalwithHoldings = 0.0;
double withHoldings = 0.0; double overTime = 0.0;
int x = 0;
while(employeeNum!= 9999)
{
cout <<" Enter Employee Number (9999 to Stop):";
cin >> employeeNum;
if(employeeNum ==9999)
break;
cout <<"Enter hourly rate:";
cin >> hourlyRate;
cout <<"Enter hours worked:";
cin >> hoursWork;
cout <<"Employee Number:"<<employeeNum << endl;
if(hoursWork <= 40)
{
grossPay= hoursWork * hourlyRate;
cout <<" Gross Weekly Pay=" << fixed <<setprecision(2)<< grossPay << endl;
}
else if (hoursWork > 40)
{
overTime = hoursWork-40;
grossPay = (overTime * 1.5 + 40)* hourlyRate;
cout <<" Gross Weekly Pay="<< fixed <<setprecision(2)grossPay << endl;
}
if( grossPay > 1000.00)
{
withHoldings= grossPay*0.28;
}
else if( grossPay <= 1000.00)
{
withHoldings= grossPay*0.21;
}
netPay= grossPay-withHoldings;
cout <<" Net Weekly Pay="<<fixed << setprecision(2) << netPay << endl;
totalhoursWork+=hoursWork;
totalnetPay+=netPay;
totalwithHoldings+= withHoldings;
averagehoursWork= totalhoursWork/totalEmployees;
totalEmployees++;
}
averagehoursWork= totalhoursWork/totalEmployees;
for (int x = 1; x < 44; x = x + 1)
cout <<"*";
cout << endl;
cout <<"Total Employees Entered=" << totalEmployees << endl;
cout <<" Total Hours Worked="<< fixed << setprecision(2) << totalhoursWork << endl;
cout <<" Average Hours Worked="<< fixed << setprecision(2) << averagehoursWork << endl;
cout <<" Total Net Pay="<<fixed << setprecision(2) << totalnetPay << endl;
cout <<" TotalwithHoldings=" << fixed << setprecision(2)<< totalwithHoldings << endl;
for (int x = 1; x < 44; x = x + 1)
cout <<"*";
cout << endl;
system("pause");
return 0;
}
Hourly rate must be greater than $7.25 and less than $100.00. Hours worked must be greater than 0 and less than 120. If the user enters invalid data display and appropriate error message and ask the user to re-enter. What statement should I use for this portion and where should I put it??

You can use Cin and Cout for Input and output,, just use do While loop
int employeeNum = 0;
do
{
Console.WriteLine("enter Employee /Number 9999 to STOP");
employeeNum = int.Parse(Console.ReadLine());
if (employeeNum == 9999)
break;
Console.WriteLine("enter hourly rate ");
double hourRate = Double.Parse(Console.ReadLine());
} while (employeeNum != 9999);

You can do something like this:
cout << "Enter hourly rate:";
cin >> hourlyRate;
while (hourlyRate <= 7.25 || hourlyRate >= 100) {
cout << endl << "Reenter hourly rate (must be in (7.25 - 100))";
cin >> hourlyRate;
}
But stackoverflow is not for others do you'r homework.

Related

Total of an array using class object

How can I get the total of the grosspay of all five employees? I've tried everything including creating objects but none seem to work, also I must store all the data in one array called EmpData so I cannot change that. I require assistance. This is the code I've created and it runs and works properly so far.
#include<iostream>
using namespace std;
class Employee {
private:
double hourswrk;
double payrate;
double grosspay;
int empno;
char empname[20];
double netpay;
double tax;
double overt;
double overtime;
double taxdeduct;
public:
void getdetails();
void calculatepay();
void showdetails();
};
void Employee::getdetails()
{
cout << "\nEnter employee name:\n";
cin >> empname;
cout << "\nEnter employee number:\n";
cin >> empno;
cout << "Enter hours worked:";
cin >> hourswrk;
cout << "Enter rate of pay";
cin >> payrate;
}
void Employee::calculatepay()
{
tax = 0.25;
overt = 1.5;
if(hourswrk >= 60)
{
grosspay = 0;
netpay = 0;
taxdeduct = 0;
cout << "You have exceeded the amount of hours!";
}
else if(hourswrk <= 40)
{
grosspay = hourswrk * payrate;
}
else if(hourswrk > 40 && hourswrk < 60)
{
overtime = hourswrk - 40;
grosspay = overt * payrate*overtime + hourswrk * payrate;
}
taxdeduct = tax * grosspay;
netpay = grosspay - taxdeduct;
}
void Employee::showdetails()
{
cout << "Employee Payslip\n";
cout << "Name: " << empname;
cout << "Employee number:" << empno;
cout << "Basic Salary" << payrate;
cout << "Hours work" << hourswrk;
cout << "Grosspay" << grosspay;
cout << "Tax: " << taxdeduct;
cout << "Net Salary" << netpay;
cout << endl;
}
int main()
{
Employee EmpData[5];
int i;
double hourswrk;
double payrate;
double grosspay;
int empno;
char empname[20];
double netpay;
double tax = 0.25;
double taxdeduct;
double overt = 1.5;
double overtime;
for(int i = 0; i < 5; i++)
{
EmpData[i].getdetails();
EmpData[i].calculatepay();
EmpData[i].showdetails();
}
system("pause");
return 0;
}
i just added a global variable which has totgrosspay every time you enter grosspay grosspay is added to totgrosspay
#include<iostream>
long totgrosspay=0;
using namespace std;
class Employee {
private:
long grosspay=0;
double hourswrk;
double payrate;
int empno;
char empname[20];
double netpay;
double tax;
double overt;
double overtime;
double taxdeduct;
public:
void getdetails();
void calculatepay();
void showdetails();
};
void Employee::getdetails()
{
cout << "\nEnter employee name:\n";
cin >> empname;
cout << "\nEnter employee number:\n";
cin >> empno;
cout << "Enter hours worked:";
cin >> hourswrk;
cout << "Enter rate of pay";
cin >> payrate;
}
void Employee::calculatepay()
{
tax = 0.25;
overt = 1.5;
if(hourswrk >= 60)
{
grosspay = 0;
netpay = 0;
taxdeduct = 0;
cout << "You have exceeded the amount of hours!";
}
else if(hourswrk <= 40)
{
grosspay = hourswrk * payrate;
}
else if(hourswrk > 40 && hourswrk < 60)
{
overtime = hourswrk - 40;
grosspay = overt * payrate*overtime + hourswrk * payrate;
}
taxdeduct = tax * grosspay;
netpay = grosspay - taxdeduct;
totgrosspay= totgrosspay+grosspay;
}
void Employee::showdetails()
{
cout << "Employee Payslip\n";
cout << "Name: " << empname;
cout << "Employee number:" << empno;
cout << "Basic Salary" << payrate;
cout << "Hours work" << hourswrk;
cout << "Grosspay" << grosspay;
cout << "Tax: " << taxdeduct;
cout << "Net Salary" << netpay;
cout << endl;
}
int main()
{
Employee EmpData[5];
int i;
for(int i = 0; i < 5; i++)
{
EmpData[i].getdetails();
EmpData[i].calculatepay();
EmpData[i].showdetails();
}
cout<<totgrosspay;// it prints gross pay value
system("pause");
return 0;
}

How to Calculate How Many Times Inputs Entered in Sentinel Loop c++

Here is the link to the programming question for detail. I have done my source code but I don't know how to calculate and display how many times inputs are entered in sentinel loop. Here is my source code:
#include <iostream>
using namespace std;
int main() {
int i, hours;
int tot_clients = 0;
float charges;
float tot_collection = 0;
const int sentinel = -1;
cout << "Welcome to ABC Parking Services Sdn Bhd" << endl;
cout << "=======================================" << endl;
while (hours != sentinel) {
cout << "Please enter number of parking hours (-1 to stop)" << endl;
cin >> hours;
if (hours <= 2 && hours > 0) {
charges = 1.00 * hours;
cout << "Charges: " << charges << endl;
}
else if (hours > 2 && hours <= 12) {
charges = (1.00 * 2) + ((hours - 2) * 0.50);
cout << "Charges: " << charges << endl;
}
else if (hours > 12) {
charges = 10.00 * hours;
cout << "Charges: " << charges << endl;
}
else if (hours == sentinel) {
break;
}
tot_collection = tot_collection + charges;
}
cout << "SUMMARY OF REPORT" << endl;
cout << "=======================================" << endl;
cout << "Total clients:" << tot_clients << endl;
cout << "Total colletion:" << tot_collection << endl;
return 0;
}
Hope someone can help me solving this. I am studying for my programming final exam.
I understand you want to count the number of clients (tot_clients). You have already intitalised the tot_clients = 0. This is good. You just have to increment the tot_clients variable inside the while loop (tot_clients++).
while (hours != sentinel)
{
cout << "Please enter number of parking hours (-1 to stop)" << endl;
cin >> hours;
tot_clients++; //this is the code to be added
/*rest of the code remains same*/
Add tot_clients++; just before or after tot_collection = tot_collection + charges;
1- initialize hours=0 otherwise hour will have some undetermined value during first-time condition check of while loop.
2-i am assuming that tot_clients stores total no. of customers than,
you just need to increment tot_clients on each iteration
#include <iostream>
using namespace std;
int main()
{
int i, hours=0;
int tot_clients=0;
float charges;
float tot_collection=0;
const int sentinel = -1;
cout << "Welcome to ABC Parking Services Sdn Bhd" << endl;
cout << "=======================================" << endl;
while (hours != sentinel)
{
cout << "Please enter number of parking hours (-1 to stop)" << endl;
cin >> hours;`
if (hours <= 2 && hours >0)
{
charges = 1.00 * hours;
cout << "Charges: " << charges << endl;
}
else if (hours>2 && hours <=12)
{
charges = (1.00*2) + ((hours - 2) * 0.50);
cout << "Charges: " << charges << endl;
}
else if (hours > 12)
{
charges = 10.00 * hours;
cout << "Charges: " << charges << endl;
}
else if (hours == sentinel)
{
break;
}
tot_collection = tot_collection + charges;
tot_clients=tot_clients+1; //increment's on each iteration except on input -1
}
cout << "SUMMARY OF REPORT" << endl;
cout << "=======================================" << endl;
cout << "Total clients:" << tot_clients << endl;
cout << "Total colletion:" << tot_collection << endl;
return 0;
}
`

Code WORKS Math DOESN'T

My code compiles nicely, but the math formulas that I am using aren't providing the right outcome. I need to calculate the balance, withdrawn, and interest for all 3 months. I am also required to validate user's input. For these purposes I am using nested loops. Please let me know if you spot my mistake. Thank you lovely people!
cout << "Please enter the starting balance: ";
cin >> startBalance;
cout << "Please enter the annual interest rate: ";
cin >> annualInterest;
for (int month = 1; month <= 3; month++) {
do {
cout << setprecision(5);
cout << "Please enter the total amount deposited on month " << month << ": ";
cin >> balance;
if (balance <0) {
goodChoice = false;
cout << "\n\t***ERROR " << balance << " ***";
cout << "*** Choice must be positive***\n" << endl;
}
else {
goodChoice = true;
}
startBalance += balance; //need to calculate the balance for all 3 months
} while (!goodChoice);
do {
cout << setprecision(5);
cout << "Please enter the total amount withdrawn on " << month << ": ";
cin >> withdrawn;
if ( (withdrawn <0) || (withdrawn > startBalance) ) {
goodChoice = false;
cout << "***ERROR " << withdrawn << " ***";
cout << "*** Choice must be positive or greater than the balance***" << endl;
}
else {
goodChoice = true;
}
finalWithdrawn += withdrawn; // the total amount of withdrawn
finalBalance = startBalance - withdrawn;
monthInterest = ((startBalance + finalBalance) / 2) * (annualInterest / 12);
totalInterest += monthInterest; //total interest for all 3 months
endBalance = monthInterest + finalBalance;
} while (!goodChoice);
}
cout << "Total Deposit: " << endBalance << endl;
cout << "Total Withdrawn: " << finalWithdrawn << endl;
cout << "Total Interest: " << totalInterest << endl;
cout << "Final Balance: " << endBalance << endl;
You have a lot of extra variables defined which aren't needed. Also, your interest rate may have been in percentage instead of a decimal number, i.e. 10% = 0.1. Also, your monthInterest is taking an average then applying interest. I wrote this up and it seems to work.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float totalDeposit = 0.0f;
float totalWithdrawn = 0.0f;
float totalInterest = 0.0f;
float totalBalance = 0.0f;
float interestRate = 0.0f;
setprecision(5); //?
cout << "Enter starting balance: ";
cin >> totalBalance;
cout << "Enter annual interest rate (%): ";
cin >> interestRate;
// Convert to monthly and non-percent; i.e. 10% = 0.1 = 10 / 100
interestRate = interestRate / 100.0f / 12.0f;
for (int month = 1; month <= 3; month++)
{
float deposit = -1.0; // Default to an error state
while (deposit < 0.0)
{
cout << "Enter total deposited in month " << month << ": ";
cin >> deposit;
if (deposit < 0.0f)
{
cout << "ERROR: Invalid amount" << endl;
continue;
}
}
float withdrawn = -1.0f; // Default to an error state
while (withdrawn < 0.0f)
{
cout << "Enter total withdrawn in month " << month << ": ";
cin >> withdrawn;
if (withdrawn < 0.0f)
{
cout << "ERROR: Invalid amount" << endl;
continue;
}
}
totalDeposit += deposit;
totalWithdrawn += withdrawn;
totalBalance = totalBalance + deposit - withdrawn;
totalBalance += totalBalance * interestRate;
totalInterest += totalBalance * interestRate;
}
cout << "Total Deposit: " << totalDeposit << endl;
cout << "Total Withdrawn: " << totalWithdrawn << endl;
cout << "Total Interest: " << totalInterest << endl;
cout << "Final Balance: " << totalBalance << endl;
int wait; // Pause so console window doesn't close. Delete this line.
cin >> wait;
return 0;
}

How to stop an overloop output in a class?

So I have an assignment for a class where I have to convert an employee payroll program into a class. I've completed that part and can even generate an output, but the problem starts there. The output keeps looping. I've had this problem before when I had an earlier program and the way I set the while loop was wrong. But this time, the while statement is fine, but the program still loops. I've corrected other errors but still cannot find this one.
Here is the code I've come up with:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cmath>
#include <cstdlib>
using namespace std;
class payroll {
ifstream fin;
char employeeid[12];
char firstname[20];
char lastname[20];
char SMH;
int SSN, hoursworked, overtimehours;
double hourlyrate, regularpay, overtimepay, grosspay, taxrate, taxamount, netpay, sum, average;
public:
payroll(){
fin.open("employee.txt");
}//CONSTRUCTOR
~payroll();
private:
void calcgrosspay() {
grosspay = regularpay + overtimepay;
if (hoursworked > 40) {
overtimehours = hoursworked - 40;
overtimepay = overtimehours * hourlyrate * 1.5;
regularpay = 40 * hourlyrate;
}//if
else {
overtimehours = 0;
overtimepay = 0;
regularpay = hoursworked * hourlyrate;
}//else
}//for
void calctax() {
if (grosspay >= 500) taxrate = .30;
else if (grosspay>200.00) taxrate = .20;
else taxrate = .10;
if (SMH == 'S' || SMH == 's')
taxrate = taxrate + .05;
taxamount = grosspay*taxrate;
}//for end of grosspay and set taxrate FOR
void calcNetpay() {
netpay = grosspay - taxamount;
}//end of calcnetpay function
void printheadings() {
cout << setw(49) << "-Payroll Report-" << endl;
cout << "------------------------------------------------------------------------------" << endl;
cout << "ID First Name Last Name Stat SSN HW HR OT OP GP Tax Net" << endl;
cout << "==============================================================================" << endl;
cout << "------------------------------------------------------------------------------" << endl;
}//printheadings
void printdata() {
setprecision(2);
cout << setw(14) << employeeid
<< setw(16) << firstname
<< setw(15) << lastname
<< setw(6) << SMH
<< setw(5) << SSN
<< setw(6) << hoursworked
<< setw(6) << hourlyrate
<< setw(8) << grosspay
<< setw(6) << taxrate
<< setw(9) << regularpay
<< setw(6) << overtimehours
<< setw(6) << overtimepay
<< setw(9) << netpay << endl;
}//print data
void payroll::findsum(int i) {
sum += netpay;
}
double payroll::findavg(double, int i) {
average = sum / i;
cout << endl << "The netpay average is " << average << endl;
return average;
}
public:
void printreport() {
int i = 0;
printheadings();
while (fin >> employeeid >> SMH >> SSN >> hoursworked >> hourlyrate >> firstname >> lastname)
{
calcgrosspay();
calctax();
calcNetpay();
printheadings();
printdata();
i++;
findsum(i);
}//while
findavg(sum, i);
}//print data report
}; // end of payroll class
payroll::~payroll() {
fin.close();
}//DESTRUCTOR
int main() {
payroll employee;
employee.printreport();
system("PAUSE");
}//main

Confused on uninitialized local variable being used when initialized?

I am getting an uninitialized Local variable error when I do believe I have already initialized. The error reads uninitialized local variable wk1 being used (It's wk1-wk5).
Here is the code:
#include <iostream>
using namespace std;
const double tax = 0.14;
int main()
{
int wk1,wk2,wk3,wk4,wk5;
wk1,wk2,wk3,wk4,wk5 = 0;
int thours = wk1 + wk2 + wk3 + wk4 + wk5; <------------ This is the error line.
thours = 0;
double payrate;
payrate = 0;
double gross = thours * payrate;
double taxes = tax * gross;
double net = gross - taxes;
double clothes = 0.10 * net;
double supplies = 0.10 * net;
double remaining = net - clothes - supplies;
double bonds = 0.25 * remaining;
double pbonds = 0.50 * bonds;
bonds = 0;
gross = 0;
net = 0;
clothes = 0;
supplies = 0;
remaining = 0;
cout << "Please enter the payrate for employee." << endl;
cin >> payrate;
payrate = 0;
cout << "Please enter employee's total hours for week one:" << endl;
cin >> wk1;
wk1 = 0;
cout << "Please enter employee's total hours for week two:" << endl;
cin >> wk2;
wk2 = 0;
cout << "Please enter employee's total hours for week three:" << endl;
cin >> wk3;
wk3 = 0;
cout << "Please enter employee's total hours for week four:" << endl;
cin >> wk4;
wk4 = 0;
cout << "Please enter employee's total hours for week five:" << endl;
cin >> wk5;
wk5 = 0;
cout << "Here is income before taxes: " << gross << endl;
cout << "Here is income after taxes: " << net << endl;
cout << "Here is clothes and accesories: " << clothes << endl;
cout << "Here is School supplies: " << supplies << endl;
cout << "Here is personal bonds: " << bonds << endl;
cout << "Here is parents bonds: " << pbonds << endl;
return 0;
}
wk1,wk2,wk3,wk4,wk5 = 0;
This line is a comma operator expression, which is equivalent to:
wk5 = 0;
Because expressions like wk1 has no side effect. Only the variable wk5 has been assigned a value, the other variables are still uninitialized. You can do:
wk1 = wk2 = wk3 = wk4 = wk5 = 0;