/* Kinetic Energy - In physics, an object that is in motion is said to
have kinetic energy. The following formula can be used to determine
a moving object's kinetic energy:
* KE = 1/2 mv²
The variables in the formula are as follows:
* KE: is the kinetic energy
* m: is the object's mass in kilograms
* v: is the object's velocity in meters per second
This program uses a function named kineticEnergy().
The function is demonstrated in this program which asks the user
to enter values for mass and velocity. */
#include "Utility.h"
/* Prototype: Kinetic energy */
double kineticEnergy(double, double);
int main()
{
/* Variables: Object mass, Object velocity */
double objMass = 0.0,
objVelocity = 0.0,
objKineticEnergy = 0.0;
/* Introduction */
cout << "\t\tKinetic Energie Function Demo\n\n"
<< "All moving objects have kinetic energy. The kinetic\n"
<< "energy an object has depends on its:\n\n"
<< "* Mass\n"
<< "* Speed\n\n"
<< "This program uses a function that let's you determine\n"
<< "the kinetic energy (in Joules) of a moving object, by\n"
<< "using a custom function that does the calculation.\n\n";
/* Get: Object mass, Object velocity */
cout << "Enter the object's mass (kg): ";
cin >> objMass;
/* Validation: While 0 or negative is entered for the object's
mass, a message is displayed, and the user is asked to repeat
entering the data */
while (objMass <= 0)
{
cout << "\nAn object's mass can not be 0 or negative.\n"
<< "Enter the object's mass (kg): ";
cin >> objMass;
}
cout << "Enter the object's velocity (m/s): ";
cin >> objVelocity;
/* Validation: While 0 or negative is entered for the object's
velocity, a message is displayed, and the user is asked to repeat
entering the data */
while (objVelocity <= 0)
{
cout << "\nAn object's velocity can not be 0 or negative.\n"
<< "Enter the object's velocity (mp/s): ";
cin >> objVelocity;
}
/* Call: kineticEnergy */
objKineticEnergy = kineticEnergy(objMass, objVelocity);
/* Display: The object's mass, velocity, and total
kinetic energy */
cout << "\nA moving object with the following parameters:\n\n"
<< "Mass: " << objMass << " kg\n"
<< "Velocity " << objVelocity << " m/s\n\n"
<< "Has a total kinetic energy of: "
<< objKineticEnergy << " J.\n";
pauseSystem();
return 0;
}
/* **********************************************************
Definition: kineticEnergy
This function accepts an object's mass (in kilograms) and
velocity (in meters per second) as arguments. The function
returns the amount of kinetic energy that the object has.
********************************************************** */
double kineticEnergy(double calcMass, double calcVelocity)
{
/* Variable: Total Object Energy */
double objTotalEnergy = 0.0;
/* Calculation: The object's total energy */
objTotalEnergy = calcMass * pow(calcVelocity, 2) / 2;
/* Return: The objects total energy */
return objTotalEnergy;
}
Tuesday, January 3, 2017
Programming Challenge 6.6 - Kinetic Energy
Monday, January 2, 2017
Programming Challenge 6.5 - Falling Distance
/* Falling Distance - When an object is falling because of gravity, the
following formula can be used to determine the distance the object
falls in a specific time period.
* d = 1/2gt²
The variables in the formula are as follows:
* d: distance in meters
* g: 9.8
* t: amount of time (seconds) the object is falling
The following function is used:
* fallingDistance()
This program demonstrates the function by calling it in a loop that
passes the values 1 through 10 as arguments, and displays the return
value. */
#include "Utility.h"
/* Prototype: Falling Distance */
double fallingDistance(double);
int main()
{
/* Variable: Falling time */
double distance = 0.0;
/* Display: Information, Header */
cout << "\t\tFree Falling Object Demo\n\n"
<< "This program demonstrates the function 'fallingDistance'\n"
<< "which calculates the distance an object falls in a specific\n"
<< "amount of time in seconds.\n\n";
cout << "After second(s):" << "\t" << "The ball has fallen:"
<< "\n------------------------------------------------------\n";
/* This loop calls fallingTime ten times, falling time, declared in
the loop header, passes fallingTime as argument to the function
fallingDistance, receives the return value stored in the variable
"distance", and displays both time and distance in meters/sec. */
for (double fallingTime = 1; fallingTime <= 10; fallingTime++)
{
distance = fallingDistance(fallingTime);
/* Set up: Formatted numeric output
Display: Time and Falling distance */
cout << fixed << showpoint << setprecision(2);
cout << setw(8) << left << fallingTime
<< "\t\t\t " << setw(8) << right << distance << " m.\n";
}
pauseSystem();
return 0;
}
/* **********************************************************
Definition: fallingDistance
This function accepts an object's falling time in seconds
as an argument. It returns the distance in meters that the
object has fallen during that time interval.
********************************************************** */
double fallingDistance(double fallingTime)
{
/* Static local variable: Acceleration (gravity) */
static double acceleration = 9.8;
/* Variable: Falling Distance */
double distance = 0.0;
/* Calculation: Falling distance */
distance = acceleration * pow(fallingTime, 2) / 2;
/* Return: Falling distance */
return distance;
}
Programming Challenge 6.4 - Safest Driving Area
/* Safest Driving Area - This program determines which of five geographic
regions within a major city (North, South, East, West, and Central) had
the fewest reported automobile accidents last year. It has the following
two functions, called by main:
* int getNumAccidents()
* void findLowest()
Input Validation: No accident number that is less than 0 is accepted. */
#include "Utility.h"
/* Prototypes: Get number of Accidents, Find region with lowest
accidents */
int getNumAccidents(int, string);
void findLowest(int, int, int, int, int);
int main()
{
/* Variables: Regions (North, South, East, West, Central) */
int regionNorth = 0,
regionSouth = 0,
regionEast = 0,
regionWest = 0,
regionCentral = 0,
numAccidents = 0;
/* Display: Introduction */
cout << "\t\tTraffic Control Center - Accident Reports\n\n"
<< "---------------------------------------------------\n"
<< "Enter the number of accidents that occured in each\n"
<< "of the following regions: North, South, East, West\n"
<< "and Central to determine which region has had the\n"
<< "smallest number of automobile accidents last year.\n"
<< "---------------------------------------------------\n\n";
/* Get: Accident figures
Call: getNumAccidents */
regionNorth = getNumAccidents(numAccidents, "Silver Creek North: ");
regionSouth = getNumAccidents(numAccidents, "Silver Creek South: ");
regionEast = getNumAccidents(numAccidents, "Silver Creek East: ");
regionWest = getNumAccidents(numAccidents, "Silver Creek West: ");
regionCentral = getNumAccidents(numAccidents, "Silver Creek Central: ");
/* Call: findLowest */
findLowest(regionNorth, regionSouth, regionEast,
regionWest, regionCentral);
pauseSystem();
return 0;
}
/* **********************************************************
Definition: getNumAccidents
The name of the region is passed to this function. It asks
the user for the number of automobile accidents reported
in that region during the last year, validates the input,
then returns it.
********************************************************** */
int getNumAccidents(int accidents, string regionName)
{
cout << "Accident Reports - " << regionName;
cin >> accidents;
/* Valdiation: While number of accidents is negative, a
message is displayed, asking the user to repeat his or
her input */
while (accidents < 0)
{
cout << "\nError! The number of traffic accidents entered\n"
<< "is invalid. Please enter 0 if applicable, or any\n"
<< "other number above 0.\n"
<< "Number of accidents: " << regionName;
cin >> accidents;
}
return accidents;
}
/* **********************************************************
Definition: findLowest
The five accident totals are passed to this function. It
determines which is the smallest and prints the name of
the region, along with its accident figure.
********************************************************** */
void findLowest(int lowestNorth, int lowestSouth, int lowestEast,
int lowestWest, int lowestCentral)
{
/* Variable: Region name */
string regionName = " ";
/* Variable: Lowest is initialized to lowestNorth as starting
value for the comparisons */
int lowest = lowestNorth;
/* Conditional Statements Tier 1: Determine which region has
had the lowest traffic accidents */
lowest = lowestSouth < lowest ? lowestSouth : lowest;
lowest = lowestEast < lowest ? lowestEast : lowest;
lowest = lowestWest < lowest ? lowestWest : lowest;
lowest = lowestCentral < lowest ? lowestCentral : lowest;
/* Conditional Statements Tier 2: The regions are assigned region
names for display in the report that follows */
regionName = lowestNorth == lowest ? "Silver Creek North" : regionName;
regionName = lowestSouth == lowest ? "Silver Creek South" : regionName;
regionName = lowestEast == lowest ? "Silver Creek East" : regionName;
regionName = lowestWest == lowest ? "Silver Creek West" : regionName;
regionName = lowestCentral == lowest ? "Silver Creek Central" : regionName;
/* Display: The region with the lowest accident number, along
with the region name */
cout << "\nAccident Report Summary: " << regionName << "\n"
<< "---------------------------------------------------\n"
<< "With " << lowest << " automobile accidents,\n"
<< regionName << " is the safest driving area.\n";
}
Programming Challenge 6.3 - Winning Division
/* Winning Division - This program determines which of a company's four
divisions (Northeast, Southeast, Northwest, and Southwest) had the
greatest sales for a quarter. It includes the following two functions
which are called by main.
* double getSales()
* void findHighest()
Input Validation: No dollar amounts less than $0.00 are accepted. */
#include "Utility.h"
/* Prototypes: Get sales, Find highest */
double getSales(double, string);
void findHighest(double, double, double, double);
int main()
{
/* Variables: Divisions (North-East, South-East,
North-West, South-West) */
double divisionNE = 0.0,
divisionSE = 0.0,
divisionNW = 0.0,
divisionSW = 0.0;
/* Display: Information */
cout << "\t\tIshikawa Fruit Company - Winning Sales Division\n\n"
<< "Every year we determine our winning sales division based\n"
<< "on the highest total sales figures per quarter. Enter\n"
<< "the sales figures for each of our four divisions, to\n"
<< "find out which division has won in this quarter.\n\n";
/* Call: getSales (NE, SE, NW, SW) */
divisionNE = getSales(divisionNE, "Division North-East");
divisionSE = getSales(divisionSE, "Division South-East");
divisionNW = getSales(divisionNW, "Division North-West");
divisionSW = getSales(divisionSW, "Division South-West");
/* Call: getHighest */
findHighest(divisionNE, divisionSE, divisionNW, divisionSW);
pauseSystem();
return 0;
}
/* **********************************************************
Definition: getSales
getSales is passed the name of a division. It asks the user
for a division's quarterly sales figure, validates the input,
then returns it. It is called once for each division.
********************************************************** */
double getSales(double salesTotal, string regionName)
{
/* Get: Sales total */
cout << "Sales Total " << regionName << "$ ";
cin >> salesTotal;
/* Validation: While salesTotal is 0 or negative, a message
is displayed asking the user to repeat his or her
input */
while (salesTotal <= 0)
{
cout << "\nThe value you entered for sales total could\n"
<< "not be accepted because it was 0 or negative.\n"
<< "Please repeat your input: ";
cin >> salesTotal;
}
return salesTotal;
}
/* **********************************************************
Definition: findHighest
findHighest is passed the four sales totals. It determines
which is the largest and prints the name of the high grossing
division, along with its sales figure.
********************************************************** */
void findHighest(double highNE, double highSE,
double highNW, double highSW)
{
/* Variable: Highest, initialized to highNE for comparison */
double highest = highNE;
/* Variable: Region name */
string divisionName = " ";
/* Conditional Statements Tier 1: Determine which division has
had the highest sales this quarter */
highest = highSE > highest ? highSE : highest;
highest = highNW > highest ? highNW : highest;
highest = highSW > highest ? highSW : highest;
/* Conditional Statements Tier 2: Assign the division names */
divisionName = highNE == highest ? "North-East Division" : divisionName;
divisionName = highSE == highest ? "South-East Division" : divisionName;
divisionName = highNW == highest ? "North-West Division" : divisionName;
divisionName = highSW == highest ? "South-West Division" : divisionName;
/* Set up: Numeric output formatting */
cout << fixed << showpoint << setprecision(2);
/* Display: The company division with the highest sales */
cout << "\nY. Sato, our most honorable Company President is proud\n"
<< "to proclaim our successful " << divisionName
<< " with a\n"
<< "Sales Total of: $" << highest
<< " the winner of this quarter's\n"
<< "Grand Prize in our traditional sales competition!\n";
}
Sunday, January 1, 2017
Programming Challenge 6.2 - Rectangle Area Complete
/* Rectangle Area Complete - This program asks the user to enter the
width and length of a rectangle and then displays the rectangle's
area.
The program calls the following functions:
* getLength: This function asks the user to enter the rectangle's
length and then returns that value as a double.
* getWidth: This function asks the user to enter the rectangle's
width and then returns that value as a double.
* getArea: This function accepts the rectangle's length and width
as arguments and returns the rectangle's area.
* The area is calculated by multiplying the length by the width.
* displayData: This function accepts the rectangle's length, width,
and area as arguments and displays them in an appropriate message
on the screen. */
#include "Utility.h"
/* Prototypes: Get length, Get width, Get area, Display data */
double getLength(double);
double getWidth(double);
double getArea(double, double);
void displayData(double, double, double);
int main()
{
/* Variables: Length, Width, Area */
double length = 0.0,
width = 0.0,
area = 0.0;
/* Display: Information */
cout << "This program allows you to easily calculate the\n"
<< "area of a rectangle, by providing the length and\n"
<< "width values. Once done, the program will display\n"
<< "the area.\n";
/* Get: Length of the rectangle
Call: getLength */
length = getLength(length);
/* Get: Width of the rectangle
Call: getWidth */
width = getWidth(width);
/* Get: Area of the rectangle
Call: getArea */
area = getArea(length, width);
/* Display: Rectangle data
Call: displayData */
displayData(length, width, area);
pauseSystem();
return 0;
}
/* **********************************************************
Definition: getLength
This function asks the user for the rectangle's length,
stores the value in lenRect and returns the value to main.
********************************************************** */
double getLength(double lenRect)
{
/* Variable: Rectangle length */
double rectLength = 0.0;
/* Get: The rectangle length */
cout << "\nPlease enter the rectangle's length: ";
cin >> rectLength;
/* Validation: While the user enters a negative value, an
error message will be displayed, and the user is asked
to repeat his or her input */
while (rectLength < 0)
{
cout << "Sorry, only positive values for the rectangle's\n"
<< "length are accepted.\n"
<< "Please enter the rectangle's length: ";
cin >> rectLength;
}
/* Return: Rectangle length */
return rectLength;
}
/* **********************************************************
Definition: getWidth
This function asks the user for the rectangle's width,
stores the value in rectWidth and returns this value to
main.
********************************************************** */
double getWidth(double wdRect)
{
/* Variable: Rectangle width */
double rectWidth = 0.0;
/* Get: The rectangle width */
cout << "Please enter the rectangle's width: ";
cin >> rectWidth;
/* Validation: While the user enters a negative value, an
error message will be displayed, and the user is asked
to repeat his or her input */
while (rectWidth < 0)
{
cout << "Sorry, only positive values for the rectangle's\n"
<< "width are accepted.\n"
<< "Please enter the rectangle's width: ";
cin >> rectWidth;
}
/* Return: Rectangle width */
return rectWidth;
}
/* **********************************************************
Definition: getArea
This function accepts the rectangle's length and width as
arguments. It returns the result of the calculation.
********************************************************** */
double getArea(double lenRect, double wdRect)
{
/* Return: Result of calculation */
return lenRect * wdRect;
}
/* **********************************************************
Definition: displayData
This function accepts the rectangle's length, width, and
area. It displays them on screen.
********************************************************** */
void displayData(double lenRect, double wdRect, double areaRect)
{
/* Display: Rectangle data */
cout << "\nA Rectangle with the following data:\n"
<< "-------------------------------------\n"
<< "\nLength: " << lenRect << " cm\n"
<< "Width: " << wdRect << " cm\n\n"
<< "-------------------------------------\n"
<< "Has an area of " << areaRect << " square cm.\n";
}
Programming Challenge 6.1 - Markup
/* Markup - This program asks the user to enter an item's wholesale cost and its
markup percentage. It then displays the item's retail price.
* If an item's wholesale cost is $5.00 and its markup percentage is
100%, then the item's retail price is $10.00.
* If an item's wholesale cost is $5.00 and its markup percentage is
50%, then the item's retail price is $7.50.
This program has a function named calculateRetail that receives the
wholesale cost and the markup percentage as arguments and returns
the retail price of the item.
Input Validation: No negative values for either the wholesale cost
of the item or the markup percentage are accepted. */
#include "Utility.h"
/* Prototype: Calculate retail */
double calculateRetail(double, double);
int main()
{
/* Variables: Wholesale cost, Markup percentage, Retail price */
double wholesaleCost = 0.0,
markupPct = 0.0,
retailPrice = 0.0;
/* Display: Information
Get: Wholesale cost */
cout << "\t\tRetail Price Calculator\n\n"
<< "This program allows you to calculate the retail price\n"
<< "of an item, by providing the price, and the markup\n"
<< "percent of the item.\n\n"
<< "Please enter the wholesale cost of the item: $";
cin >> wholesaleCost;
/* Validate input: While a negative value is entered for
wholesaleCost, an error message is displayed, and the
user is asked to repeat his or her input */
while (wholesaleCost <= 0)
{
cout << "\nSorry, but only positive values are allowed.\n"
<< "Please enter the wholesaleCost of the item: $";
cin >> wholesaleCost;
}
/* Get: Markup percentage */
cout << "\nPlease enter the markup percentage of the item: %";
cin >> markupPct;
/* Validate input: While markupPct gets a negative value, an
error message is displayed, and the user is asked to repeat
his or her input */
while (markupPct <= 0)
{
cout << "\nSorry, only positive values are accepted as input.\n"
<< "Please enter the markup percentage of the item: %";
cin >> markupPct;
}
/* Call: calculateRetail */
retailPrice = calculateRetail(wholesaleCost, markupPct);
/* Set up: Numeric output */
cout << fixed << showpoint << setprecision(2);
/* Display: The retail price of the item */
cout << "\nThe retail cost of the item is: $" << retailPrice << endl;
pauseSystem();
return 0;
}
/* **********************************************************
Definition: calculateRetail
This function gets its arguments from wholesalePrice and
markupPct, stores the values in cost and percent, then
calculates and returns the retail price.
********************************************************** */
double calculateRetail(double cost, double percent)
{
/* Variable: Retail cost */
double retailCost = 0.0;
/* Calculate: Retail cost */
retailCost = cost + (cost * percent) / 100;
/* Return: retailCost to retailPrice in main */
return retailCost;
}
Happy New Year! Welcome, 2017! Welcome Back!
/* Happy New Year - This program uses a function two display a message to
my visitors. */
#include "Utility.h"
/* Prototype: Display greeting */
void displayGreeting();
int main()
{
/* Call: displayGreeting */
displayGreeting();
pauseSystem();
return 0;
}
/* **********************************************************
Definition: displayGreeting
This function wishes all my visitors a HAPPY NEW YEAR
********************************************************** */
void displayGreeting()
{
cout << "HAPPY NEW YEAR!\n";
cout << "新年おめでとうございます!\n";
cout << "Pase yon bon nouvel àne!\n";
cout << "Gelukkige nuwe jaar\n";
cout << "Bonne annèe\n";
cout << "Ein frohes Neues Jahr!\n";
}
Last year I made a promise not to start working on chapter 6 until after new year has begun, and obviously didn't keep it ... Then again, it wouldn't be me to take a break, so i started with this chapter the very next day i uploaded my last blog-post. Above code fits the topic perfectly. Functions, functions everywhere ... Lots of new terminology such as parameters, arguments, and so forth. The first two or three sub-chapters were illuminating, as i could clearly see how functions might make life a whole lot easier when used correctly. Then, around sub-chapter 6.5 my mind drew a blank, what with all the new concepts, and how-to-do-this-how-to-do-that, when-to-use-this-when-that ... I still managed to work my way through the Review Questions and Exercises, the Algorithm Workbench, and to solve the first two Challenges.
A New Chapter, A New Year, A New Commenting Style
I must confess that my code comments were too painstakingly long and detailed ... My intention was all good, it just got a little overboard. It is one thing to make clear what parts of the code do, while writing the code it helped me to understand, and when looking at my code I thought it would help others who learn as well. This has now changed. I still write comments, but they are more to the point, yet still helpful in understanding what goes on in my code.
Enough of words, time for more coding action! Back to the drawing ... err-IDE-board.
Subscribe to:
Posts (Atom)