Sheet2_solved

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Fundamental of Programming 1

Sheet 2: C++ basics


(variables, assignment statement, Input/output , Flow of control : if
statement)

Q1. Write a complete C++ program that asks the user for a number of gallons
and then outputs the equivalent number of liters. There are 3.78533 liters in a
gallon. Use a declared constant.
Sol:
#include <iostream>
using namespace
std;
int main()
{
const double LITERS_PER_GALLON = 3.78533;
double gallons, liters;
cout << "Enter the number of gallons:\n";
cin >> gallons;
liters = gallons*LITERS_PER_GALLON;
cout << "There are " << liters << " in "
<< gallons << " gallons.\n";
return 0;
}

Q2. Write a program that prints out “C S !” in large block letters inside a border of *s followed by
two blank lines then the message Computer Science is Cool Stuff. The output should look as
follows:
Solution Hint: Just mention the idea: difference between just repeating cout vs using for loop.

Q3. Write a very simple conversational dialog program. Your program should
do the following:
■ Say “Hello” to the user.
■ Ask them if they are having a good day, and record their input.
■ If their response is anything other than a ‘y’ for yes or an ‘n’ for no,
repeat the question.
■ If they respond with a ‘y’, output “I’m glad to hear that”, and if they
answer with an ‘n’, then output “I hope your day gets better soon.”
Sol:

#include <iostream>

using namespace std;

// ====================

// main function

// ====================

int main()

{
cout << "Please enter your name:\n";

string name;

cin >> name;

cout << "Hello ";

cout << name;

cout << "\n";

char goodDay;

do

cout << "Are you having a good day?\n";

cin >> goodDay;

} while (goodDay != 'y' && goodDay != 'n');

if (goodDay == 'y')

cout << "I'm glad to hear that\n";

else

cout << "I hope your day gets better soon\n";

return 0;

Q4.An employee is paid at a rate of $16.78 per hour for the first 40 hours
worked in a week. Any hours over that are paid at the overtime rate of one-
and-one-half times that. From the worker’s gross pay, 6% is withheld for
Social Security tax, 14% is withheld for federal income tax, 5% is withheld for
state income tax, and $10 per week is withheld for union dues. If the worker
has three or more dependents, then an additional $35 is withheld to cover
the extra cost of health insurance beyond what the employer pays. Write a
program that will read in the number of hours worked in a week and the
number of dependents as input and will then output the worker’s gross pay,
each withholding amount, and the net take-home pay for the week. For a
harder version, write your program so that it allows the calcula- tion to be
repeated as often as the user wishes. If this is a class exercise, ask your
instructor whether you should do this harder version.

Sol: // this week solve it only with if statement.

This problem involves payroll and uses the selection construct. A possible restatement: An hourly
employee's regular payRate is $16.78/hour for hoursWorked <= 40 hours. If hoursWorked > 40 hours,
then (hoursWorked -40) is paid at an overtime premium rate of 1.5 * payRate. FICA (social security) tax
is 6% and Federal income tax is 14%. Union dues of $10/week are withheld. If there are 3 or more
covered dependents, $15 more is withheld for dependent health insurance.

a) Write a program that, on a weekly basis, accepts hours worked then outputs gross pay, each
withholding amount, and net (take-home) pay.
b) Add 'repeat at user discretion' feature.

I was unpleasantly surprised to find that with early GNU g++ , you cannot use a leading 0 (such as an
SSN 034 56 7891) in a sequence of integer inputs. The gnu iostreams library took the integer to be zero
and went directly to the next input! You either have to either use an array of char, or 9 char variables to
avoid this restriction.

Otherwise, the code is fairly straight forward.

//Programming Project 6
//Pay roll problem:
//Inputs: hoursWorked, number of dependents
//Outputs: gross pay, each deduction, net pay
//
//This is the 'repeat at user discretion' version
//Outline:
//In a real payroll program, each of these values would be
//stored in a file after the payroll calculation was printed //to a report.
//
//regular payRate = $10.78/hour for hoursWorked <= 40 //hours.
//If hoursWorked > 40 hours,
// overtimePay = (hoursWorked - 40) * 1.5 * PAY_RATE.
//FICA (social security) tax rate is 6%
//Federal income tax rate is 14%.
//Union dues = $10/week .
//If number of dependents >= 3
// $15 more is withheld for dependent health insurance.
//
#include <iostream>
using namespace std;

const double PAY_RATE = 16.78;


const double SS_TAX_RATE = 0.06;
const double FedIRS_RATE = 0.14;
const double STATE_TAX_RATE = 0.05;
const double UNION_DUES = 10.0;
const double OVERTIME_FACTOR = 1.5;
const double HEALTH_INSURANCE = 15.0;

int main()
{
double hoursWorked, grossPay, overTime, fica,
incomeTax, stateTax, union_dues, netPay;
int numberDependents, employeeNumber;
char ans;
//set the output to two places, and force .00 for cents
cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout.precision(2);
// compute payroll
do
{
cout << "Enter employee SSN (digits only,”
<< “ no spaces or dashes) \n”;
cin >> employeeNumber ;
cout << “Please the enter hours worked and number “
<< “of employees.” << endl;
cin >> hoursWorked ;
cin >> numberDependents;
cout << endl;

if (hoursWorked <= 40 )
grossPay = hoursWorked * PAY_RATE;
else
{
overTime =
(hoursWorked - 40) * PAY_RATE * OVERTIME_FACTOR;
grossPay = 40 * PAY_RATE + overTime;
}

fica = grossPay * SS_TAX_RATE;


incomeTax = grossPay * FedIRS_RATE;
stateTax = grossPay * STATE_TAX_RATE;
netPay =
grossPay - fica - incomeTax
- UNION_DUES - stateTax;

if ( numberDependents >= 3 )
netPay = netPay - HEALTH_INSURANCE;

//now print report for this employee:


cout << "Employee number: "
<< employeeNumber << endl;
cout << "hours worked: " << hoursWorked << endl;
cout << "regular pay rate: " << PAY_RATE << endl;

if (hoursWorked > 40 )
{
cout << "overtime hours worked: "
<< hoursWorked - 40 << endl;
cout << "with overtime premium: "
<< OVERTIME_FACTOR << endl;
}

cout << "gross pay: " << grossPay << endl;


cout << "FICA tax withheld: " << fica << endl;
cout << "Federal Income Tax withheld: "
<< incomeTax << endl;
cout << "State Tax withheld: " << stateTax << endl;

if (numberDependents >= 3 )
cout << "Health Insurance Premium withheld: "
<< HEALTH_INSURANCE << endl;

cout << "Flabbergaster's Union Dues withheld: "


<< UNION_DUES << endl;
cout << "Net Pay: " << netPay << endl << endl;
cout << "Compute pay for another employee?”
<< “ Y/y repeats, any other ends" << endl;
cin >> ans;
} while( 'y' == ans || 'Y' == ans );
return 0;
}

Q5. Many treadmills output the speed of the treadmill in miles per hour (mph)
on the console, but most runners think of speed in terms of a pace. A
common pace is the number of minutes and seconds per mile instead of
mph.
Write a program that starts with a quantity in mph and converts the quantity
into minutes and seconds per mile. As an example, the proper output for an
input of 6.5 mph should be 9 minutes and 13.8 seconds per mile.
Sol:

#include <iostream>

using namespace std;

// ====================

// main function

// ====================

int main()

double milesPerHour;

double hoursPerMile;

double minutesPerMile;

double secondsPace;

int minutesPace;

// Input miles per hour

cout << "Enter speed in miles per hour:" << endl;

cin >> milesPerHour;


// Compute inverse, which is hours per mile

hoursPerMile = 1.0 / milesPerHour;

// Convert to minutes per mile which is 60 seconds/hour * hoursPerMile

minutesPerMile = 60 * hoursPerMile;

// Extract minutes by converting to an integer, while

// truncates any value after the decimal point

minutesPace = static_cast<int>(minutesPerMile);

// Seconds is the remaining number of minutes * 60

secondsPace = (minutesPerMile - minutesPace) * 60;

cout << milesPerHour << " miles per hour is a pace of " <<

minutesPace << " minutes and " << secondsPace << " seconds. " << endl;

return 0;

Q6. Write a program that reads in three int values. The numbers should then
be output in ascending order from smallest to largest. Can you do this with
only if statements and three int variables (Hint: try nesting if statements or
using the && operator)? What happens if you input three identical numbers?
Sol

#include <iostream>

using namespace std;


int main()

int int1, int2, int3;

cout << "Enter three ints:\n";

cin >> int1;

cin >> int2;

cin >> int3;

cout << "In order of smallest to largest:\n";

if (int1 <= int2 && int1 <= int3)

cout << int1;

cout << " ";

if (int2 <= int3)

cout << int2;

cout << " ";

cout << int3;

else

cout << int3;

cout << " ";

cout << int2;

}
else
{

if (int2 <= int1 && int2 <= int3)

cout << int2;

cout << " ";

if (int1 <= int3)

cout << int1;

cout << " ";

cout << int3;

else

cout << int3;

cout << " ";

cout << int1;

else

cout << int3;

cout << " ";

if (int1 <= int2)

cout << int1;

cout << " ";

cout << int2;

}
else

cout << int2;

cout << " ";

cout << int1;

cout << "\n";

return 0;

Typical run

Enter three ints:

3 2 1

In order of smallest to largest:

1 2 3

Q7. Computers normally treat time as the number of seconds from an


arbitrary starting point called an epoch. Write a C++ program that asks the
user for the current hour of the day (from 0 to 23), the current minute of the
hour (from 0 to 59) and the current second of the minute (from 0 to 59). Use
the user’s input to calculate the number of seconds since midnight that
their time represents. If the user enters an invalid input, like 67 minutes
for the current minutes in the hour, then ask them for that value again
until they enter a correct value. Sample input and output is shown below.
Enter the hour of the day: 3
Enter the minutes of the hour: 45
Enter the seconds passed in the current minute: 25
Enter the seconds passed in the current minute: 90
Enter the seconds passed in the current minute: 3
The time in seconds since midnight is: 45903
Sol:

#include <iostream>

using namespace std;

int main()

int hour;

do

cout << "Enter the hour of the day:\n";

cin >> hour;

} while (hour < 0 || hour > 23);

int minute;

do

cout << "Enter the minutes of the hour:\n";

cin >> minute;

} while (minute < 0 || minute > 59);

int second;

do

cout << "Enter the seconds past in the current minute:\n";

cin >> second;


} while (second < 0 || second > 59);

cout << "The time in seconds since midnight is: ";

cout << hour * 60 * 60 + minute * 60 + second;

cout << "\n";

return 0;

You might also like