diff --git a/.gitignore b/.gitignore index 259148f..815be8f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ + +# Created by https://www.gitignore.io/api/osx,c++,linux,macos,windows,visualstudio,visualstudiocode + +### C++ ### # Prerequisites *.d @@ -30,3 +34,380 @@ *.exe *.out *.app + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### OSX ### + +# Icon must end with two \r + +# Thumbnails + +# Files that might appear in the root of a volume + +# Directories potentially created on remote AFP share + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Uncomment the next line to ignore your web deploy settings. +# By default, sensitive information, such as encrypted password +# should be stored in the .pubxml.user file. +#*.pubxml +*.pubxml.user +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Typescript v1 declaration files +typings/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +### VisualStudio Patch ### +# By default, sensitive information, such as encrypted password +# should be stored in the .pubxml.user file. + + +# End of https://www.gitignore.io/api/osx,c++,linux,macos,windows,visualstudio,visualstudiocode diff --git a/Chapter-1-Intro-to-Computers-and-Programming/1-1.cpp b/Chapter-1-Intro-to-Computers-and-Programming/1-1.cpp new file mode 100644 index 0000000..f604a8c --- /dev/null +++ b/Chapter-1-Intro-to-Computers-and-Programming/1-1.cpp @@ -0,0 +1,29 @@ +//*********************************************** +// This program calculates the user's pay. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 21, 2016 +//*********************************************** +#include +using namespace std; + +int main() +{ + double hours, rate, pay; + + // Get the number of hours worked. + cout << "How many hours did you work?"; + cin >> hours; + + // Get the hourly pay rate. + cout << "How much do you get paid per hour?"; + cin >> rate; + + // Calculate the pay. + pay = hours * rate; + + // Display the pay. + cout << "You have earned $" << pay << endl; + + return 0; +} diff --git a/Chapter-1-Intro-to-Computers-and-Programming/1-30.cpp b/Chapter-1-Intro-to-Computers-and-Programming/1-30.cpp new file mode 100644 index 0000000..dd7ba8f --- /dev/null +++ b/Chapter-1-Intro-to-Computers-and-Programming/1-30.cpp @@ -0,0 +1,26 @@ +//******************************************************* +// This program calculates a customer's available credit. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 21, 2016 +//******************************************************* +#include +using namespace std; + +int main() +{ + int maxCredit, creditUsed, availableCredit; + + cout << "Enter the customer's maximum credit $"; + cin >> maxCredit; + + cout << "Enter the amount of credit used by the customer $"; + cin >> creditUsed; + + availableCredit = maxCredit - creditUsed; + + cout << "The customer's available credit is $" + << availableCredit << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.1-The-Parts-of-a-C++-Program/2-1.cpp b/Chapter-2-Intro-to-C++/2.1-The-Parts-of-a-C++-Program/2-1.cpp new file mode 100644 index 0000000..19db90a --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.1-The-Parts-of-a-C++-Program/2-1.cpp @@ -0,0 +1,14 @@ +//********************************** +// A simple C++ program. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 21, 2016 +//********************************** +#include +using namespace std; + +int main() +{ + cout << "Programming is great fun!" << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.10-The-bool-Data-Type/2-17.cpp b/Chapter-2-Intro-to-C++/2.10-The-bool-Data-Type/2-17.cpp new file mode 100644 index 0000000..7cccf8d --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.10-The-bool-Data-Type/2-17.cpp @@ -0,0 +1,23 @@ +//********************************************** +// This program demonstrates boolean variables. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//********************************************** +#include +using namespace std; + +int main() +{ + bool boolValue; + + boolValue = true; + cout << boolValue << endl; + boolValue = false; + cout << boolValue << endl; + boolValue = 1; + cout << boolValue << endl; + boolValue = 0; + cout << boolValue << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.11-Determining-the-Size-of-a-Data-Type/2-18.cpp b/Chapter-2-Intro-to-C++/2.11-Determining-the-Size-of-a-Data-Type/2-18.cpp new file mode 100644 index 0000000..97a2850 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.11-Determining-the-Size-of-a-Data-Type/2-18.cpp @@ -0,0 +1,22 @@ +//***************************************************************** +// This program determines the size of integers, long +// integers, and long doubles. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//***************************************************************** +#include +using namespace std; + +int main() +{ + long double apple; + + cout << "The size of an integer is " << sizeof(int); + cout << " bytes.\n"; + cout << "The size of a long integer is " << sizeof(long); + cout << " bytes.\n"; + cout << "An apple can be eaten in " << sizeof(apple); + cout << " bytes\n"; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.12-Variable-Assignments-and-Initialization/2-19.cpp b/Chapter-2-Intro-to-C++/2.12-Variable-Assignments-and-Initialization/2-19.cpp new file mode 100644 index 0000000..c4215c8 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.12-Variable-Assignments-and-Initialization/2-19.cpp @@ -0,0 +1,16 @@ +//********************************************* +// This program shows variable initialization. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//********************************************* +#include +using namespace std; + +int main() +{ + int month = 2, days = 28; + + cout << "Month " << month << " has " << days << " days.\n"; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.13-Scope/2-20.cpp b/Chapter-2-Intro-to-C++/2.13-Scope/2-20.cpp new file mode 100644 index 0000000..72599f9 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.13-Scope/2-20.cpp @@ -0,0 +1,16 @@ +//*********************************************** +// This program can't find its variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//*********************************************** +#include +using namespace std; + +int main() +{ + cout << value; // ERROR! value not defined yet! + + int value = 100; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-21.cpp b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-21.cpp new file mode 100644 index 0000000..d824698 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-21.cpp @@ -0,0 +1,32 @@ +//********************************************************** +// This program calculates hourly wages, including overtime. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + double regularWages, // To hold regular wages + basePayRate = 18.25, // Base pay rate + regularHours = 40.0, // Hours worked less overtime + overtimeWages, // To hold overtime wages + overtimePayRate = 27.78, // + overtimeHours = 10, // Overtime hours worked + totalWages; + + // Calculate the regular wages. + regularWages = basePayRate * regularHours; + + // Calculate the overtime wages. + overtimeWages = overtimePayRate * overtimeHours; + + // Calculate the total wages. + totalWages = regularWages + overtimeWages; + + // Display the total wages. + cout << "Wages for this week are $" << totalWages << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-22.cpp b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-22.cpp new file mode 100644 index 0000000..851dc21 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-22.cpp @@ -0,0 +1,34 @@ +//*********************************************** +// This program caculates the amount of pay that +// will be contributed to a retirement plan if 5%, +// 7%, or 10% of monthly pay is withheld. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//*********************************************** +#include +using namespace std; + +int main() +{ + // Variables to hold the monthly pay and the + // amount of contribution. + double monthlyPay = 6000.0, contribution; + + // Calculate and display a 5% contribution. + contribution = monthlyPay * 0.05; + cout << "5 percent is $" << contribution + << " per month.\n"; + + // Calculate and display a 7% contribution. + contribution = monthlyPay * 0.07; + cout << "7 percent is $" << contribution + << " per month.\n"; + + // Calculate and display a 10% contribution. + contribution = monthlyPay * 0.1; + cout << "10 percent is $" << contribution + << " per month.\n"; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-23.cpp b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-23.cpp new file mode 100644 index 0000000..9342170 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-23.cpp @@ -0,0 +1,30 @@ +//******************************************************* +// This program calculates the sale price of an iostream +// that is regularly priced at $59.95, with a 20 percent +// discount subtracted. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//******************************************************* +#include +using namespace std; + +int main() +{ + // Variables to hold the regular price, the + // amount of a discount, and the sale price. + double regularPrice = 59.99, discount, salePrice; + + // Calculate the amount of a 20% discount. + discount = regularPrice * 0.2; + + // Calculate the sale price by subtracting the + // discount from the regular price. + salePrice = regularPrice - discount; + + // Display the results. + cout << "Regular price: $" << regularPrice << endl; + cout << "Discount amount: $" << discount << endl; + cout << "Sale price: $" << salePrice << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-24.cpp b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-24.cpp new file mode 100644 index 0000000..07e90b1 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-24.cpp @@ -0,0 +1,19 @@ +//****************************************************** +// This program extracts the rightmost digit of a number. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//****************************************************** +#include +using namespace std; + +int main() +{ + int number = 123452; + int rightMost = number % 10; + + cout << "The rightmost digit in " + << number << " is " + << rightMost << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-25.cpp b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-25.cpp new file mode 100644 index 0000000..cd2b4c3 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.14-Arithmetic-Operators/2-25.cpp @@ -0,0 +1,29 @@ +//****************************************************** +// This program converts seconds to minutes and seconds. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//****************************************************** +#include +using namespace std; + +int main() +{ + // The total seconds is 125. + int totalSeconds = 125; + + // Variables for the minutes and seconds + int minutes, seconds; + + // Get the number of minutes. + minutes = totalSeconds / 60; + + // Get the remaining seconds. + seconds = totalSeconds % 60; + + // Display the results. + cout << totalSeconds << " seconds is equivalent to:\n"; + cout << "Minutes: " << minutes << endl; + cout << "Seconds: " << seconds << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.15-Comments/2-26.cpp b/Chapter-2-Intro-to-C++/2.15-Comments/2-26.cpp new file mode 100644 index 0000000..5e6b453 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.15-Comments/2-26.cpp @@ -0,0 +1,7 @@ +// This is a single-line comment + +/* + this is a + multi-line + comment. +*/ diff --git a/Chapter-2-Intro-to-C++/2.16-Named-Constants/2-28.cpp b/Chapter-2-Intro-to-C++/2.16-Named-Constants/2-28.cpp new file mode 100644 index 0000000..c6a6d8a --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.16-Named-Constants/2-28.cpp @@ -0,0 +1,25 @@ +//******************************************************** +// This program calculates the circumference of a circle. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//******************************************************** + #include + using namespace std; + + int main() + { + // Constants + const double PI = 3.14159; + const double DIAMETER = 10.0; + + // Variable to hold the circumference + double circumference; + + // Calculate the circumference. + circumference = PI * DIAMETER; + + // Display the circumference. + cout << "The circumference is: " << circumference << endl; + return 0; + } diff --git a/Chapter-2-Intro-to-C++/2.17-Programming-Style/2-29.cpp b/Chapter-2-Intro-to-C++/2.17-Programming-Style/2-29.cpp new file mode 100644 index 0000000..718fea5 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.17-Programming-Style/2-29.cpp @@ -0,0 +1,11 @@ +//************************************ +// A program that is difficult to read. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//************************************ +#include +using namespace std;int main(){double shares=220.0; +double avgPrice=14.67;cout<<"There were "< +using namespace std; + +int main() +{ + double shares = 220.0; + double avgPrice = 14.67; + + cout << "There was " << shares << " shares sold at $"; + cout << avgPrice << " per share.\n"; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-2.cpp b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-2.cpp new file mode 100644 index 0000000..612b032 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-2.cpp @@ -0,0 +1,14 @@ +//********************************* +// A simple C++ program. +// +// By: Jesus Hilario Hernandez +// Last Updated: Novmber 21, 2016 +//********************************* +#include +using namespace std; + +int main() +{ + cout << "Programming is " << "great fun!" << endl; + return 0; +} \ No newline at end of file diff --git a/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-3.cpp b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-3.cpp new file mode 100644 index 0000000..a1b7467 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-3.cpp @@ -0,0 +1,15 @@ +//******************************************************* +// A simple C++ program +// +// By: Jesus Hilario Hernandez +// Last Updated: November 21, 2016 +//******************************************************* +#include +using namespace std; + +int main() +{ + cout << "Programming is "; + cout << "great fun!" << endl; + return 0; +} \ No newline at end of file diff --git a/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-4.cpp b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-4.cpp new file mode 100644 index 0000000..fa7c411 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-4.cpp @@ -0,0 +1,17 @@ +//***************************************** +// An unruly printing program. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 21, 2016 +//***************************************** +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers"; + cout << "Computer games"; + cout << "Coffee"; + cout << "Aspirin" << endl; + return 0; +} \ No newline at end of file diff --git a/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-5.cpp b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-5.cpp new file mode 100644 index 0000000..61b0cb3 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-5.cpp @@ -0,0 +1,18 @@ +//********************************* +// A well-adjusted printing program. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 21, 2016 +//********************************* +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers" << endl; + cout << "during the month of july:" << endl; + cout << "Computer games" << endl; + cout << "Coffee" << endl; + cout << "Aspirin" << endl; + return 0; +} \ No newline at end of file diff --git a/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-6.cpp b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-6.cpp new file mode 100644 index 0000000..f0a9577 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.2-The-cout-object/2-6.cpp @@ -0,0 +1,17 @@ +//*************************************************** +// Yet another well-adjusted printing program +// +// By: Jesus Hilario Hernandez +// Last Updated: November 21, 2016 +//*************************************************** +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers\n"; + cout << "during the month of July:\n"; + cout << "Computer games\nCoffee"; + cout << "\nAspirin\n"; + return 0; +} \ No newline at end of file diff --git a/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-7.cpp b/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-7.cpp new file mode 100644 index 0000000..426e84e --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-7.cpp @@ -0,0 +1,17 @@ +//************************************************ +// This program has a variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//************************************************ +#include +using namespace std; + +int main() +{ + int number; + + number = 5; + cout << "The value in number is " << number << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-8.cpp b/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-8.cpp new file mode 100644 index 0000000..b3596ae --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-8.cpp @@ -0,0 +1,17 @@ +//********************************************** +// This program has a variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//********************************************** +#include +using namespace std; + +int main() +{ + int number; + + number = 5; + cout << "The value in number is " << "number" << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-9.cpp b/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-9.cpp new file mode 100644 index 0000000..333ba0f --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.4-Variables-and-Literals/2-9.cpp @@ -0,0 +1,18 @@ +//******************************************** +// This program has literals and a variable. +// +// By: Jesus Hilaro Hernandez +// Last Updated: November 22, 2016 +//******************************************** +#include +using namespace std; + +int main() +{ + int apples; + + apples = 20; + cout << "Today we sold " << apples + << " bushels of apples.\n"; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.6-Integer-Data-Types/2-10.cpp b/Chapter-2-Intro-to-C++/2.6-Integer-Data-Types/2-10.cpp new file mode 100644 index 0000000..6e20e71 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.6-Integer-Data-Types/2-10.cpp @@ -0,0 +1,25 @@ +//************************************************************ +// This program has variables of several of the integer types. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//************************************************************ +#include +using namespace std; + +int main() +{ + int checking; + unsigned int miles; + long days; + + checking = -20; + miles = 4276; + days = 189000; + cout << "We have made a long journey of " << miles; + cout << " miles.\n"; + cout << "Our checking occount balance is " << checking; + cout << "\nAbout " << days << " days ago Columbus "; + cout << "stood on this spot.\n"; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.6-Integer-Data-Types/2-11.cpp b/Chapter-2-Intro-to-C++/2.6-Integer-Data-Types/2-11.cpp new file mode 100644 index 0000000..d92c140 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.6-Integer-Data-Types/2-11.cpp @@ -0,0 +1,21 @@ +//*********************************************************** +// this program show three variables defined on the same line. +// +// By: Jesus Hilario Hernandez +// Last Update: November 22, 2016 +//*********************************************************** +#include +using namespace std; + +int main() +{ + int floors, rooms, suites; + + floors = 15; + rooms = 300; + suites = 30; + cout << "The Grand Hotel has " << floors << " floors\n"; + cout << "with " << rooms << " roomms and " << suites; + cout << " suites.\n"; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-12.cpp b/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-12.cpp new file mode 100644 index 0000000..888651c --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-12.cpp @@ -0,0 +1,19 @@ +//******************************************* +// This program works with characters. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//******************************************* +#include +using namespace std; + +int main() +{ + char letter; + + letter = 'A'; + cout << letter << endl; + letter = 'B'; + cout << letter << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-13.cpp b/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-13.cpp new file mode 100644 index 0000000..71aa033 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-13.cpp @@ -0,0 +1,20 @@ +//********************************************************* +// This program demonstrates the close relationship between +// characters and integers. +// +// By: Jesus Hilario Hernandez +// Last Updates: November 22, 2016 +//********************************************************* +#include +using namespace std; + +int main() +{ + char letter; + + letter = 65; + cout << letter << endl; + letter = 66; + cout << letter << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-14.cpp b/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-14.cpp new file mode 100644 index 0000000..4b6d163 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.7-The-char-Data-Type/2-14.cpp @@ -0,0 +1,19 @@ +//***************************************** +// This program uses character literals. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//***************************************** +#include +using namespace std; + +int main() +{ + char letter; + + letter = 'A'; + cout << letter << '\n'; + letter = 'B'; + cout << letter << '\n'; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.8-The-C++-string-Class/2-15.cpp b/Chapter-2-Intro-to-C++/2.8-The-C++-string-Class/2-15.cpp new file mode 100644 index 0000000..798a305 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.8-The-C++-string-Class/2-15.cpp @@ -0,0 +1,18 @@ +//******************************************** +// This program demonstrates the string class. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//******************************************** +#include +#include // Required for the string class. +using namespace std; + +int main() +{ + string movieTitle; + + movieTitle = "Wheels of Fury"; + cout << "My favorite movie is " << movieTitle << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/2.9-Floating-Point-Data-Types/2-16.cpp b/Chapter-2-Intro-to-C++/2.9-Floating-Point-Data-Types/2-16.cpp new file mode 100644 index 0000000..2fa5c67 --- /dev/null +++ b/Chapter-2-Intro-to-C++/2.9-Floating-Point-Data-Types/2-16.cpp @@ -0,0 +1,20 @@ +//*********************************************** +// This program uses loating point data types. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//*********************************************** +#include +using namespace std; + +int main() +{ + float distance; + double mass; + + distance = 1.495979E11; + mass = 1.989E30; + cout << "The Sun is " << distance << " meters away.\n"; + cout << "The Sun\'s mass is " << mass << " kilograms.\n"; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/00.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/00.cpp new file mode 100644 index 0000000..63cb533 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/00.cpp @@ -0,0 +1,18 @@ +/******************************************************************** +* +* 00. TITLE +* Problem. +* +* Jesus Hilario Hernandez +* December 15th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/01.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/01.cpp new file mode 100644 index 0000000..ac5109c --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/01.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* 01. SUM OF TWO NUMBERS +* Write a program that stores the integers 50 and 100 in variables, +* and stores the sum of these two in a variable named total. +* +* Jesus Hilario Hernandez +* December 15th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int fifty = 50, + oneHundred = 100, + total = fifty + oneHundred; + + cout << "Total = " << total << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/02.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/02.cpp new file mode 100644 index 0000000..7962876 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/02.cpp @@ -0,0 +1,28 @@ +/******************************************************************** +* +* 02. SALES TAX +* The East Coast sales division of a company generates 58 percent +* of total sales. Based on that percentage, write a program +* that will predict how much that East Coast division will +* generate if the company has $8.6 million in sales this year. +* +* Jesus Hilario Hernandez +* December 18th 2017 +* +* +********************************************************************/ +#include + +using namespace std; + +int main() +{ + float totalSalesPercentage = .58, totalSalesThisYear = 8.6E6; + + cout << endl << endl; + cout << "The East Coast division will more than likely generate "; + cout << totalSalesPercentage * totalSalesThisYear << endl; + cout << "percent of total sales this year." << endl << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/03.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/03.cpp new file mode 100644 index 0000000..a07f630 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/03.cpp @@ -0,0 +1,34 @@ +/******************************************************************** +* +* 03. SALES PREDICTION +* Write a program that will compute the total sales tax on a +* $95 purchase. Assume the state sales tax is 4% and the +* county sales tax is 2 percent. +* +* Jesus Hilario Hernandez +* December 17th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + int purchase = 95; + float stateSalesTax = .04, + countySalesTax = .02; + + // Set decimal percision to 2 places after the decimal point. Ex 0.00 + cout << setprecision(2) << fixed << endl; + + cout << "The total state sales tax on a $95 dollar purchase is $"; + cout << purchase * stateSalesTax << endl; + + cout << "The total county sales tax on a $95 dollar purchase is $"; + cout << purchase * countySalesTax << endl << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/04.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/04.cpp new file mode 100644 index 0000000..ed31c62 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/04.cpp @@ -0,0 +1,35 @@ +/******************************************************************** +* +* 04. RESTAURANT BILL +* Write a program that computes the tax and tip on a restaurant +* bill for a patron with a $88.67 meal charge. The tax should be +* 6.75 percent of the meal cost. The tip should be 20 percent +* of the total after adding the tax. Display the meal cost, tax +* amount, tip amount, and total bill on the screen. +* +* Jesus Hilario Hernandez +* December 18th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + float mealCharge = 88.67, + taxPercentage = .0675, + tipPercentage = .20, + mealChargeTaxAmount = mealCharge * taxPercentage, + mealChargeTipAmount = (mealCharge + mealChargeTaxAmount) * tipPercentage; + + cout << setprecision(2) << fixed; + cout << "\nMeal cost : $" << mealCharge << endl; + cout << "Tax amount: $" << mealChargeTaxAmount << endl; + cout << "Tip amount: $" << mealChargeTipAmount << endl; + cout << "Total bill: $" << mealCharge + mealChargeTaxAmount + mealChargeTipAmount << endl << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/05.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/05.cpp new file mode 100644 index 0000000..2157557 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/05.cpp @@ -0,0 +1,37 @@ +/******************************************************************** +* +* 05. AVERAGE OF VALUES +* To get the average of a series of values, you add the values +* up and then divide the sum by the number of values. Write a +* program that stores the following values in five different +* variables: 28, 32, 37, 24, and 33. The program should first * calculate the sum of these five variables and store the result +* in a separate variable name sum. Then, the program should divide +* the sum variable by 5 to get the average. Display the average on +* the screen. +* +* Jesus Hilario Hernandez +* December 18th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + int a = 28, + b = 32, + c = 37, + d = 24, + e = 33, + sum = a + b + c + d + e, + average = sum / 5; + + cout << endl << endl; + cout << "The average is " << average; + cout << endl << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/06.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/06.cpp new file mode 100644 index 0000000..94e3612 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/06.cpp @@ -0,0 +1,37 @@ +/******************************************************************** +* +* 06. ANNUAL PAY +* Suppose an employee gets paid every two weeks and earns $2,200 +* each pay period. In a year the employee gets paid 26 times. +* Write a program that defines the following variables: +* +* payAmount - 2200.0. +* payPeriods - 26. +* annualPay - to be calculated. +* +* The program should calculate the employee's total annual pay by +* multiplying the employee's pay amount by the number of pay +* periods in a year and store the result in the annualPay variable. +* Display the total annual pay on the screen. +* +* Jesus Hilario Hernandez +* December 18th 2017 +* +* +********************************************************************/ +#include + +using namespace std; + +int main() +{ + double payAmount = 2200.0, + payPeriods = 26, + annualPay = payAmount * payPeriods; + + cout << endl << endl; + cout << "Total annual pay = $" << annualPay; + cout << endl << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/07.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/07.cpp new file mode 100644 index 0000000..fe205b5 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/07.cpp @@ -0,0 +1,37 @@ +/******************************************************************** +* +* 07. OCEAN LEVELS +* Assuming the ocean's level is currently rising at about 1.5 +* millimeters per year, write a program the displays: +* +* - The number of millimeters higher than the current level that +* the ocean's level will be in 5 years +* +* - The number of millimeters higher than the current level that +* the ocean's level will be in 7 years +* +* - The number of millimeters higher than the current level that +* the ocean's level will be in 10 years +* +* Jesus Hilario Hernandez +* December 19th 2017 +* +* +********************************************************************/ +#include + +using namespace std; + +int main() +{ + cout << endl; + cout << "The ocean's level will grow " << 1.5 * 5; + cout << " millimeters after 5 years." << endl; + cout << "The ocean's level will grow " << 1.5 * 7; + cout << " millimeters after 7 years." << endl; + cout << "The ocean's level will grow " << 1.5 * 10; + cout << " millimeters after 10 years." << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/08.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/08.cpp new file mode 100644 index 0000000..4e54ef3 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/08.cpp @@ -0,0 +1,51 @@ +/******************************************************************** +* +* 08. TOTAL PURCHASE +* A customer in a store is purchasing five items. The prices of +* five items are +* +* Price of item 1 = $15.95 +* Price of item 2 = $24.95 +* Price of item 3 = $6.95 +* Price of item 4 = $12.95 +* Price of item 5 = $3.95 +* +* Write a program that holds the prices of the five items in +* five variables. Display each item's price, the subtotal of the +* sale, the amount of sales tax, and the total. Assume the sales +* tax is 7%. +* +* Jesus Hilario Hernandez +* December 19th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + float item1 = 15.95, + item2 = 24.95, + item3 = 6.95, + item4 = 12.95, + item5 = 3.95, + subtotal = item1 + item2 + item3 + item4 + item5, + totalSalesTax = subtotal * .07; + + cout << endl; + cout << setprecision(2) << fixed; + cout << "Item 1 = $" << item1 << endl; + cout << "Item 2 = $" << item2 << endl; + cout << "Item 3 = $" << item3 << endl; + cout << "Item 4 = $" << item4 << endl; + cout << "Item 5 = $" << item5 << endl; + cout << "Subtotal = $" << subtotal << endl; + cout << "Sales tax = $" << totalSalesTax << endl; + cout << "Grand Total = $" << subtotal + totalSalesTax << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/09.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/09.cpp new file mode 100644 index 0000000..c6e62bd --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/09.cpp @@ -0,0 +1,31 @@ +/******************************************************************** +* +* 09. CYBORG DATA TYPE SIZES +* You have been given a job as a programmer on a Cyborg +* supercomputer. In order to accomplish some calculations, you +* need to know how many bytes the following data types use: +* char, int, float, and double. +* You don't have any manuals, so you can't look this information up. +* Write a C++ program that will determine the amount of memory +* used by these types and display the information on the screen. +* +* Jesus Hilario Hernandez +* December 19th 2017 +* +* +********************************************************************/ +#include + +using namespace std; + +int main() +{ + cout << endl; + cout << "A char uses " << sizeof(char) << " byte." << endl; + cout << "An int uses " << sizeof(int) << " bytes. " << endl; + cout << "A float uses " << sizeof(float) << " bytes. " << endl; + cout << "A double uses " << sizeof(double) << " bytes. " << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/10.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/10.cpp new file mode 100644 index 0000000..e423a3a --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/10.cpp @@ -0,0 +1,32 @@ +/******************************************************************** +* +* 10. MILES PER GALLON +* A car holds 15 gallons of gasoline and can travel 375 miles +* before refueling. Write a program that calculates the number +* of miles per gallon the car gets. Display the result on the +* screen. +* +* Hint: Use the following formula to calculate miles per +* gallon (MPG): +* +* MPG = Miles Driven/Gallons of Gas Used +* +* Jesus Hilario Hernandez +* December 19th 2017 +* +* +********************************************************************/ +#include + +using namespace std; + +int main() +{ + cout << endl; + cout << "A car that holds 15 gallons of gas " << endl; + cout << "and that can travel 375 miles before " << endl; + cout << "refuling will use " << 375 / 15 << " Miles Per Gallon." << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/11.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/11.cpp new file mode 100644 index 0000000..9280345 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/11.cpp @@ -0,0 +1,41 @@ +/******************************************************************** +* +* 11. DISTANCE PER TANK OF GAS +* A car with a 20-gallon gas tank averages 23.5 mile per gallon +* when driven in town and 28.9 miles per gallon when driven on +* the highway. Write a program that calculates and displays the +* distance the car can travel on one tank of gas when driven in +* town and when driven on the highway. +* +* Hint: The following formula can be used to calculate the distance: +* +* Distance = Number of Gallons X Average Miles per Gallon +* +* Jesus Hilario Hernandez +* December 19th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + int numOfGallons = 20; + float inTownMPG = 23.5, + outOfTownMPG = 28.9; + + cout << endl; + cout << "The distance a car can travel in town" << endl; + cout << "on a 20-gallon gas tank at 23.5 MPG is "; + cout << numOfGallons * inTownMPG << " miles." << endl; + cout << endl; + cout << "The distance a car can travel on the highway" << endl; + cout << "on a 20-gallon tank of gas at 28.9 MPG is "; + cout << numOfGallons * outOfTownMPG << " miles." << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/12.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/12.cpp new file mode 100644 index 0000000..42f01ed --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/12.cpp @@ -0,0 +1,32 @@ +/******************************************************************** +* +* 12. LAND CALCULATION +* One acre of land is equivalent to 43,560 square feet. Write +* a program that calculates the number of acres in a tract of +* land with 391,876 square feet. +* +* Jesus Hilario Hernandez +* December 19th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + float numOfAcres = 391876; + + cout << setprecision(3) << fixed << endl; + cout << "---------------" << endl; + cout << "One acre of land is equivalent to 43,560 sqft." << endl; + cout << "---------------" << endl << endl; + cout << "There are approximately " << numOfAcres / 43560; + cout << " acres in a" << endl; + cout << "tract of land that has 391,876 square feet." << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/13.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/13.cpp new file mode 100644 index 0000000..5547840 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/13.cpp @@ -0,0 +1,34 @@ +/******************************************************************** +* +* 13. CIRCUIT BOARD PRICE +* An electronic company sells circuit boards at a 35 percent +* profit. Write a program that will calculate the selling price +* of a circuit board that costs $14.95. Display the result on +* the screen. +* +* Jesus Hilario Hernandez +* December 27th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + float profit = .35; + float sellingPrice = 14.95; + + cout << setprecision(2) << fixed; + + cout << endl; + cout << "An electronic company sells circuit boards at a 35 percent profit." << endl; + cout << "Therefore, the selling price of a circuit board that costs $"; + cout << sellingPrice; + cout << " is $" << (sellingPrice * profit) + sellingPrice; + cout << endl << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/14.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/14.cpp new file mode 100644 index 0000000..a8d60c9 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/14.cpp @@ -0,0 +1,27 @@ +/******************************************************************** +* +* 14. PERSONAL INFORMATION +* Write a program that displays the following pieces of +* information, each on a separate line: +* +* Your name +* Your address, with city, state, and ZIP code +* Your telephone number +* Your college major +* +* Use only a single cout statement to display all of this +* information. +* +* Jesus Hilario Hernandez +* December 15th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + cout << "\nJesus Hilario Hernandez\n1515 29th Street, San Antonio, Texas, 78404.\n361-779-3759\nComputer Science.\n" << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/15.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/15.cpp new file mode 100644 index 0000000..532c28d --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/15.cpp @@ -0,0 +1,29 @@ +/******************************************************************** +* +* 15. TRIANGLE PATTERN +* Write a program that displays the following pattern on the +* screen: +* +* * +* *** +* ***** +* ******* +* +* Jesus Hilario Hernandez +* December 15th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + cout << endl << endl; + cout << " * " << endl; + cout << " *** " << endl; + cout << " ***** " << endl; + cout << " ******* " << endl; + cout << endl << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/16.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/16.cpp new file mode 100644 index 0000000..e6b4ced --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/16.cpp @@ -0,0 +1,34 @@ +/******************************************************************** +* +* 16. DIAMOND PATTERN +* Write a program that displays the following pattern: +* +* * +* *** +* ***** +* ******* +* ***** +* *** +* * +* +* Jesus Hilario Hernandez +* December 15th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + cout << endl << endl; + cout << " * " << endl; + cout << " *** " << endl; + cout << " ***** " << endl; + cout << " ******* " << endl; + cout << " ***** " << endl; + cout << " *** " << endl; + cout << " * " << endl; + cout << endl << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/17.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/17.cpp new file mode 100644 index 0000000..e3db151 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/17.cpp @@ -0,0 +1,42 @@ +/******************************************************************** +* +* 17. STOCK COMMISSION +* Kathryn bought 750 shares of stock at a price of $35.00 per +* share. She must pay her stockbroker a 2 percent commission for +* the transaction. Write a program that calculates and displays +* the following: +* +* - The amount paid for the stock alone (without the commission) +* - The amount of the commission +* - The total amount paid (for the stock plus the commission) +* +* Jesus Hilario Hernandez +* December 27th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int sharesOfStockBought = 750, + pricePerShare = 35, + totalAmountPaidForStock = sharesOfStockBought * pricePerShare; + + float commissionPercentage = .02, + totalAmountForCommission = totalAmountPaidForStock * commissionPercentage ; + + cout << endl << endl; + cout << "Total amount paid without commission: $"; + cout << totalAmountPaidForStock << endl; + + cout << "Total amount of commission: $"; + cout << totalAmountForCommission << endl; + + cout << "Total amount paid including commission: $"; + cout << totalAmountForCommission + totalAmountPaidForStock << endl; + cout << endl << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Programming Challenges/18.cpp b/Chapter-2-Intro-to-C++/Programming Challenges/18.cpp new file mode 100644 index 0000000..61f1c6d --- /dev/null +++ b/Chapter-2-Intro-to-C++/Programming Challenges/18.cpp @@ -0,0 +1,46 @@ +/******************************************************************** +* +* 18. ENERGY DRINK CONSUMPTION +* +* A soft drink company recently survayed 16,500 of its +* customers and found that approximately 15% of those surveyed +* purchase one or more energy drinks per week. Of those +* customers who purchase energy drinks, approximately 58% +* of them prefer citrus-flavored energy drinks. Write a +* program that displays the following: +* +* - The approximate # of customers in the survey who purchase +* one or more energy drinks per week +* - The approximate # of customers in the survey who prefer +* citrus-flavored energy drinks +* +* Jesus Hilario Hernandez +* December 15th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + int survayedCustomers = 16500; + float percentThatPurchasedOneOrMore = .15, + percentThatPreferCitrusFlavored = .58, + totalThatPurchasedOneOrMore = survayedCustomers * percentThatPurchasedOneOrMore; + + cout << setprecision(0) << fixed; + cout << endl << endl; + cout << "The approximate # of customers in the survey who" << endl; + cout << "purchase one or more energy drinks per week is "; + cout << totalThatPurchasedOneOrMore << endl; + + cout << "The approximate # of customers in the survey who" << endl; + cout << "prefer citrus-flavored energy drinks "; + cout << (totalThatPurchasedOneOrMore) * percentThatPreferCitrusFlavored << endl; + cout << endl << endl; + + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Review Questions and Exercises/Algorithm Workbench/27.cpp b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Algorithm Workbench/27.cpp new file mode 100644 index 0000000..0c07e0a --- /dev/null +++ b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Algorithm Workbench/27.cpp @@ -0,0 +1,27 @@ +//****************************************************************** +// Convert the follow pseudocode to C++ code. Be sure to define the +// appropriate variables. +// +// Store 20 in the speed variable. +// Store 10 in the time variable. +// Multiply speed by time and store the result in the +// distance variable. +// Display the contents of the distance variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//****************************************************************** +#include +using namespace std; + +int main() +{ + int speed = 20, + time = 10, + distance; + + distance = speed * time; + cout << "The distance of speed multiplied by time is " << distance + << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Review Questions and Exercises/Algorithm Workbench/28.cpp b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Algorithm Workbench/28.cpp new file mode 100644 index 0000000..2857cc1 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Algorithm Workbench/28.cpp @@ -0,0 +1,31 @@ +//********************************************************** +// Convert the follow pseudocode to C++ code. Be sure to +// define the appropriate variables. +// +// Store 172.5 in the force variable. +// Store 27.5 in the area variable. +// Divide area by force and store the result in the +// pressure variable. +// Display the contents of the pressure variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + // Declare variables + double force = 172.5, + area = 27.5, + pressure; + + // Divide area by force and store in pressure variables + pressure = force / area; + + // Display contents in the pressure variables + cout << "\nThe contents in the pressure variable are " << pressure + << endl << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Review Questions and Exercises/Find the Error/29.cpp b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Find the Error/29.cpp new file mode 100644 index 0000000..fd6f9f0 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Find the Error/29.cpp @@ -0,0 +1,20 @@ +//*************************************************************** +// There are a number of syntax errors in the following program. +// Locate as many as you can. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//*************************************************************** +/* What's wrong with this program */ +#include +using namespace std; + +int main() +{ + int a, b, c; // Three integers + a = 3; + b = 4; + c = a + b; + cout << "The value of c is %d" << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/17.cpp b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/17.cpp new file mode 100644 index 0000000..e466876 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/17.cpp @@ -0,0 +1,47 @@ +//************************************************************************ +// Assume w = 5, x = 4, y = 8, and z = 2. What value will +// be stored in result in each of the following statements? +// A) result = x + y; +// B) result = z * 2; +// C) result = y / x; +// D) result y - z; +// E) result = w % 2; +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//************************************************************************ +#include +using namespace std; + +int main() +{ + int w = 5, + x = 4, + y = 8, + z = 2, + result; + // A) + result = x + y; + cout << "The result variable holds a value of " << result << endl; + + // B) + result = z * 2; + cout << "The result variable now holds a value of " << result << endl; + + // C) + result = y / x; + cout << "The result variable now holds a value of " << result << endl; + + // D) + result = y - z; + cout << "The result variable now holds a value of " << result << endl; + + // E) + result = y - z; + cout << "The result variable now holds a value of " << result << endl; + + // F) + result = w % 2; + cout << "The result variable now holds a value of " << result << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/4.cpp b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/4.cpp new file mode 100644 index 0000000..7167ec3 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/4.cpp @@ -0,0 +1,46 @@ +//****************************************************************** +// Write assignment statements that perform the following operations +// with the variables a, b, and c. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//****************************************************************** +#include +using namespace std; + +int main() +{ + double a, b; + char c; + + // A. + a = 2; + b = a; + cout << "The value in a is " << a << endl; + cout << "The value in b is " << b << endl; + + // B. + a = b * 4; + cout << "The value in a is now " << a << endl; + + // C. + b = a / 3.14; + cout << "The value of variable b is now " << b << endl; + + // D. + a = b - 8; + cout << "The value of variable a is now " << a << endl; + + // E. + a = 27; + cout << "The value in variable a is now " << a << endl; + + // F. + c = 'K'; + cout << "The value in variable c is " << c << endl; + + // G. + c = 66; + cout << "The value in variable c is now " << c << endl; + return 0; +} diff --git a/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/7.cpp b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/7.cpp new file mode 100644 index 0000000..4455a34 --- /dev/null +++ b/Chapter-2-Intro-to-C++/Review Questions and Exercises/Short Answer/7.cpp @@ -0,0 +1,18 @@ +//****************************************************** +// Modify the following program so it prints two blank +// lines between each line of text. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 22, 2016 +//****************************************************** +#include +using namespace std; + +int main() +{ + cout << "Two mandolins like creatures in the" << endl << endl; + cout << "dark" << endl << endl; + cout << "Creating the agony of ecstacy." << endl << endl; + cout << " - George Barker" << endl << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-1.cpp b/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-1.cpp new file mode 100644 index 0000000..76225c9 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-1.cpp @@ -0,0 +1,26 @@ +//************************************************ +// This program asks the user to enter the length +// and width of a rectangle. It calculates the +// rectangle's area and displays the value on the +// screen. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 6, 2016 +//************************************************ +#include +using namespace std; + +int main() +{ + int length, width, area; + + cout << "This program calculates the area of a "; + cout << "rectangle.\n"; + cout << "What is the length of the rectangle? "; + cin >> length; + cout << "What is the width of the rectangle? "; + cin >> width; + area = length * width; + cout << "The area of the rectangle is " << area << ".\n"; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-2.cpp b/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-2.cpp new file mode 100644 index 0000000..66ef2da --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-2.cpp @@ -0,0 +1,23 @@ +//********************************************************** +// This program asks the user to enter the length and width +// of a rectangle. It calculates the rectangle's area and +// displays the value on the screen. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 6, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + int length, width, area; + + cout << "This program calculates the area of a "; + cout << "rectangle.\n"; + cout << "Enter the length and width of the rectangle "; + cin >> length >> width; + area = length * width; + cout << "The area of the rectangle is " << area << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-3.cpp b/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-3.cpp new file mode 100644 index 0000000..36e989d --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-3.cpp @@ -0,0 +1,23 @@ +//*********************************************************** +// This program demonstrates how cin can read multiple values +// of different data types. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 6, 2016 +//*********************************************************** +#include +using namespace std; + +int main() +{ + int whole; + double fractional; + char letter; + + cout << "Enter an integer, a double, and a character: "; + cin >> whole >> fractional >> letter; + cout << "Whole: " << whole << endl; + cout << "Fractional: " << fractional << endl; + cout << "Letter: " << letter << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.10 Debugging/3-27.cpp b/Chapter-3-Expressions-and-Interactivity/3.10 Debugging/3-27.cpp new file mode 100644 index 0000000..9d605ed --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.10 Debugging/3-27.cpp @@ -0,0 +1,25 @@ +//*************************************************** +// This program asks for three numbers, then displays +// the average of the numbers. DO YOU SEE THE ERROR?? +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//*************************************************** +#include +using namespace std; + +int main() +{ + double num1, num2, num3, avg; + + cout << "Enter the first number: "; + cin >> num1; + cout << "Enter the second number: "; + cin >> num2; + cout << "Enter the third number: "; + cin >> num3; + + avg = (num1 + num2 + num3) / 3; + cout << "The average is " << avg << endl << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.11 Problem Solving/3-28.cpp b/Chapter-3-Expressions-and-Interactivity/3.11 Problem Solving/3-28.cpp new file mode 100644 index 0000000..5023112 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.11 Problem Solving/3-28.cpp @@ -0,0 +1,55 @@ +//*********************************************************** +// This program is used by General Crates, Inc. to +// calculate the volume, cost, customer, and profit +// of a crate of any size. It calculates this data from user +// input, which consists of the dimensions of the crate. +// +// By: Jesus Hilario Hernandez +// Last Update: December 12, 2016 +//*********************************************************** +#include +#include +using namespace std; + +int main() +{ + // Constants for cost and amount charged + const double COST_PER_CUBIC_FOOT = 0.23; + const double CHARGE_PER_CUBIC_FOOT = 0.5; + + // Variables + double length, // The crate's length + width, // The crate's width + height, // The crate's height + volume, // The volume of the crate + cost, // The cost to build the crate + charge, // The customer charge for the crate + profit; // The profit made on the crate + + // Set the desired output formating for numbers. + cout << setprecision(2) << fixed << showpoint; + + // Prompt the user for the crate's length, width, and height + cout << "Enter the dimensions of the crate (in feet):\n"; + cout << "Length: "; + cin >> length; + cout << "Width: "; + cin >> width; + cout << "Height: "; + cin >> height; + + // Calculate the crate's volume, the cost to produce it, + // the charge to the customer, and the profit. + volume = length * width * height; + cost = volume * COST_PER_CUBIC_FOOT; + charge = volume * CHARGE_PER_CUBIC_FOOT; + profit = charge - cost; + + // Display the calculated data. + cout << "The volume of the crate is "; + cout << volume << " cubic feet.\n"; + cout << "Cost to build: $" << cost << endl; + cout << "Charge to customer: $" << charge << endl; + cout << "Profit: $" << profit << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-4.cpp b/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-4.cpp new file mode 100644 index 0000000..82ff167 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-4.cpp @@ -0,0 +1,25 @@ +//****************************************************** +// This Program asks the user to enter the numerator and +// denominator of a fraction and it displays the decimal +// value. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 6, 2016 +//****************************************************** +#include +using namespace std; + +int main() +{ + double numerator, denominator; + + cout << "This program shows the decimal value of "; + cout << "a fraction.\n"; + cout << "Enter the numerator: "; + cin >> numerator; + cout << "Enter the denominator: "; + cin >> denominator; + cout << "The decimal value is "; + cout << (numerator / denominator) << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-5.cpp b/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-5.cpp new file mode 100644 index 0000000..991b75e --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-5.cpp @@ -0,0 +1,24 @@ +//************************************************** +// This program calculates the area of a circle. +// The formula for the area of a circle is PI times +// the radius squared. PI is 3.14159. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 6, 2016 +//************************************************** +#include +#include // Needed for pow function +using namespace std; + +int main() +{ + const double PI = 3.14159; + double area, radius; + + cout << "This program calculates the area of a circle.\n"; + cout << "What is the radius of the circle? "; + cin >> radius; + area = PI * pow(radius, 2.0); + cout << "The area is " << area << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-6.cpp b/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-6.cpp new file mode 100644 index 0000000..dfa4365 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.2 Mathematical Expressions/3-6.cpp @@ -0,0 +1,31 @@ +//************************************* +// This program calculates the average +// of three test scores. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 6, 2016 +//************************************* +#include +#include +using namespace std; + +int main() +{ + double test1, test2, test3; // To hold the scores + double average; // To hold the average + + // Get the three test scores. + cout << "Enter the first test score: "; + cin >> test1; + cout << "Enter the second test score: "; + cin >> test2; + cout << "Enter the third test score: "; + cin >> test3; + + // Calculates the average of the scores. + average = (test1 + test2 + test3) / 3.0; + + // Display the average. + cout << "The average score is: " << average << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.4 Overflow and Underflow/3-7.cpp b/Chapter-3-Expressions-and-Interactivity/3.4 Overflow and Underflow/3-7.cpp new file mode 100644 index 0000000..9169297 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.4 Overflow and Underflow/3-7.cpp @@ -0,0 +1,26 @@ +//*********************************************************** +// This program demonstrates integer overflow and underflow. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 6, 2016 +//*********************************************************** +#include +using namespace std; + +int main() +{ + // testVar is initialized with the maximum value for a short. + short testVar = 32767; + + // Display testVar + cout << testVar << endl; + + // Add 1 to testVar to make it overflow. + testVar = testVar + 1; + cout << testVar << endl; + + // Subtract 1 from testVar to make it underflow. + testVar = testVar - 1; + cout << testVar << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.4 Overflow and Underflow/3-8.cpp b/Chapter-3-Expressions-and-Interactivity/3.4 Overflow and Underflow/3-8.cpp new file mode 100644 index 0000000..07d16ea --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.4 Overflow and Underflow/3-8.cpp @@ -0,0 +1,20 @@ +//********************************************************* +// This program can be used to see how your system handles +// floating point overflow and underflow. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 6, 2016 +//********************************************************* +#include +using namespace std; + +int main() +{ + float test; + + test = 2.0e38 * 1000; // Should overflow test. + cout << test << endl; + test = 2.0E-38 / 2.0e38; // Should underflow + cout << test << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.5 Type Casting/3-10.cpp b/Chapter-3-Expressions-and-Interactivity/3.5 Type Casting/3-10.cpp new file mode 100644 index 0000000..d9a2768 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.5 Type Casting/3-10.cpp @@ -0,0 +1,21 @@ +//**************************************************** +// This program uses a type cast expression to print a +// character from a number. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//**************************************************** +#include +using namespace std; + +int main() +{ + int number = 65; + // Display the value of the number variable + cout << number << endl; + + // Display the value of number converted to the char + // data type. + cout << static_cast(number) << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.5 Type Casting/3-9.cpp b/Chapter-3-Expressions-and-Interactivity/3.5 Type Casting/3-9.cpp new file mode 100644 index 0000000..9e23fef --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.5 Type Casting/3-9.cpp @@ -0,0 +1,41 @@ +//********************************************************* +// This program uses a type cast to avoid integer division. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//********************************************************* +#include +using namespace std; + +int main() +{ + int books; // Number of books to read + int months; // Number of months spent reading + double perMonth; // Average number of books per month + + cout << "How many books do you plan to read? "; + // Error Checking + while (!(cin >> books)) + { + // Explain error + cout << "ERROR: a number must be entered: "; + // clear input stream + cin.clear(); + //discard previous input + cin.ignore(123, '\n'); + } + cout << "How many months will it take you to read them? "; + // Error checking + while (!(cin >> months)) + { + // Explain error + cout << "ERROR: a number must be entered: "; + // clear input stream + cin.clear(); + //discard previous input + cin.ignore(123, '\n'); + } + perMonth = static_cast(books) / months; + cout << "That is " << perMonth << " books per month.\n"; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.6 Multiple Assisgnments/3-11.cpp b/Chapter-3-Expressions-and-Interactivity/3.6 Multiple Assisgnments/3-11.cpp new file mode 100644 index 0000000..9f26b86 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.6 Multiple Assisgnments/3-11.cpp @@ -0,0 +1,87 @@ +//********************************************************** +// This program tracks the inventory of three widget stores +// that opened at the same time. Each store started with the +// same number of widgets in inventory. By subtracting the +// number of widgets each store has sold from its inventory, +// the current inventory can be calculated. +// +// By: Jesus Hilari Hernandez +// Last Updated: December 10, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + int begInv, // Beginning inventory for all stores + sold, // Number of widgets sold + store1, // Store 1's inventory + store2, // Store 2's inventory + store3; // Store 3's inventory + + // Get the beginning inventory for all stores. + cout << "One week ago, 3 new widget stores opened.\n"; + cout << "at the same time with the same beginning\n"; + cout << "inventory. What was the beginning inventory? "; + // Error check + while (!(cin >> begInv)) + { + // Explain Error + cout << "ERROR: a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + + // Set eat store's inventory + store1 = store2 = store3 = begInv; + + // Get the number of widgets sold in store 1. + cout << "How many widgets has store 1 sold? "; + // Error check + while (!(cin >> sold)) + { + // Explain Error + cout << "ERROR: a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + store1 -= sold; // Adjust store 1's inventory. + + // Get the number of widgets sold in store 2. + cout << "How many widgets has store 2 sold? "; + // Error check + while (!(cin >> sold)) + { + // Explain Error + cout << "ERROR: a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + store2 -= sold; // Adjust store 1's inventory. + + // Get the number of widgets sold in store 3. + cout << "How many widgets has store 3 sold? "; + // Error check + while (!(cin >> sold)) + { + // Explain Error + cout << "ERROR: a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + store3 -= sold; // Adjust store 1's inventory. + + // Display each store's current inventory. + cout << "Store 1: " << store1 << endl; + cout << "Store 2: " << store2 << endl; + cout << "Store 3: " << store3 << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-12.cpp b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-12.cpp new file mode 100644 index 0000000..573c285 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-12.cpp @@ -0,0 +1,25 @@ +//************************************************ +// This program displays three rows of numbers. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//************************************************ +#include +using namespace std; + +int main() +{ + int num1 = 2897, num2 = 5, num3 = 837, + num4 = 34, num5 = 7, num6 =1623, + num7 = 390, num8 = 3456, num9 = 12; + + // Display the first row of numbers + cout << num1 << " " << num2 << " " << num3 << endl; + + // Display the second row of numbers + cout << num4 << " " << num5 << " " << num6 << endl; + + // Display the third row of numbers + cout << num7 << " " << num8 << " " << num9 << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-13.cpp b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-13.cpp new file mode 100644 index 0000000..002e2da --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-13.cpp @@ -0,0 +1,29 @@ +//***************************************************** +// This program displays three rows of numbers. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//***************************************************** +#include +#include // Required for setw +using namespace std; + +int main() +{ + int num1 = 2897, num2 = 5, num3 = 837, + num4 = 34, num5 = 7, num6 =1623, + num7 = 390, num8 = 3456, num9 = 12; + + // Display the first row of numbers + cout << setw(6) << num1 << setw(6) + << num2 << setw(6) << num3 << endl; + + // Display the first row of numbers + cout << setw(6) << num4 << setw(6) + << num5 << setw(6) << num6 << endl; + + // Display the first row of numbers + cout << setw(6) << num7 << setw(6) + << num8 << setw(6) << num9 << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-14.cpp b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-14.cpp new file mode 100644 index 0000000..84a3b2a --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-14.cpp @@ -0,0 +1,23 @@ +//***************************************************** +// This program demonstrates the setw manipulator being +// used with values of various data types. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//***************************************************** +#include +#include +#include +using namespace std; + +int main() +{ + int intValue = 3928; + double doubleValue = 91.5; + string stringValue = "John J. Smith"; + + cout << "(" << setw(5) << intValue << ")" << endl; + cout << "(" << setw(8) << doubleValue << ")" << endl; + cout << "(" << setw(16) << stringValue << ")" << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-15.cpp b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-15.cpp new file mode 100644 index 0000000..1ab03c0 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-15.cpp @@ -0,0 +1,24 @@ +//**************************************************** +// This program demonstrates how setprecision rounds a +// floating pint value. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//**************************************************** +#include +#include +using namespace std; + +int main() +{ + double quotient, number1 = 132.364, number2 = 26.91; + + quotient = number1 / number2; + cout << quotient << endl; + cout << setprecision(5) << quotient << endl; + cout << setprecision(4) << quotient << endl; + cout << setprecision(3) << quotient << endl; + cout << setprecision(2) << quotient << endl; + cout << setprecision(1) << quotient << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-16.cpp b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-16.cpp new file mode 100644 index 0000000..bdfb26f --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-16.cpp @@ -0,0 +1,36 @@ +//***************************************************** +// This program asks for sales figurres for 3 days. The +// total sales are calculated and displayed in a table. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//***************************************************** +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + // Get the sales for each day. + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + // Calculate the total sales. + total = day1 + day2 + day3; + + // Display the sales figures. + cout << "\nSales Figures\n"; + cout << "-------------\n"; + cout << setprecision(5); + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-17.cpp b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-17.cpp new file mode 100644 index 0000000..0f06e02 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.7 Formatting Output/3-17.cpp @@ -0,0 +1,36 @@ +//********************************************************** +// This program asks for sales figures for 3 days. The total +// sales are calculated and displayed in a table. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//********************************************************** +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + // Get the sales for each day. + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + // Calculate the total sales. + total = day1 + day2 + day3; + + // Display the sales figures. + cout << "\nSales Figures\n"; + cout << "--------------\n"; + cout << setprecision(2) << fixed; + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-18.cpp b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-18.cpp new file mode 100644 index 0000000..acae859 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-18.cpp @@ -0,0 +1,25 @@ +//******************************************************** +// This progam illustrates a problem that can occur if +// cin is used to read character data into a string object. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//******************************************************** +#include +#include +using namespace std; + +int main() +{ + string name; + string city; + + cout << "Please enter your name: "; + cin >> name; + cout << "Enter the city you live in: "; + cin >> city; + + cout << "Hello, " << name << endl; + cout << "You live in " << city << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-19.cpp b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-19.cpp new file mode 100644 index 0000000..371665d --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-19.cpp @@ -0,0 +1,25 @@ +//***************************************************** +// This program demonstrates using the getline function +// to read character data into a string object. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//***************************************************** +#include +#include +using namespace std; + +int main() +{ + string name; + string city; + + cout << "Please enter your name: "; + getline(cin, name); + cout << "Enter the city you live in: "; + getline(cin, city); + + cout << "Hello, " << name << endl; + cout << "You live in " << city << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-20.cpp b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-20.cpp new file mode 100644 index 0000000..d8cc522 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-20.cpp @@ -0,0 +1,19 @@ +//************************************************* +// This program reads a single character into a char +// variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//************************************************* +#include +using namespace std; + +int main() +{ + char ch; + + cout << "Type a character and press Enter: "; + cin >> ch; + cout << "You entered " << ch << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-21.cpp b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-21.cpp new file mode 100644 index 0000000..05b7b55 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-21.cpp @@ -0,0 +1,23 @@ +//****************************************************** +// This program demonstrates three ways to use cin.get() +// to pause a program. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//****************************************************** +#include +using namespace std; + +int main() +{ + char ch; + + cout << "This program has paused. Press Enter again."; + cin.get(ch); + cout << "It has paused a second time. Please press Enter again. "; + ch = cin.get(); + cout << "It has paused a third time. Please press Enter again. "; + cin.get(); + cout << "Thank you!" << endl << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-22.cpp b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-22.cpp new file mode 100644 index 0000000..2ea4857 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-22.cpp @@ -0,0 +1,22 @@ +//************************************************ +// This program demonstrates a problem that occurs +// when you mix cin >> with cin.get(). +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//************************************************ +#include +using namespace std; + +int main() +{ + char ch; // Define a character variable + int numbers; // Define an integer variable + + cout << "Enter a number: "; + cin >> numbers; // Read an integer + cout << "Enter a character: "; + ch = cin.get(); // Read a character + cout << "Thank You!\n"; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-23.cpp b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-23.cpp new file mode 100644 index 0000000..1204bf6 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.8 Characters and string Objects/3-23.cpp @@ -0,0 +1,23 @@ +//***************************************** +// This program successfully uses both +// cin >> and cin.get() for keyboard input. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//***************************************** +#include +using namespace std; + +int main() +{ + char ch; + int number; + + cout << "Enter a number: "; + cin >> number; + cin.ignore(); // Skip the newline character + cout << "Enter a character: "; + ch = cin.get(); + cout << "Thank You!\n"; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-24.cpp b/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-24.cpp new file mode 100644 index 0000000..1bb41e0 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-24.cpp @@ -0,0 +1,26 @@ +//******************************************************** +// This program asks for the lengths of the two sides of a +// right triangle. The length of the hypotenuse is then +// calculated and displayed. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//******************************************************** +#include +#include // For setprecision +#include // Fot the sqrt and pow functions +using namespace std; + +int main() +{ + double a, b, c; + + cout << "Enter the length of side a: "; + cin >> a; + cout << "Enter the length of side b: "; + cin >> b; + c = sqrt(pow(a, 2.0) + pow(b, 2.0)); + cout << "The length of the hypotenuse is "; + cout << setprecision(2) << c << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-25.cpp b/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-25.cpp new file mode 100644 index 0000000..04fcd54 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-25.cpp @@ -0,0 +1,25 @@ +//********************************************* +// This program demonstrates random numbers. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//********************************************* +#include +#include // For rand and srand +#include +using namespace std; + +int main() +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + // Display three random numbers. + cout << rand() << endl; + cout << rand() << endl; + cout << rand() << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-26.cpp b/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-26.cpp new file mode 100644 index 0000000..7bd53a6 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/3.9 Math Library Functons/3-26.cpp @@ -0,0 +1,46 @@ +//************************************ +// This program simulates rolling dice. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 10, 2016 +//************************************ +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +int main() +{ + // Constants + const int MIN_VALUE = 1; // Minimum die value + const int MAX_VALUE = 6; // Maximum die value + + // Variables + int die1; // To hold the value of die #1 + int die2; // To hold the value of die #2 + + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + cout << "Rolling the dice...\n"; + die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << die1 << endl; + cout << die2 << endl; + + cout << "Rolling the dice...\n"; + die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << die1 << endl; + cout << die2 << endl; + + cout << "Rolling the dice...\n"; + die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << die1 << endl; + cout << die2 << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/00.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/00.cpp new file mode 100644 index 0000000..0698c1b --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/00.cpp @@ -0,0 +1,17 @@ +/******************************************************************** +* +* 00. TITLE +* Problem. +* +* Jesus Hilario Hernandez +* Date 15th 0000 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/25.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/25.cpp new file mode 100644 index 0000000..93bbfa5 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/25.cpp @@ -0,0 +1,26 @@ +/******************************************************************** +* +* 25. A retail store grants its customers a maximum amout of +* credit. Each customer's available credit is his or her +* maximum amount of credit minus the mount of credit used. +* Write a pseudocode algorithm for a program that asks for a +* customer's maximum amount of credit and amount of credit +* used. The program should then disply the customer's available +* credit. +* +* Jesus Hilario Hernandez +* Jan. 4th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Ask the user for the maximum amount of credit. + // Ask the user for the amount of credit used. + // Calculate by subtracting credit used from maximum amount. + // Display users available credit. + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/26.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/26.cpp new file mode 100644 index 0000000..7053ecf --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/26.cpp @@ -0,0 +1,56 @@ +/******************************************************************** +* +* 26. Write a pseudocode algorithm for a program that calculates +* the total of a retail sale. The program should ask for the +* amount of the sale and the sales tax rate. The sales tax rate +* should be entered as a floating-point number. For example, +* if the sales tax rate is 6 percent, the use should enter +* 0.06. The program should display the amount of sales tax and +* the total of the sale. +* +* After you write the pseudocode algorithm, conbert it to a +* complete C__ program. +* +* Jesus Hilario Hernandez +* Jan. 4th 2018 +* +********************************************************************/ +#include +#include +using namespace std; + +int main() +{ + // Ask the user for the amount of sale. + // Ask for the sales tax rate as a floating-point number. + // Calculate the sales tax by multiplying it by the amount of sale + // Calculate the total by adding the sales tax amount to the amount of sale + // Display sales tax total + // Display total amount of sale + + // Variables + float salesTaxRate, amountOfSale, salesTaxTotal, totalAmountOfSale; + + // Ask for input + cout << endl; + cout << "Enter the amount of sale: "; + cin >> amountOfSale; + cout << "Enter percentage of sales tax, Ex. if 6% type (.06): "; + cin >> salesTaxRate; + + // Calculate + salesTaxTotal = amountOfSale * salesTaxRate; + totalAmountOfSale = amountOfSale + salesTaxTotal; + + // Display + cout << endl; + cout << "Amount of sale = $" << amountOfSale << endl; + cout << "Sales tax rate = $" << salesTaxRate << endl; + cout << setprecision(2) << fixed; + cout << "Total sales tax = $" << salesTaxTotal << endl; + cout << "Total amount of sale = $" << totalAmountOfSale << endl; + cout << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/27.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/27.cpp new file mode 100644 index 0000000..f853461 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Algorithm Workbench/27.cpp @@ -0,0 +1,49 @@ +/******************************************************************** +* +* 27. Write a pseudocode algorithm for a program that asks the user +* enter a golfer's score for three games of golf, and then +* displays the average of the three scores. +* +* After you write the pseudocode algorithm, convert +* it to a complete C++ program. +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Ask user for three scores. + // Calculate the average of the three scores. + // Display the average of the three scores. + + // Variables + int x, y, z, average; + + // Ask user for three scores: + cout << endl; + cout << "Enter three scores for three golf games. " << endl; + + cout << "Enter Score 1: "; + cin >> x; + + cout << "Enter Score 2: "; + cin >> y; + + cout << "Enter Score 3: "; + cin >> z; + + // Calculate average of three scores: + average = (x + y + z) / 3; + + // Display average score: + cout << "Your average score for three golf games is "; + cout << average << endl; + cout << endl; + + // Terminate Program. + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Fill-in-the-Blank/15-24.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Fill-in-the-Blank/15-24.cpp new file mode 100644 index 0000000..e430d7f --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Fill-in-the-Blank/15-24.cpp @@ -0,0 +1,72 @@ +/******************************************************************** +* +* 15-24. Use the following functions and include statements within +* a program: +* 15. cosine +* 16. sine +* 17. tangent +* 18. exponential +* 19. remainder +* 20. natural logarithm +* 21. base-10 logarithm +* 22. power +* 23. square root +* 24. +* +* Jesus Hilario Hernandez +* January 4th 2017 +* +* +********************************************************************/ +#include +#include // 24. + +using namespace std; + +int main() +{ + int x = 2; + double y = 0; // double has a higher data type ranking than an int + + cout << endl; + + // 15. consine + y = cos(x); + cout << "y = cos(x) is " << y << endl; + + // 16. sine + y = sin(x); + cout << "y = sin(x) is " << y << endl; + + // 17. tangent + y = tan(x); + cout << "y = tan(x) is " << y << endl; + + // 18. exponential + y = exp(x); + cout << "y = exp(x) is " << y << endl; + + // 19. remainder + y = fmod(45, x); + cout << "y = fmod(45, x) is " << y << endl; + + // 20. natural logarithm (ln) + y = log(x); + cout << "y = log(x) is " << y << endl; + + // 21. base-10 logarithm + y = log10(x); + cout << "y = log10(x) is " << y << endl; + + // 22. power + y = pow(x, 2); + cout << "y = pow(x, 2) is " << y << endl; + + // 23. square root + y = sqrt(x); + cout << "y = sqrt(x) is " << y << endl; + cout << endl; + + // Treminate program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/00.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/00.cpp new file mode 100644 index 0000000..82235a8 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/00.cpp @@ -0,0 +1,17 @@ +/******************************************************************** +* +* 00. Each of the following programs has some errors. Locate as +* many as you can. +* +* Jesus Hilario Hernandez +* Date 15th 0000 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/28.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/28.cpp new file mode 100644 index 0000000..dc44b81 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/28.cpp @@ -0,0 +1,27 @@ +/******************************************************************** +* +* 28. Each of the following programs has some errors. Locate as +* many as you can. +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + double number1, number2, sum; + + cout << endl; + cout << "Enter a number: "; + cin >> number1; + cout << "Enter another number: "; + cin >> number2; + sum = number1 + number2; + cout << "The sum of the two numbers is " << sum; + cout << endl << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/29.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/29.cpp new file mode 100644 index 0000000..c0078d7 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/29.cpp @@ -0,0 +1,28 @@ +/******************************************************************** +* +* 29. Each of the following programs has some errors. Locate as +* many as you can. +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int number1, number2; + float quotient; + + cout << endl; + cout << "Enter two numbers and I will divide\n"; + cout << "the first by the second for you.\n"; + cin >> number1 >> number2; + + quotient = static_cast(number1) / number2; + + cout << quotient << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/30.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/30.cpp new file mode 100644 index 0000000..47e05b9 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/30.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* 30. Each of the following programs has some errors. Locate as +* many as you can. +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int number1, number2, product; + + cout << endl; + cout << "Enter two numbers and I will multiply them for you.\n"; + cin >> number1 >> number2; + product = number1 * number2; + cout << number1 << " * " << number2 << " = " << product << endl << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/31.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/31.cpp new file mode 100644 index 0000000..d7927bd --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/31.cpp @@ -0,0 +1,27 @@ +/******************************************************************** +* +* 31. Each of the following programs has some errors. Locate as +* many as you can. +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int number1, number2; + + cout << endl; + cout << "Enter two numbers and I will multiply\n"; + cout << "them by 50 for you.\n"; + cin >> number1 >> number2; + number1 *= 50; + number2 *= 50; + cout << number1 << " " << number2 << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/32.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/32.cpp new file mode 100644 index 0000000..6100ad3 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/32.cpp @@ -0,0 +1,28 @@ +/******************************************************************** +* +* 32. Each of the following programs has some errors. Locate as +* many as you can. +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + double number1, half; + + cout << endl; + cout << "Enter a number and I will divide it\n"; + cout << "in half for you.\n"; + cin >> number1; + half = number1 / 2; + cout << fixed << showpoint << half << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/33.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/33.cpp new file mode 100644 index 0000000..982d8cb --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Find the Errors/33.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* 33. Each of the following programs has some errors. Locate as +* many as you can. +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + string name; + + cout << endl; + cout << "Enter your name: "; + getline(cin, name); + cout << "Hi " << name << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/00.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/00.cpp new file mode 100644 index 0000000..0de5b3d --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/00.cpp @@ -0,0 +1,17 @@ +/******************************************************************** +* +* 00. What will the following program display? (Some should be +* traced and require a calculator.) +* +* Jesus Hilario Hernandez +* DATE 00th 0000 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/34.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/34.cpp new file mode 100644 index 0000000..ff26e76 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/34.cpp @@ -0,0 +1,23 @@ +/******************************************************************** +* +* 34. What will the following program display? (Some should be +* traced and require a calculator.) +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + double salary, monthly; + cout << endl; + cout << "What is your annual salary? "; + cin >> salary; + monthly = static_cast(salary) / 12; + cout << "Your monthly wages are " << monthly << endl; + cout << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/35.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/35.cpp new file mode 100644 index 0000000..be0c8ef --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/35.cpp @@ -0,0 +1,26 @@ +/******************************************************************** +* +* 34. What will the following program display? (Some should be +* traced and require a calculator.) +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + long x, y, z; + + x = y = z = 4; + x += 2; + y -= 1; + z *= 3; + + cout << endl; + cout << x << ' ' << y << " " << z << endl; + cout << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/36.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/36.cpp new file mode 100644 index 0000000..71af16c --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/36.cpp @@ -0,0 +1,31 @@ +/******************************************************************** +* +* 36. What will the following program display? (Some should be +* traced and require a calculator.) +* +* +* (Assume the user enters George Washington.) +* +* +* Jesus Hilario Hernandez +* January 6th 2018 +* +********************************************************************/ +#include +#include +#include + +using namespace std; + +int main() +{ + string userInput; + cout << endl; + cout << "What is your name? "; + getline(cin, userInput); + cout << "Hello " << userInput << endl; + cout << endl; + + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/37.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/37.cpp new file mode 100644 index 0000000..0ad973a --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Predict the Output/37.cpp @@ -0,0 +1,44 @@ +/******************************************************************** +* +* 37. What will the following program display? (Some should be +* traced and require a calculator.) +* +* +* (Assume the user enters 36720152. Use a calculator.) +* Jesus Hilario Hernandez +* January 6th 2017 +* +********************************************************************/ +#include +#include +using namespace std; + +int main() +{ + long seconds; + double minutes, hours, days, months, years; + + cout << endl; + cout << "Enter the number of seconds that have\n"; + cout << "elapsed since some time in the past and\n"; + cout << "I will tell you how many minutes, hours,\n"; + cout << "days, months, and years have passed: "; + cin >> seconds; + + minutes = seconds / 60; + hours = minutes / 60; + days = hours / 24; + years = days / 365; + months = years * 12; + + cout << endl; + cout << setprecision(4) << fixed << showpoint << right; + cout << "Minutes: " << setw(6) << minutes << endl; + cout << "Hours: " << setw(6) << hours << endl; + cout << "Days: " << setw(6) << days << endl; + cout << "Months: " << setw(6) << months << endl; + cout << "Years: " << setw(6) << years << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/00.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/00.cpp new file mode 100644 index 0000000..c18dff9 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/00.cpp @@ -0,0 +1,18 @@ +/******************************************************************** +* +* 00. TITLE +* +* Problem. +* +* Jesus Hilario Hernandez +* Date 15th 0000 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/01.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/01.cpp new file mode 100644 index 0000000..17fb064 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/01.cpp @@ -0,0 +1,42 @@ +/******************************************************************** +* +* 01. MILES PER GALLON +* +* Write a program that calculates a car's gas mileage. The +* program should ask the user to enter the number of gallons of +* gas the car can hold and the number of miles it can be driven +* on a full tank. It should then display the number of miles +* that may be driven per gallon of gas. +* +* Jesus Hilario Hernandez +* January 9th 2017 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int numberOfGallons, + fullTankMiles; + float MPG; + + // Ask user to enter number of gallons car can hold + cout << endl; + cout << "Enter number of gallons the car can hold: "; + cin >> numberOfGallons; + + // Ask user for number of miles can be driven on full tank + cout << "Enter number of miles the car can be " << endl; + cout << "driven on a full tank of gas: "; + cin >> fullTankMiles; + + // Calculate number of miles that can be driven per gallon of gas + MPG = static_cast(fullTankMiles) / numberOfGallons; + + // Display number of miles driven per gallon of gas + cout << "The car gets " << MPG << " miles per gallon."<< endl; + cout << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/02.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/02.cpp new file mode 100644 index 0000000..a37efa3 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/02.cpp @@ -0,0 +1,82 @@ +/******************************************************************** +* +* 02. STADIUM SEATING +* +* There are three seating categories at a stadium. For a +* softball game, Class A seats cost $15, Class B seats cost $12, +* and Class C seats cost $9. Write a program that ask how many +* tickets for each class of seats were sold, then displays the +* amount of income generated from ticket sales. Format your dollar +* amount in fixed-point notation, with two decimal places of +* precision, and be sure the decimal point is always displayed. +* +* Jesus Hilario Hernandez +* January 9th 2017 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + const float CLASS_A_COST_PER_SEAT = 15.00, + CLASS_B_COST_PER_SEAT = 12.00, + CLASS_C_COST_PER_SEAT = 9.00; + + int seatsSoldClassA, + seatsSoldClassB, + seatsSoldClassC; + + float classATotal, + classBTotal, + classCTotal, + totalIncomeGenerated; + + // Ask user for number of seats sold per class + cout << endl; + cout << "Enter number of seats sold in Class A: "; + cin >> seatsSoldClassA; + cout << "Enter number of seats sold in Class B: "; + cin >> seatsSoldClassB; + cout << "Enter number of seats sold in Class C: "; + cin >> seatsSoldClassC; + + // Calculate cost per section + classATotal = seatsSoldClassA * CLASS_A_COST_PER_SEAT; + classBTotal = seatsSoldClassB * CLASS_B_COST_PER_SEAT; + classCTotal = seatsSoldClassC * CLASS_C_COST_PER_SEAT; + + totalIncomeGenerated = classATotal + classBTotal + classCTotal; + + // Display income generated from ticket sales + cout << endl; + cout << setprecision(2) << fixed; + cout << seatsSoldClassA << " Class A seats @ $"; + cout << setw(6) << CLASS_A_COST_PER_SEAT; + cout << " = $" << classATotal << '.' << endl; + + cout << seatsSoldClassB << " Class B seats @ $"; + cout << setw(6) << CLASS_B_COST_PER_SEAT; + cout << " = $" << classBTotal << '.' << endl; + + cout << seatsSoldClassC << " Class C seats @ $"; + cout << setw(6) << CLASS_C_COST_PER_SEAT; + cout << " = $" << classCTotal << '.' << endl; + + cout << endl; + cout << setw(6) << "Total income generated for all seats: $"; + cout << totalIncomeGenerated << '.' << endl; + cout << endl; + + // Terminate Program + return 0; +} +// Resources used: +// +// <---- how to declare a constant int ---->: +// Chapter-7-Arrays/7.5-the-range-based-for-loop/7-12.cpp +// +// diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/03.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/03.cpp new file mode 100644 index 0000000..38cd84a --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/03.cpp @@ -0,0 +1,53 @@ +/******************************************************************** +* +* 03. TEST AVERAGE +* +* Write a program that asks for five test scores. The program +* should calculate the average test score and display it. +* The number displayed should be formatted in fixed-point +* notation, with one decimal point of precision. +* +* Jesus Hilario Hernandez +* January 10th 2017 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables & Arrays + const int NUM_OF_SCORES = 5; + float testScores[NUM_OF_SCORES], + average, + total; + + // Ask user for 5 test scores + cout << "\nThis program will calculate the average of 5 test scores.\n"; + cout << "\nPress enter to continue"; + cin.get(); + cout << endl; + + // Put test scores into an array + for (int x = 0; x < NUM_OF_SCORES; x++) + { + cout << "Enter test score #" << (x + 1) << ": "; + cin >> testScores[x]; + + // Calculate total by adding test scores together + total += testScores[x]; + } + + // Calculate average test score + average = total / NUM_OF_SCORES; + + // Display average test score --> used fixed point with one decimal + cout << setprecision(1) << fixed; + cout << "\nThe averages test score is " << average << endl; + cout << endl; + + //Terminate Program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/04.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/04.cpp new file mode 100644 index 0000000..baae9c1 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/04.cpp @@ -0,0 +1,57 @@ +/******************************************************************** +* +* 04. AVERAGE RAINFALL +* +* Write a program that calculates the average rainfall for three +* months. The program should ask the user to enter the name of +* each month, such as Jun or July, and the amount of rain +* (in inches) that fell each month. The program should +* display a message similar to the following: +* +* The average rainfal for June, July, and August is 6.72 inches. +* +* Jesus Hilario Hernandez +* January 9th 2017 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + const int NUM_OF_MONTHS = 3; + string months[NUM_OF_MONTHS]; + float rainfall[NUM_OF_MONTHS], + total, + average; + + // This Program calculate the average rainfall for three months + cout << endl; + cout << "---------------------------------------------------------------"; + cout << "\nThis program calculate the average rainfall for three months." << endl; + cout << "---------------------------------------------------------------"; + cout << "\n\nPress enter to continue." << endl; + cin.get(); + + // Ask user to enter name of each month. + // Ask user to enter amount of rain for each month (in inches). + for (int x = 0; x < NUM_OF_MONTHS; x++) + { + cout << "Enter name of " << (x + 1) << "st month: "; + cin >> months[x]; + cout << "How many inches of rain fell for " << months[x] << ": "; + cin >> rainfall[x]; + total += rainfall[x]; + } + + // Calculte the average rain fall for those three months + average = total / NUM_OF_MONTHS; + + // Display rainfall average + cout << "\nThe average rainfall for "; + cout << months[0] << ", " << months[1] << ", and " << months[2]; + cout << " is " << average << " inches.\n" << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/05.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/05.cpp new file mode 100644 index 0000000..b43db46 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/05.cpp @@ -0,0 +1,53 @@ +/******************************************************************** +* +* 05. MALE AND FEMALE PERCENTAGES +* +* Write a program that asks the user for the number of males and +* the number of females registered in a class. The program +* should display the percentage of males and females in the class. +* +* Hint: Suppose there are 8 males and 12 females in a class. +* There are 20 students in the class. The percentage of males +* can be calculated as 8 / 20 = 0.4, or 40%. The percentage +* of females can be calculated as 12 / 20 = 0.06, or 60%. +* +* Jesus Hilario Hernandez +* January 6th 2017 +* +********************************************************************/ +#include +#include +using namespace std; + +int main() +{ + // Variables + int number_of_males, + number_of_females, + total_num_of_students; + + float percentage_of_males, + percentage_of_females; + + // Ask user for number of males and females in the class. + cout << endl; + cout << "How many males have register for the class: "; + cin >> number_of_males; + cout << "How many females have registered: "; + cin >> number_of_females; + cout << endl; + + // Calculate the percentage of each with the class. + total_num_of_students = number_of_males + number_of_females; + percentage_of_males = (number_of_males / static_cast(total_num_of_students)) * 100; + percentage_of_females = (number_of_females / static_cast(total_num_of_students)) * 100; + + // Display the percentage of male and females in the class. + cout << setprecision(2); + cout << "There are " << total_num_of_students << " in the class. " << endl; + cout << "The percentage of males in the class is %" << percentage_of_males << '.' << endl; + cout << "The percentage of females is %" << percentage_of_females << '.' << endl << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/06.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/06.cpp new file mode 100644 index 0000000..22e9686 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/06.cpp @@ -0,0 +1,57 @@ +/******************************************************************** +* +* 06. INGREDIENT ADJUSTER +* +* A cookie recipe calls for the following ingredients: +* - 1.5 cups of sugar +* - 1 cup of butter +* - 2.75 cups of flour +* +* The recipe produces 48 cookies with this amount of the +* ingredients. Write a program that asks the user how many +* cookies he or she wants to make, and then displays the +* number of cups of each ingredient needed for the specified number +* of cookies. +* +* Jesus Hilario Hernandez +* January 7th 2017 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + float num_of_cookies_to_make, + total_cups_butter, + total_cups_sugar, + total_cups_flour; + // Ask the user how many cookies they want to make + cout << setprecision(4); + cout << "\nHow many cookies do you want to make? "; + cin >> num_of_cookies_to_make; + + // Calculate the amount of ingredients it takes to make + // 1.5 cup of sugar = 48 cookies + // (1.5 / y) * (48 / x) + // = (1.5 / x) * (48/num_of_cookies_to_make); + // = (48x) / (1.5 * num_of_cookies_to_make) + // 1.5 * num_of_cookies_to_make = 48x + // (1.5 * num_of_cookies_to_make) / 48 = x + total_cups_sugar = (1.5 * num_of_cookies_to_make) / 48; + total_cups_butter = (1 * num_of_cookies_to_make) / 48; + total_cups_flour = (2.75 * num_of_cookies_to_make) / 48; + // 1 cup of butter = 48 cookies + // 2.75 cups of flour = 48 cookies + // Display the number of cups for each ingredient. + cout <<"To make " << num_of_cookies_to_make << " cookies "; + cout << "you will need the following ingredients: " << endl << endl; + cout << " - " << total_cups_sugar << " cups of sugar" << endl; + cout << " - " << total_cups_butter << " cups of butter" << endl; + cout << " - " << total_cups_flour << " cups of flour" << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/07.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/07.cpp new file mode 100644 index 0000000..7780f8b --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/07.cpp @@ -0,0 +1,65 @@ +/******************************************************************** +* +* 07. BOX OFFICE +* +* A movie theater only keeps a percentage of the revenue earned +* from ticket sales. The remainder goes to the movie distributor. +* Write a program that calculates a theater's gross and net box +* office profit for a night. The program should ask for the name +* of the movie, and how many adult and child tickets were sold. +* (The price of an adult ticket is $10.00 and a child's ticket +* is $6.00.) It should display a report similar to +* +* Movie Name: "Wheels of Fury" +* Adult Tickets Sold: 382 +* Child Tickets Sold: 127 +* Gross Box Office Profit: $4582.00 +* +* (NOTE: Assume the theater keeps 20 percent of the gross box +* office profit.) +* +* Jesus Hilario Hernandez +* January 7th 2017 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + string movie_name; + int adult_tickets, + child_tickets; + + float total_cost, + theater_percentage; + + // ask for the name of the movie + cout << endl; + cout << "What was the name of the movie? "; + getline(cin, movie_name); + + // ask how many adult and child tickets were sold + cout << "How many adult tickets? "; + cin >> adult_tickets; + cout << "How many child tickets? "; + cin >> child_tickets; + + // calculate the gross and net box office profit + total_cost = (adult_tickets * 10) + (child_tickets * 6); + theater_percentage = total_cost * .20; + + // display the report + cout << setprecision(2) << fixed; + cout << "Movie Name: " << movie_name << endl; + cout << "Adult tickets sold: " << setw(10) << adult_tickets << endl; + cout << "Child tickets sold: " << setw(10) << child_tickets << endl; + cout << "Total cost: $" << setw(10) << total_cost << endl; + cout << "Gross Box Office Profit @ %20: $" << setw(10) << theater_percentage << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/08.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/08.cpp new file mode 100644 index 0000000..7483581 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/08.cpp @@ -0,0 +1,58 @@ +/******************************************************************** +* +* 08. HOW MANY WIDGETS? +* +* The Yukon Widget Company manufactures widgets that weigh 12.5 +* pounds each. Write a program that calculates how many widgets +* are stacked on a pallet, based on the total weight of the +* pallet. The program should ask the user how much the pallet +* weighs by itself and with the widgets stacked on it. It +* should then calculate and display the number of widgets +* stacked on the pallet. +* +* Jesus Hilario Hernandez +* January 7th 2017 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + const float INDIVIDUAL_WIDGET_WEIGHT = 12.5; // Widget weight. + float pallet_weight, + pallet_with_widgets, + widget_weight, + number_of_widgets; + + // Ask user how much the pallet weighs by itself + cout << endl; + cout << "How much does the pallet weigh by itself? "; + cin >> pallet_weight; + + // Ask user how much the pallet weighs with widget stacked on + cout << "How much does the pallet weigh with widgets? "; + cin >> pallet_with_widgets; + + /** + * Calculate how many widgets are stacked on a pallet, + * based on the total weight of the pallet. + */ + widget_weight = pallet_with_widgets - pallet_weight; + + number_of_widgets = widget_weight / INDIVIDUAL_WIDGET_WEIGHT; + + // Display the number of widgets stacked on the pallet. + cout << setprecision(2) << fixed << right << endl; + cout << "Individual widget weight = " << setw(6) << INDIVIDUAL_WIDGET_WEIGHT << endl; + cout << "Pallet weight = " << setw(6) << pallet_weight << endl; + cout << "Pallet weight with widgets = " << setw(6) << pallet_with_widgets << endl; + cout << "Widget weight = " << setw(6) << widget_weight << endl; + cout << "Number of widgets = " << setw(6) << number_of_widgets << endl; + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/09.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/09.cpp new file mode 100644 index 0000000..79fe2dc --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/09.cpp @@ -0,0 +1,58 @@ +/******************************************************************** +* +* 09. HOW MANY CALORIES? +* +* A bag of cookies holds 30 cookies. The calorie information on +* the bag claims that there are 10 "servings" in the bag and +* that a serving equals 300 calories. Write a program that +* asks the user to input how many cookies he or she +* actually ate and then reports how many total calories +* were consumed. +* +* Jesus Hilario Hernandez +* January 16th 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + const int NUM_COOKIES_PER_BAG = 30, // Number of cookies per bag + NUM_SERVINGS_PER_BAG = 10, // Number of servings per bag + NUM_CALORIES_PER_SERVING = 300; // Calories per serving. + + // Number of cookies per serving + float num_cookies_per_serving = NUM_COOKIES_PER_BAG / NUM_SERVINGS_PER_BAG, + num_cookies_eaten, + num_servings_eaten, + num_calories_consumed; + + // Ask user to input how many cookies she actually ate + cout << endl; + cout << "How many cookies did you eat? "; + cin >> num_cookies_eaten; + + // Calculate number of servings she ate + num_servings_eaten = num_cookies_eaten / num_cookies_per_serving; + + // Calculate number of calories were consumed + num_calories_consumed = num_servings_eaten * NUM_CALORIES_PER_SERVING; + + // Display how many total calories were consumed + cout << '\n' << setprecision(2) << fixed << right; + + cout << "Number of cookies per bag = " << setw(8) << NUM_COOKIES_PER_BAG << endl; + cout << "Number of servings per bag = " << setw(8) << NUM_SERVINGS_PER_BAG << endl; + cout << "Number of calories per serving = " << setw(8) << NUM_CALORIES_PER_SERVING << endl; + cout << "Number of cookies per serving = " << setw(8) << num_cookies_per_serving << endl; + cout << "Number of cookies eaten = " << setw(8) << num_cookies_eaten << endl; + cout << "Number of servings eaten = " << setw(8) << num_servings_eaten << endl; + cout << "Number of calories consumed = " << setw(8) << num_calories_consumed << endl; + cout << endl; + + // Terminate program. + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/10.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/10.cpp new file mode 100644 index 0000000..59721c8 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/10.cpp @@ -0,0 +1,52 @@ +/******************************************************************** +* +* 10. HOW MUCH INSURANCE? +* +* Many financial experts advise that property owners should +* insure their homes or buildings for at least 80 percent +* of the amount it would cost to replace the structure. Write a +* program that asks the user to enter the replacement cost of a +* building and then displays the minimum amount of insurance he or +* she should buy for the property. +* +* Jesus Hilario Hernandez +* January 7th 2017 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Insure at least 80 percent of the cost to replace the structure + const float INSURE_AT_PERCENTAGE = .80; + float replacement_cost, + minimum_amount_insurance; + + // Ask the user to enter the replacement cost of a building + cout << endl; + cout << "-----------------------------------------------------------" << endl; + cout << "Many financial experts advise that property owners " << endl; + cout << "should insure their homes or buildings for at least" << endl; + cout << "80 percent of the amount it would cost to replace the" << endl; + cout << "structure." << endl; + cout << "-----------------------------------------------------------\n" << endl; + cout << "Press \"Enter\" to continute." << endl << endl; + cin.get(); + cout << "This program will calculate the 80 percent for you. " << endl; + cout << "-----------------------------------------------------------\n" << endl; + cout << "Enter the replacement cost of your home or building : $"; + cin >> replacement_cost; + + // Calculate + minimum_amount_insurance = replacement_cost * INSURE_AT_PERCENTAGE; + + // Display the minimum amount of insurance he should buy for property + cout << setprecision(2) << fixed; + cout << "The minimum amount of insurance to buy at %80 is : $"; + cout << minimum_amount_insurance << endl; + cout << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/11.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/11.cpp new file mode 100644 index 0000000..3bf6abd --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/11.cpp @@ -0,0 +1,60 @@ +/******************************************************************** +* +* 11. AUTOMOBILE COSTS +* +* Write a program that asks the user to enter the monthly costs +* for the following expenses incurred from operating his or +* her automobile: loan payment, insurance, gas, oil, tires, +* and maintenance. The program should then display the total +* monthly cost of these expenses, and the total annual cost of +* these expenses. +* +* Jesus Hilario Hernandez +* January 16th 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + float loan_payment, + insurance, + gas, + oil, + tires, + maintenance, + total_monthly_cost, + total_annual_cost_per_year; + + // Ask the user to enter monthly costs for car expenses: + cout << "\nEnter the following monthly costs for your automobile: "; + cout << endl << setprecision(2) << fixed; + cout << "Loan Payment : $"; + cin >> loan_payment; + cout << "Insurance : $"; + cin >> insurance; + cout << "Gas : $"; + cin >> gas; + cout << "Oil : $"; + cin >> oil; + cout << "Tires : $"; + cin >> tires; + cout << "Maintenance : $"; + cin >> maintenance; + + // Calculate total monthly cost of expenses + total_monthly_cost = loan_payment + insurance + gas + oil + tires + maintenance; + + // Calculate total annual cost of expenses + total_annual_cost_per_year = total_monthly_cost * 12; + + // Display total monthly cost + cout << "Monthly car expenses equals $" << total_monthly_cost << endl; + + // Display total annual cost + cout << "Monthly annual cost per year $" << total_annual_cost_per_year << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/12.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/12.cpp new file mode 100644 index 0000000..d223f30 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/12.cpp @@ -0,0 +1,44 @@ +/******************************************************************** +* +* 12. CELSIUS TO FAHRENHEIT +* +* Write a program that converts Celsius temperatures to +* Fahrenheit temperatures. The formula is +* +* F = (9/5)C + 32 +* +* F is the Fahrenheit temperature, and C is the +* Celsius temperature. +* +* +* Jesus Hilario Hernandez +* January 17th 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + float F, C; + + // Ask user to enter Celsius Temp. + cout << endl; + cout << "Enter the current Celsius Temperature: "; + cin >> C; + + // Calculate Fahrenheit + F = ((9.0 / 5) * C) + 32; + + // Display Fahrenheit + cout << setprecision(2) << fixed << right << endl; + cout << "Celsius Temp = " << setw(6) << C << endl; + cout << "Fahrenheit Temp = " << setw(6) << F << endl; + cout << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/13.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/13.cpp new file mode 100644 index 0000000..5f9ed16 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/13.cpp @@ -0,0 +1,55 @@ +/******************************************************************** +* +* 13. CURRENCY +* +* Write a program that will convert U.S. dollar amounts to +* Japanese yen and to euros, storing the conversion factors +* in the constants YEN_PER_DOLLAR and EUROS_PER_DOLLAR. +* To get the most up-to-date exchange rates, search the +* Internet using the term "currency exchange rate". If +* you cannot ding the most recent exchange rates, use the +* following: +* +* 1 Dollar = 98.93 Yen +* 1 Dollar = 0.74 Euros +* +* Format your currency amounts in fixed-point notation, +* with two decimal places of percision, and be sure +* the decimal point is always displayed. +* +* Jesus Hilario Hernandez +* January 17th 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Store conversion factors into constants + const float YEN_PER_DOLLAR = 111.23, // As of Jan. 17th 2018 + EUROS_PER_DOLLAR = 0.82; // As of Jan. 17th 2018 + float user_dollar_amount, + user_dollar_amount_to_Yen, + user_dollar_amount_to_Euros; + + // Ask user for dollar amount + cout << endl; + cout << "Enter your U.S. dollar amount: "; + cin >> user_dollar_amount; + + // Convert U.S. dollar to Japanese Yen and Euros + user_dollar_amount_to_Yen = user_dollar_amount * YEN_PER_DOLLAR; + user_dollar_amount_to_Euros = user_dollar_amount * EUROS_PER_DOLLAR; + + // Format currency amounts in fixed-point notation, two decimal points + // Display + cout << setprecision(2) << fixed << endl; + cout << "U.S. dollar amount = $ " << user_dollar_amount << endl; + cout << "Japanese yen amount = Â¥ " << user_dollar_amount_to_Yen << endl; + cout << "European Euro amount = € " << user_dollar_amount_to_Euros << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/14.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/14.cpp new file mode 100644 index 0000000..16c64b9 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/14.cpp @@ -0,0 +1,87 @@ +/******************************************************************** +* +* 14. MONTHLY SALES TAX +* +* A retail company must file a monthly sales tax +* report listing the sales for the month and the +* amount of sales tax collected. Write a program +* that asks for the month, the year, and the total +* amount collected at the cash register (that is, sales +* plus sales tax). Assume the state sales tax is 4 +* percent and the county sales tax is 2 percent. +* +* If the total amount collected is known and the total +* sales tax is 6 percent, the amount of +* product sales may be calculated as: +* +* S = T / 1.06 +* +* S is the product sales and T is the total income +* (product sales plus sales tax). +* +* The program should display a report similar to +* +* Month: October +* -------------------- +* Total Collected: $ 26572.89 +* Sales: $ 25068.76 +* County Sales Tax: $ 501.38 +* State Sales Tax: $ 1002.75 +* Total Sales Tax: $ 1504.13 +* +* Jesus Hilario Hernandez +* January 17th 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + const float STATE_SALES_TAX = 0.04, + COUNTY_SALES_TAX = 0.02, + SALES_TAX = 0.06; + + float S, // product sales + T, // total income (product sales + sales tax) + total_state_tax, + total_county_tax, + total_sales_tax; + + string month; + + int year; + + // Ask user for month, year, and total collected (sales plus sales tax) + cout << endl; + cout << "Enter the month to receive the report for: "; + cin >> month; + cout << "Enter the year: "; + cin >> year; + cout << "Total amount collected for the month of " << month << ": "; + cin >> T; + + // Calculate Sales, County Sales Tax, State Sales Tax, and Total Sales Tax + S = T / 1.06; + total_state_tax = S * STATE_SALES_TAX; + total_county_tax = S * COUNTY_SALES_TAX; + total_sales_tax = S * SALES_TAX; + + // Display Calculations + cout << setprecision(2) << fixed << right << endl; + cout << "---------------------------------" << endl; + cout << "Month: " << month << endl; + cout << "---------------------------------" << endl; + cout << "Total Collected: $" << setw(10) << T << endl; + cout << "Sales: $" << setw(10) << S << endl; + cout << "County Sales Tax: $" << setw(10) << total_county_tax << endl; + cout << "State Sales Tax: $" << setw(10) << total_state_tax << endl; + cout << "Total Tales Tax: $" << setw(10) << total_sales_tax << endl; + cout << "---------------------------------" << endl; + cout << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/15.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/15.cpp new file mode 100644 index 0000000..8c86cf2 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/15.cpp @@ -0,0 +1,51 @@ +/******************************************************************** +* +* 15. PROPERTY TAX +* +* A county collects property taxes on the assessment value of +* property, which is 60 percent of the property's +* actual value. If an acre of land is valued at +* $10,000, its assessment value is $6,000. The +* property tax is then 75¢ for each $100 of the assessment +* value. The tax for the acre assessed at $6,000 will be +* $45. Write a program that asks for the actual value of a +* piece of property and displays the assessment value and property +* tax. +* +* Jesus Hilario Hernandez +* January 17th 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + const float ASSESSMENT_PERCENTAGE = 0.60, + PROPERTY_TAX_PERCENTAGE = 0.75; + + float total_assessment_value, + total_property_tax, + value_of_property; + + // Ask user for actual value of piece of property. + cout << endl; + cout << "What is the actual value of a piece of property? "; + cin >> value_of_property; + + // Calculate assessment value and property tax. + total_assessment_value = value_of_property * ASSESSMENT_PERCENTAGE; + total_property_tax = (total_assessment_value / 100) * PROPERTY_TAX_PERCENTAGE; + + // Display assessment value and property tax. + cout << setprecision(2) << fixed << right << endl; + cout << "Property Value: $" << setw(12) << value_of_property << endl; + cout << "Assessment value: $" << setw(12) << total_assessment_value << endl; + cout << "Property Tax: $" << setw(12) << total_property_tax << endl; + cout << endl; + + // Terminate Program. + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/16.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/16.cpp new file mode 100644 index 0000000..c70b809 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/16.cpp @@ -0,0 +1,77 @@ +/******************************************************************** +* +* 16. SENIOR CITIZEN PROPERTY TAX +* +* Madison County provides a $5,000 homeowner exemption for its +* senior citizens. For example, if a senior's house is +* valued at $158,000 its assessed value would be $94,800, +* as explained above. However, he would only pay tax on +* $89,800. At last year's tax rate of $2.64 for each $100 of +* assessed value, the property tax would be $2,370.72. In +* addition to the tax break, senior citizens are allowed to +* pay their property tax in four equal payments. The quarterly +* payment due on this property would be $592.68. Write a +* program that asks the user to input the actual value +* of a piece of property and the current tax rate for +* each $100 of assessed value. The program should then +* calculate and report how much annual property tax a +* senior homeowner will be charged for this property +* and what the quarterly tax bill will be. +* +* Jesus Hilario Hernandez +* January 17th 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + const float ASSESSMENT_PERCENTAGE = 0.60; + + float value_of_property, + current_tax_rate, + total_annual_property_tax, + quarterly_tax_bill; + + // $5,000 homeowner exemption for senior citizens + // + // Ex: Senior's house = $158,000. assessed value = $94,800 + // But only pay tax on $89,800 ($94,800 - $5,000) + // That's ($89,800 / $100) * $2.64 = $2370.72 + // Paid quarterly is $2370.72 / 4 = $592.68 quarterly + // + + // Ask user for value of property and current tax rate + cout << endl; + cout << "----------------------------------------------\n"; + cout << "What is the value of the property? "; + cin >> value_of_property; + cout << "What is the current tax rate? "; + cin >> current_tax_rate; + cout << "----------------------------------------------\n"; + + // Calculate annual property tax for senior homeowner + total_annual_property_tax = + (((value_of_property * ASSESSMENT_PERCENTAGE) + - 5000) + / 100) + * current_tax_rate; + + // Calculate quarterly tax bill + quarterly_tax_bill = total_annual_property_tax / 4; + + // Display annual property tax and quarterly tax bill. + cout << setprecision(2) << fixed << right; + cout << "----------------------------------------------\n"; + cout << "Value of the property: $" << setw(11) << value_of_property; + cout << "\nAnnual property tax: $" << setw(11) << total_annual_property_tax; + cout << "\nQuarterly tax bill: $" << setw(11) << quarterly_tax_bill; + cout << '\n' << "----------------------------------------------\n"; + cout << endl; + + // Terminate Program. + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/17.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/17.cpp new file mode 100644 index 0000000..ac3c96c --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/17.cpp @@ -0,0 +1,63 @@ +/******************************************************************** +* +* 17. MATH TUTOR +* +* Write a program that can be used as a math tutor for a +* young student. The program should display two random numbers +* to be added, such as +* +* 247 + 129 = ? +* +* The program should then pause while the student works on the +* problem. When the student is ready to check the answer, +* he or she can press a key and the program will display the +* correct solution: +* +* 247 + 129 = 376 +* +* Jesus Hilario Hernandez +* January 17th 2018 +* +********************************************************************/ +#include +#include // For rand and srand functions +#include // For the time function + +using namespace std; + +int main() +{ + int MIN_VALUE = 100, + MAX_VALUE = 1000, + num1, + num2; + + // Get the system time. + unsigned seeds = time(0); + + // Seed the random number generator. + srand(seeds); + + cout << endl; + cout << "------------------------------------------------------\n" << endl; + cout << "This program displays two random numbers to be added.\n" << endl; + + // Generate two random numbers to be added + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + + // Display problem to solve + cout << num1 << " + " << num2 << " = ? \n" << endl; + + // Ask user to press enter to continue + cout << "Press \"ENTER\" to see solution"; + cin.get(); + cout << endl; + + // Display the answer to the problem + cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; + cout << "\n-------------------------------------------------------" << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/18.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/18.cpp new file mode 100644 index 0000000..8c30da6 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/18.cpp @@ -0,0 +1,85 @@ +/******************************************************************** +* +* NEEDS TO BE OVER LOOKED! +* NEEDS TO BE OVER LOOKED! +* NEEDS TO BE OVER LOOKED! +* NEEDS TO BE OVER LOOKED! +* +* 18. Interest Earned +* +* Assuming there are no deposits other than the original +* investment, the balance in a savings account after one +* year may be calculated as +* +* Amount = Principal * (1 + Rate/T)^T +* +* Principal is the balance in the savings account, Rate is +* the interest rate, and T is the number of times the interest +* is compounded during a year (T is 4 if the interest is +* compounded quarterly). +* +* Write a program that asks for the principal, +* the interest rate, and the number of times the interest +* is compounded. It should display a report similar +* to +* +* Interest Rate: 4.25% +* Times Compounded: 12 +* Principal: $ 1000.00 +* Interest: $ 43.34 +* Amount in Savings: $ 1043.34 +* +* Jesus Hilario Hernandez +* January 25th 2017 +* +********************************************************************/ +#include +#include // For pow() function +#include // For formatting + +using namespace std; + +int main() +{ + // Variables. + double Rate, + Principal, + T, + Amount, + power; + + // Ask the user for the + // principal, + // interest rate, + // num of times interest is compounded + cout << endl; + cout << "What is the pricipal balance in the savings account? "; + cin >> Principal; + cout << "What is the interest rate? "; + cin >> Rate; + cout << "What is the number of times the interest is compounded"; + cout << "\nduring a year? "; + cin >> T; + + // Calculate the amount in savings + // Amount = Principal * (1 + Rate/T)^T + Amount = Principal * pow((1 + (((Rate * .01))/T)), T); + + // Display the report: + /******************************************** + * Interest Rate: 4.25% + * Times Compounded: 12 + * Principal: $ 1000.00 + * Interest: $ 43.34 + * Amount in Savings: $ 1043.34 + *********************************************/ + cout << setprecision(2) << fixed << right << endl; + cout << "Interest Rate: " << setw(10) << Rate << endl; + cout << "Times Compounded: " << setw(10) << T << endl; + cout << "Principal: " << setw(10) << Principal << endl; + cout << "Interest: " << setw(10) << Principal * (Rate * .01) << endl; + cout << "Amount in Savings: " << setw(10) << Amount << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/19.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/19.cpp new file mode 100644 index 0000000..883c7e4 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/19.cpp @@ -0,0 +1,73 @@ +/******************************************************************** +* +* 19. MONTHLY PAYMENTS +* +* The monthly payment on a loan may be calculated by the +* following formula: +* Payment = [Rate * (1 + Rate)^N / ((1 + Rate)^N - 1)] * L +* +* Rate is the monthly interest rate, which is the annual interest +* rate divided by 12. (12% annual interest would be 1 percent +* monthly interest.) N is the number of payments, and L is the +* amount of the loan. Write a program that asks for these +* values and displays a report similar to +* +* Loan Amount: $ 10000.00 +* Monthly Interest Rate: 1% +* Number of Payments: 36 +* Monthly Payment: $ 332.14 +* Amount Paid Back: $ 11957.15 +* Interest Paid: $ 1957.15 +* +* Jesus Hilario Hernandez +* January 9th 2017 +* +********************************************************************/ +#include +#include // For pow() function +#include // For formatting + +using namespace std; + +int main() +{ + // Variables + double Rate = 1, // Monthly interest rate = Annual interest rate / 12 + N = 36, // Number of payments + L = 1500, // Amount of the loan + Payment; + + + // Ask the user for Rate, number of paymets, and amount of the loan + cout << endl; + cout << "What is interest rate of the loan? "; + cin >> Rate; + cout << "What is the Amount of the loan? "; + cin >> L; + cout << "Number of payments? "; + cin >> N; + // Calculate the Monthly payment + // Payment = [Rate * (1 + Rate)^N / ((1 + Rate)^N - 1)] * L + Payment = ((Rate * .01) * pow(1 + (Rate * .01), N) / (pow(1 + (Rate * .01), N) - 1)) * L; + + // Display + /************************************************ + * Loan Amount: $ 10000.00 * + * Monthly Interest Rate: 1% * + * Number of Payments: 36 * + * Monthly Payment: $ 332.14 * + * Amount Paid Back: $ 11957.15 * + * Interest Paid: $ 1957.15 * + ************************************************/ + + cout << setprecision(2) << fixed << right << endl; + + cout << "Loan Amount: $" << setw(10) << L << endl; + cout << "Monthly Interest Rate: " << setw(10) << Rate << endl; + cout << "Number of Payments: " << setw(10) << N << endl; + cout << "Monthly Payment: $" << setw(10) << Payment << endl; + cout << "Amount Paid Back: $" << setw(10) << N * Payment << endl; + cout << "Interest Paid: $" << setw(10) << abs(L - (N * Payment)); + cout << endl << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/20.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/20.cpp new file mode 100644 index 0000000..c93d6cf --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/20.cpp @@ -0,0 +1,68 @@ +/******************************************************************** +* +* 20. PIZZA PIE +* +* Joe’s Pizza Palace needs a program to calculate the number of +* slices a pizza of any size can be divided into. The program +* should perform the following steps: +* +* A) Ask the user for the diameter of the pizza in inches. +* B) Calculate the number of slices that may be taken from a +* pizza of that size. +* C) Display a message telling the number of slices. +* +* To calculate the number of slices that may be taken from the +* pizza, you must know the following facts: +* +* • Each slice should have an area of 14.125 inches. +* • To calculate the number of slices, simply divide the +* area of the pizza by 14.125. +* • The area of the pizza is calculated with this formula: +* +* Area = Ï€r^2 +* +* NOTE: Ï€ is the Greek letter pi. 3.14159 can be used as its value. +* The variable r is the radius of the pizza. Divide the diameter +* by 2 to get the radius. +* +* Make sure the output of the program displays the number of +* slices in fixed point notation, rounded to one decimal +* place of precision. Use a named constant for pi. +* +* Jesus Hilario Hernandez +* January 28th 2017 +* +********************************************************************/ +#include +#include // For use of pow() function. +#include // For use of setprecision() function. +using namespace std; + +int main() +{ + const float SLICE_AREA_SIZE = 14.125, + PI = 3.14159; + float d, + r, + Area, + num_of_slices; + + // Ask the user for the diameter of the pizza in inches. + cout << endl; + cout << "What is the diameter of the pizza in inches? "; + cin >> d; + + // Calculate the # of slices that may be taken from a pizza + // of that size + r = d / 2; + Area = PI * pow(r, 2); + num_of_slices = Area / SLICE_AREA_SIZE; + + // Display a message telling the number of slices. + cout << setprecision(1) << fixed; + cout << "Number of slices = " << num_of_slices << endl; + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/21.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/21.cpp new file mode 100644 index 0000000..b9a91ca --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/21.cpp @@ -0,0 +1,61 @@ +/******************************************************************** +* +* 21. How Many Pizzas? +* +* Modify the program you wrote in Programming Challenge 20 +* (Pizza Pi) so that it reports the number of pizzas you need +* to buy for a party if each person attending is expected to eat +* an average of four slices. The program should ask the user for +* the number of people who will be at the party and for the +* diameter of the pizzas to be ordered. It should then calculate +* and display the number of pizzas to purchase. +* +* Jesus Hilario Hernandez +* January 28th 2017 +* +********************************************************************/ +#include +#include // For use of pow() function. +#include // For use of setprecision() function. +using namespace std; + +int main() +{ + const float SLICE_AREA_SIZE = 14.125, + PI = 3.14159; + float d, + r, + Area, + num_of_slices, + slices_needed, + num_of_pizzas; + + int num_of_people; + + // Ask the user for the number of people who will be at the party + cout << "\nWhat is the number of people who will be at the party? "; + cin >> num_of_people; + + // Ask the user for the diameter of the pizza in inches. + cout << "What is the diameter of the pizza in inches? "; + cin >> d; + + // Calculate the # of slices that may be taken from a pizza + // of that size + slices_needed = num_of_people *= 4; // Num Slices needed + r = d / 2; // Calculate Radius + Area = PI * pow(r, 2); // Calculate Area + num_of_slices = Area / SLICE_AREA_SIZE; // Num Slices per pizza + num_of_pizzas = slices_needed /= num_of_slices; // Numb pizzas needed + + // Display a message telling the number of slices. + cout << setprecision(1) << fixed; + cout << "Number of people = " << num_of_people << endl; + cout << "Number of slices needed = " << slices_needed << endl; + cout << "Number of slices per Pizza = " << num_of_slices << endl; + cout << "Number of pizzas to order = " << slices_needed << endl; + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/22.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/22.cpp new file mode 100644 index 0000000..05de4b0 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/22.cpp @@ -0,0 +1,41 @@ +/******************************************************************** +* +* 22. ANGLE CALCULATOR +* +* Write a program that asks the user for an angle, entered in +* radians. The program should then display the sine, cosine, +* and tangent of the angle. (Use the sin, cos, and tan library +* functions to determine these values.) The output should +* be displayed in fixed-point notation, rounded +* to four decimal places of precision. +* +* Jesus Hilario Hernandez +* January 9th 2017 +* +********************************************************************/ +#include +#include +#include + +using namespace std; + +int main() +{ + // Variables + double angle; // User's angle + + // Ask the user for an angle in radians + cout << "\nWhat is an angle in radians? "; + cin >> angle; + + // Display the sine, cosine, and tangent of the angle + cout << "Angle in radians = " << angle << endl; + cout << setprecision(4) << fixed; + cout << "Sine of the angle = " << sin(angle) << endl; + cout << "Cosine of angle = " << cos(angle) << endl; + cout << "Tangent of angle = " << tan(angle) << endl; + cout << endl; + + // Terminate + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/23.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/23.cpp new file mode 100644 index 0000000..6d1ee4a --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/23.cpp @@ -0,0 +1,101 @@ +/******************************************************************** +* +* 23. STOCK TRANSACTION PROGRAM +* +* Last month Joe purchased some stock in Acme Software, Inc. +* Here are the details of the purchase: +* +* • The number of shares that Joe purchased was 1,000. +* • When Joe purchased the stock, he paid $45.50 per share. +* • Joe paid his stockbroker a commission that amounted to 2% +* of the amount he paid for the stock. +* +* Two weeks later Joe sold the stock. Here are the details of +* the sale: +* +* • The number of shares that Joe sold was 1,000. +* • He sold the stock for $56.90 per share. +* • He paid his stockbroker another commission that amounted +* to 2% of the amount he received for the stock. +* +* Write a program that displays the following information: +* • The amount of money Joe paid for the stock. +* • The amount of commission Joe paid his broker when he +* bought the stock. +* • The amount that Joe sold the stock for. +* • The amount of commission Joe paid his broker when he sold +* the stock. +* • Display the amount of profit that Joe made after selling +* his stock and paying the two commissions to his broker. +* (If the amount of profit that your program displays is a +* negative number, then Joe lost money on the transaction.) +* +* Jesus Hilario Hernandez +* January 31 2018 +* +********************************************************************/ +#include +#include // Formatting + +using namespace std; + +int main() +{ + // Variables + const float BROKER_COM_PER = .02, // % paid to broker + PRICE_PAID_PER_SHARE = 45.50, // Price per share when bought + PRICE_SOLD_PER_SHARE = 56.90; // Price per share when sold + + const int NUM_OF_SHARES = 1000; + + float joes_stock_purchase, // Original stock purchase amount + total_com_paid_bought, // Paid broker commission when bought + total_com_paid_sold, // Paid broker commission when sold + amount_stock_sold_for; // Amount stock sold for + + // Explain program + cout << endl; + cout << "****************************************************************" << endl; + cout << endl; + cout << " Last month Joe purchased some stock in Acme Software, Inc." << endl; + cout << " Here are the details of the purchase: " << endl; + cout << " • The number of shares that Joe purchased was 1,000." << endl; + cout << " • When Joe purchased the stock, he paid $45.50 per share." << endl; + cout << " • Joe paid his stockbroker a commission that amounted to 2%" << endl; + cout << " of the amount he paid for the stock." << endl; + cout << endl; + cout << " Two weeks later Joe sold the stock. Here are the details of" << endl; + cout << " the sale:" << endl; + cout << " • The number of shares that Joe sold was 1,000." << endl; + cout << " • He sold the stock for $56.90 per share." << endl; + cout << " • He paid his stockbroker another commission that amounted" << endl; + cout << " to 2% of the amount he received for the stock." << endl; + cout << endl; + cout << "****************************************************************" << endl; + + // Calculate + joes_stock_purchase = NUM_OF_SHARES * PRICE_PAID_PER_SHARE; + total_com_paid_bought = joes_stock_purchase * BROKER_COM_PER; + amount_stock_sold_for = NUM_OF_SHARES * PRICE_SOLD_PER_SHARE; + total_com_paid_sold = amount_stock_sold_for * BROKER_COM_PER; + + // Display information: + cout << setprecision(2) << fixed << endl; // Format, fixed with 2 decimal points + + cout << " Amount paid for the stock: " << joes_stock_purchase << endl; + cout << " Amount commission paid when bought stock: " << total_com_paid_bought << endl; + cout << " Amount Joe sold stock for: " << amount_stock_sold_for << endl; + cout << " Amount commission paid when stock sold: " << total_com_paid_sold << endl; + cout << " Amount of profit Joe made after selling stock and" << endl; + cout << " paying two commissions to broker "; + cout << + (amount_stock_sold_for + - (total_com_paid_bought + total_com_paid_sold)) + - joes_stock_purchase + << '\n' << endl; + cout << "****************************************************************" << endl; + cout << endl; + + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/24.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/24.cpp new file mode 100644 index 0000000..9d30a66 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Programming Challenges/24.cpp @@ -0,0 +1,70 @@ +/******************************************************************** +* +* 24. WORD GAME +* +* Write a program that plays a word game with the user. The +* program should ask the user to enter the following: +* +* • His or her name +* • His or her age +* • The name of a city +* • The name of a college +* • A profession +* • A type of animal +* • A pet’s name +* +* After the user has entered these items, the program should +* display the following story, inserting the user’s input into +* the appropriate locations: +* +* There once was a person named NAME who lived in CITY. At the +* age of AGE, NAME went to college at COLLEGE. NAME graduated +* and went to work as a PROFESSION. Then, NAME adopted +* a(n) ANIMAL named PETNAME. They both lived happily +* ever +* after! +* +* Jesus Hilario Hernandez +* January 9th 2017 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + string username, + city, + college, + profession, + animal, + pet_name; + + int age; + + // ask the user to enter info + cout << endl; + cout << "What is your name? "; + getline(cin, username); + cout << "Your age? "; + cin >> age; + cin.ignore(); + cout << "What city to you live? "; + getline(cin, city); + cout << "What college? "; + getline(cin, college); + cout << "What do you do for a living? "; + getline(cin, profession); + cout << "What type of animal? "; + getline(cin, animal); + cout << "Pet's name? "; + getline(cin, pet_name); + cout << endl; + + // Display user info in a sentence + cout << "There once was a person named " << username << " who lived in " << city << ". At the age of " << age << ", " << username << " went to college at " << college << ". " << username << " graduated and went to work as a " << profession << ". Then, " << username << " adopted a(n) " << animal << " named " << pet_name << ". They both lived happily ever after!\n" << endl; + + // Terminate + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/00.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/00.cpp new file mode 100644 index 0000000..a72ecbc --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/00.cpp @@ -0,0 +1,18 @@ +/******************************************************************** +* +* 00. TITLE +* Problem. +* +* Jesus Hilario Hernandez +* Date 15th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/01.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/01.cpp new file mode 100644 index 0000000..83dc138 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/01.cpp @@ -0,0 +1,39 @@ +/******************************************************************** +* +* 01. Assume that the following variables are defined: +* +* - int age; +* - double pay; +* - char section; +* +* Write a single cin statement that will read input into each +* of these variables. +* +* Jesus Hilario Hernandez +* December 29th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int age; + double pay; + char section; + + cout << endl << endl; + cout << "What is your age? "; + cin >> age; + + cout << "How much do you make? "; + cin >> pay; + + cout << "In what section are you parked? "; + cin >> section; + cout << endl << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/02.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/02.cpp new file mode 100644 index 0000000..0151819 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/02.cpp @@ -0,0 +1,36 @@ +/******************************************************************** +* +* 02. Assume a string object has been defined as follows: +* +* - string description; +* +* A) Write a cin statement that reads in a one-word string. +* B) Write a statement that reads in a string that can contain +* multiple words separated by blanks. +* +* Jesus Hilario Hernandez +* December 29th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + string description; + + cout << endl << endl; + cout << "What is you first name? "; + getline(cin, description); + cout << "You first name is " << description << endl; + + cout << "What is your full name? "; + getline(cin, description); + cout << "You full name is " << description << endl; + cout << endl << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/03.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/03.cpp new file mode 100644 index 0000000..ccecc9c --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/03.cpp @@ -0,0 +1,21 @@ +/******************************************************************** +* +* 03. What header files must be included in the following program? +* +* Jesus Hilario Hernandez +* December 29th 2017 +* +* +********************************************************************/ +#include +// #include + +using namespace std; + +int main() +{ + double amount = 89.7; + cout << showpoint << fixed; + cout << setw(8) << amount << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/04.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/04.cpp new file mode 100644 index 0000000..a79643e --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/04.cpp @@ -0,0 +1,44 @@ +/******************************************************************** +* +* 04. Complete the following table by writing the value of each +* expression in the Value column. +* ---------------------------------------------------------------- +* Expression: Value: +* ---------------------------------------------------------------- +* 28 / 4 - 2 5 +* 6 + 12 * 2 - 8 22 +* 4 + 8 * 2 20 +* 6 + 17 % 3 - 2 6 +* 2 + 22 * (9 - 7) 46 +* (8 + 7) * 2 30 +* (16 + 7) % 2 1 +* 12 / (10 - 6) 3 +* (19 - 3) * (2 + 2) / 4 16 +* ---------------------------------------------------------------- +* +* Jesus Hilario Hernandez +* December 29th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + cout << endl; + + cout << 28 / 4 - 2 << endl; + cout << 6 + 12 * 2 - 8 << endl; + cout << 4 + 8 * 2 << endl; + cout << 6 + 17 % 3 - 2 << endl; + cout << 2 + 22 * (9 - 7) << endl; + cout << (8 + 7) * 2 << endl; + cout << (16 + 7) % 2 << endl; + cout << 12 / (10 - 6) << endl; + cout << (19 - 3) * (2 + 2) / 4 << endl; + + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/05.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/05.cpp new file mode 100644 index 0000000..c97b0e7 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/05.cpp @@ -0,0 +1,53 @@ +/******************************************************************** +* +* 05. Write C++ expressions for the following algebraic +* expressions: +* - a = 12x +* - y = x^4 +* - z = 5x + 14y + 6k +* - g = h + 12 / 4k +* - c = a^3 / b^2 k^4 +* +* Jesus Hilario Hernandez +* December 29th 2017 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables. + int x = 2, + k = 2, + h = 2, + b = 2; + + // Expressions. + int a = 12 * x, + y = pow(x, 4), + z = (5 * x) + (14 * y) + (6 * k), + g = (h + 12) / (4 * k), + c = pow(a, 3) / (pow(b, 2) * pow(k, 4)); + + + // print values to to screen. + cout << endl; + + cout << "a = 12x = " << a << endl; + cout << "y = x^4 = " << y << endl; + cout << "z = 5x + 14y + 6k = " << z << endl; + cout << "g = h + 12 / 4k = " << g << endl; + cout << "c = a^3 / b^2 k^4 = " << c << endl; + + cout << endl; + + + + + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/06.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/06.cpp new file mode 100644 index 0000000..987968f --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/06.cpp @@ -0,0 +1,55 @@ +/******************************************************************** +* +* 06. Assume a program has the following variable definitions: +* +* - int units; +* - float mass; +* - double weight; +* +* and the following statement: +* +* - weight = mass * units; +* +* Which automatic data type conversion will take place? +* +* A) mass is demoted to an int, units remins an int, and the result +* of mass * units is an int. +* B) units is promoted to a float, mass remains a float, and the +* result of mass * units is a float. +* C) units is promoted to a float, mass remains a float, and the +* result of mass * units is a double. <<<<<<<<<<<<<<<< C +* +* Jesus Hilario Hernandez +* December 29th 2017 +* +* +********************************************************************/ +#include +#include +using namespace std; + +int main() +{ + int units = 12; + float mass = 2.0; + double weight = 3.0; + + cout << endl; + cout << typeid(units).name() << endl; + cout << typeid(mass).name() << endl; + cout << typeid(weight).name() << endl; + cout << endl; + + + weight = mass * units; + cout << weight << endl; + + + cout << endl; + cout << typeid(units).name() << endl; + cout << typeid(mass).name() << endl; + cout << typeid(weight).name() << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/07.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/07.cpp new file mode 100644 index 0000000..67447de --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/07.cpp @@ -0,0 +1,36 @@ +/******************************************************************** +* +* 07. ASSUME THE FOLLOWING PROGRAM HAS THE FOLLOWING VARIABLE +* DEFINITIONS: +* +* int a, b = 2; +* float c = 4.2; +* +* AND THE FOLLOWING STATEMENT: +* a = b * c; +* +* WHAT VALUE WILL BE STORED IN a? +* A) 8.4 +* B) 8 <<<<<--- +* C) 0 +* D) None of the above +* +* Jesus Hilario Hernandez +* December 29th 2017 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int a, b = 2; + float c = 4.2; + + a = b * c; + + cout << endl << "a = " << a << endl << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/08.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/08.cpp new file mode 100644 index 0000000..b4088f1 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/08.cpp @@ -0,0 +1,30 @@ +/******************************************************************** +* +* 08. Assume the qty and salesReps are both integers. Use a type +* cast espression to rewrite the following statement so it will +* no longer perform integer division. +* +* unitsEach = qty / salesReps; +* +* Jesus Hilario Hernandez +* January 2nd 2018 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int qty = 89, salesReps = 2; + float unitsEach; + + // Original + unitsEach = qty / salesReps; + cout << "unitsEach (no type cast)= " << unitsEach << endl; + + // Type Casted to a double + unitsEach = static_cast(qty) / salesReps; + cout << "unitsEach (with type cast)= " << unitsEach << endl; + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/09.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/09.cpp new file mode 100644 index 0000000..c1a0a9a --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/09.cpp @@ -0,0 +1,22 @@ +/******************************************************************** +* +* 09. Rewrite the following variable definitions so the variable is +* is a named constant. +* +* int rate; +* +* Jesus Hilario Hernandez +* January 2nd 2018 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + const int rate = 9; + cout << endl << "rate = " << rate << '\n' ``t<< endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/10.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/10.cpp new file mode 100644 index 0000000..1ec0617 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/10.cpp @@ -0,0 +1,53 @@ +/******************************************************************** +* +* 10. Rewrite the following statements with combined assignment +* operators: +* +* x = x + 5; +* total = total + subtotal; +* dist = dist / rep; +* ppl = ppl * period; +* inv = inv - shrinkage; +* num = num % 2; +* +* Jesus Hilario Hernandez +* January 2nd 2018 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x = 2, + total = 2, + subtotal = 2, + dist = 2, + rep = 2, + ppl = 2, + period = 2, + inv = 2, + shrinkage = 2, + num = 2; + + // Original statements rewritten with combined assignment operators + x += 5; // 2 += 5; 7 + total += subtotal; // 2 += 2; 4 + dist /= rep; // 2 /= 2; 1 + ppl *= period; // 2 *= 2; 4 + inv -= shrinkage; // 2 -= 2; 0 + num %= 2; // 2 %= 2; 0 + + cout << endl; + cout << "x += 5: " << x << endl; + cout << "total += subtotal: " << total << endl; + cout << "dist /= rep: " << dist << endl; + cout << "ppl *= period: " << ppl << endl; + cout << "inv -= shrinkage: " << inv << endl; + cout << "num %= 2: " << num << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/11.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/11.cpp new file mode 100644 index 0000000..befc66d --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/11.cpp @@ -0,0 +1,40 @@ +/******************************************************************** +* +* 11. Write a multiple assignment statement that can be used instead +* of the following group of assignment statements: +* +* east = 1; +* west = 1; +* north = 1; +* south = 1; +* +* Jesus Hilario Hernandez +* January 2nd 2018 +* +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int east = 1, + west, + north, + south; + + // Multiple assignemt statments: + east = west = north = south; + + // Print values to screen. + cout << endl; + cout << "west = " << west << endl; + cout << "east = " << east << endl; + cout << "south = " << south << endl; + cout << "north = " << north << endl; + cout << endl; + + // Program termination. + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/12.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/12.cpp new file mode 100644 index 0000000..4a9cc4d --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/12.cpp @@ -0,0 +1,28 @@ +/******************************************************************** +* +* 12. Write a cout statement so that variable divSales is displayed +* in a field of 8 spaces, in fixed point notation, with a +* precision of 2 decimal points. +* +* Jesus Hilario Hernandez +* January 2nd 2018 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + float divSales = 78.90234; + + cout << endl; + cout << setprecision(2) << fixed; + cout << "(" << setw(8) << divSales << ")" << endl; + cout << endl; + + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/13.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/13.cpp new file mode 100644 index 0000000..fc91374 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/13.cpp @@ -0,0 +1,29 @@ +/******************************************************************** +* +* 13. Write a cout statement so the variable totalAge is displayed +* in a field of 12 spaces, in fixed point notation, with a +* precision of 4 decimal places. +* +* Jesus Hilario Hernandez +* January 2nd 2018 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + float totalAge = 56.43498; + + cout << endl; + cout << setprecision(4) << fixed; + cout << "(" << setw(12) << totalAge << ")"<< endl; + cout << endl; + + // Program termination. + return 0; +} diff --git a/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/14.cpp b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/14.cpp new file mode 100644 index 0000000..4986113 --- /dev/null +++ b/Chapter-3-Expressions-and-Interactivity/Review Questions and Exercises/Short Answer/14.cpp @@ -0,0 +1,31 @@ +/******************************************************************** +* +* 14. Write a cout statement so the variable population is +* displayed in a field of 12 spaces, left-justified, with a +* precision of 8 decimal places. The decimal point should +* always be displayed. +* +* Jesus Hilario Hernandez +* January 2nd 2018 +* +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + float population = 78.342098230429; + + // Print to screen: + cout << endl; + cout << setprecision(8) << fixed << left; + cout << "(" << setw(12) << population << ")" << endl; + cout << endl; + + // Program termination. + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.1.cpp b/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.1.cpp new file mode 100644 index 0000000..ecf0137 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.1.cpp @@ -0,0 +1,94 @@ +/******************************************************************** +* +* Checkpoint 4.1 +* +* Assuming x is 5, y is 6, and z is 8, indicate by circling +* the T or F whether each of the following relational +* expressions is true or false: +* +* A) x == 5 T F +* B) 7 <= (x + 2) T F +* C) z < 4 T F +* D) (2 + x) != y T F +* E) z != 4 T F +* F) x >= 9 T F +* G) x <= (y * 2) T F +* +* Jesus Hilario Hernandez +* February 12, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x = 5, + y = 6, + z = 8; + + // Program title + cout << endl; + cout << "Checkpoint 4.1" << endl; + cout << "---------------" << endl; + cout << "Variables: " << endl; + cout << "x = 5," << endl; + cout << "y = 6," << endl; + cout << "z = 8 " << endl; + + // A). x == 5 + cout << "\nA). x == 5 --> "; + if (x == 5) + cout << "True"; + else + cout << " False"; + + // B). 7 <= (x + 2) + cout << "\nB). 7 <= (x + 2) --> "; + if (7 <= (x + 2)) + cout << "True"; + else + cout << " False"; + + // C). z < 4 + cout << "\nC). z < 4 --> "; + if (z < 4) + cout << "True"; + else + cout << " False"; + + // D). (2 + x) != y + cout << "\nD). (2 + x) != y --> "; + if ((2 + x) != y) + cout << "True"; + else + cout << " False"; + + // E). z != 4 + cout << "\nE). z != 4 --> "; + if (z != 4) + cout << "True"; + else + cout << " False"; + + // F). x >= 9 + cout << "\nF). x >= 9 --> "; + if (x >= 9) + cout << "True"; + else + cout << " False"; + + // G). x <= (y * 2) + cout << "\nG). x <= (y * 2) --> "; + if (x <= (y * 2)) + cout << "True"; + else + cout << " False"; + + // Formatting for end line + cout << '\n' << endl; + + // Terminate Program False + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.2.cpp b/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.2.cpp new file mode 100644 index 0000000..f96e0ef --- /dev/null +++ b/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.2.cpp @@ -0,0 +1,66 @@ +/******************************************************************** +* +* Checkpoint 4.2 +* +* Indicate whether the following statements about relational +* expressions are correct or incorrect. +* +* A) x <= y is the same as y > x. +* +* B) x != y is the same as y >= x. +* +* C) x >= y is the same as y <= x. +* +* Jesus Hilario Hernandez +* February 12, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x = 1, y = 1; + + // Program title + cout << endl; + cout << "Checkpoint 4.2" << endl; + cout << "---------------" << endl; + cout << "Variables: " << endl; + cout << "x = 1," << endl; + cout << "y = 1" << endl << endl; + + + // A). x <= y is the same as y > x. + cout << "A). x <= y is the same as y > x. --> "; + if ((x <= y) == (y < x)) + cout << "True"; + else + cout << "False"; + cout << endl; + + // B). x != y is the same as y >= x. + cout << "B). x != y is the same as y >= x. --> "; + if ((x != y) == (y >= x)) + cout << "True"; + else + cout << "False"; + cout << endl; + + // C). x >= y is the same as y <= x. + cout << "C). x >= y is the same as y <= x. --> "; + if ((x >= y) == (y <= x)) + cout << "True"; + else + cout << "False"; + cout << endl; + + + // Formatting + cout << endl; + + + // Terminate Program False + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.3.cpp b/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.3.cpp new file mode 100644 index 0000000..70738ba --- /dev/null +++ b/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.3.cpp @@ -0,0 +1,103 @@ +/******************************************************************** +* +* Checkpoint 4.3 +* +* Answer the following questions with a yes or no. +* +* A) If it is true that x > y and it is also true that x < z, +* does that mean y < z is true? +* +* B) If it is true that x >= y and it is also true that z == x, +* does that mean that z == y is true? +* +* C) If it is true that x != y and it is also true that x != z, +* does that mean that z != y is true? +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x = 2, y = 1, z = 3; + + // Program title + cout << endl; + cout << "Checkpoint 4.3" << endl; + cout << "---------------" << endl; + + + + // A) If it is true that x > y and it is also true that x < z, + // does that mean y < z is true? + + // Set variables + x = 2, y = 1, z = 3; + + // Display + cout << "Variables: " << endl; + cout << "x = 2" << endl; + cout << "y = 1" << endl; + cout << "z = 3 \n" << endl; + + cout << "A) If it is true that x > y and it is also true that x < z,\n"; + cout << " does that mean that y < z is true? --> "; + if ((x > y) && (x < z) && (y < z)) + cout << "True"; + else + cout << "False"; + cout << '\n' << endl; + + // B) If it is true that x >= y and it is also true that z == x, + // does that mean that z == y is true? + + // Set variables + x = 2, y = 1, z = 2; + + // Display + cout << "Variables: " << endl; + cout << "x = 2" << endl; + cout << "y = 1" << endl; + cout << "z = 2 \n" << endl; + + cout << "B) If it is true that x >= y and it is also true that z == x,\n"; + cout << " does that mean that z == y is true? --> "; + if ((x >= y) && (z == x) && (z == y)) + cout << "True"; + else + cout << "False"; + cout << '\n' << endl; + + // C) If it is true that x != y and it is also true that x != z, + // does that mean that z != y is true? + + // Set variables + x = 2, y = 1, z = 1; + + // Display + cout << "Variables: " << endl; + cout << "x = 2" << endl; + cout << "y = 1" << endl; + cout << "z = 1 \n" << endl; + + cout << "C) If it is true that x != y and it is also true that x != z,\n"; + cout << " does that mean that z != y is true? --> "; + if ((x != y) && (x != z) && (z != y)) + cout << "True"; + else + cout << "False"; + cout << endl; + + + // Formatting + cout << "---------------" << endl; + cout << endl; + + + // Terminate Program False + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.4.cpp b/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.4.cpp new file mode 100644 index 0000000..4969060 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.1 Relational Operators/Checkpoint/4.4.cpp @@ -0,0 +1,27 @@ +/******************************************************************** +* +* Checkpoint 4.4 +* +* What will the following program display? +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int a = 0, b = 2, x = 4, y = 0; + + // Display + cout << (a == b) << endl; // 0 + cout << (a != y) << endl; // 0 + cout << (b <= x) << endl; // 1 + cout << (y > a) << endl; // 0 + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.1 Relational Operators/Examples/4-1.cpp b/Chapter-4-Making-Decisions/4.1 Relational Operators/Examples/4-1.cpp new file mode 100644 index 0000000..2a5130e --- /dev/null +++ b/Chapter-4-Making-Decisions/4.1 Relational Operators/Examples/4-1.cpp @@ -0,0 +1,22 @@ +//********************************************** +// This Program displays the values of true and +// false states. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 15, 2016 +//********************************************** +#include +using namespace std; + +int main() +{ + bool trueValue, falseValue; + int x = 5, y = 10; + + trueValue = x < y; + falseValue = y == x; + + cout << "True is " << trueValue << endl; + cout << "False is " << falseValue << endl; + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.10 Menus/Examples/4-18.cpp b/Chapter-4-Making-Decisions/4.10 Menus/Examples/4-18.cpp new file mode 100644 index 0000000..f4d9a6c --- /dev/null +++ b/Chapter-4-Making-Decisions/4.10 Menus/Examples/4-18.cpp @@ -0,0 +1,70 @@ +//********************************************************** +// This program displays a menu and asks the user to make a +// selection. An if/else if statement determines which item +// the user has chosen. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//********************************************************** +#include +#include +using namespace std; + +int main() +{ + int choice; // To hold a meny choice + int months; // To hold the number of months + double charges; // To hold the monthly charges + + // Constants for membership rates + const double ADULT = 40.0, + SENIOR = 30.0, + CHILD = 20.0; + + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Display the menu and get a choice. + cout << "\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; + cin >> choice; + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Respond to the user's menu selection. + if (choice == ADULT_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * ADULT; + cout << "The total charges are $" << charges << endl; + } + else if (choice == CHILD_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * CHILD; + cout << "The total charges are $" << charges << endl; + } + else if (choice == SENIOR_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * SENIOR; + cout << "The total charges are $" << charges << endl; + } + else + { + cout << "The valid choices are 1 through 4. Run the\n" + << "program again and select one of those.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.11 Focus On Software Engineering: Validating User Input/Examples/4-19.cpp b/Chapter-4-Making-Decisions/4.11 Focus On Software Engineering: Validating User Input/Examples/4-19.cpp new file mode 100644 index 0000000..f401d63 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.11 Focus On Software Engineering: Validating User Input/Examples/4-19.cpp @@ -0,0 +1,61 @@ +//******************************************************* +// This test scoring program does not accept test scores +// that are less than 0 or greater than 100. +// +// By: Jesus Hilari Hernandez +// Last Updated: December 20, 2016 +//******************************************************* +#include +using namespace std; + +int main() +{ + // Constatns for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60, + MIN_SCORE = 0, // Minimum valid score + MAX_SCORE = 100; // Maximum valid score + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell you the letter grade you earned: "; + cin >> testScore; + + // Validate the input and determine the grade. + if (testScore >= MIN_SCORE && testScore <= MAX_SCORE) + { + // Determine the letter grade. + if (testScore >= A_SCORE) + { + cout << "Your grade is A.\n"; + } + else if (testScore >= B_SCORE) + { + cout << "Your grade is B.\n"; + } + else if (testScore >= C_SCORE) + { + cout << "Your grade is C.\n"; + } + else if (testScore >= D_SCORE) + { + cout << "Your grade is D.\n"; + } + else + { + cout << "Your grade is F.\n"; + } + } + else // trailing else for main if + { + // An invalid score was entered. + cout << "That is an invalid score. Run the program\n" + << "again and enter a value in the range of\n" + << MIN_SCORE << " through " << MAX_SCORE << ". \n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/0.00.cpp b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/0.00.cpp new file mode 100644 index 0000000..8b5bc9d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/0.00.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/4.22.cpp b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/4.22.cpp new file mode 100644 index 0000000..6723a9f --- /dev/null +++ b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/4.22.cpp @@ -0,0 +1,52 @@ +/******************************************************************** +* +* Checkpoint 4.22 +* +* Indicate whether each of the following relational expressions +* is true or false. Refer to the ASCII table in Appendix B if +* necessary. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + cout << endl; + + // A). 'a' == 97, 'z' == 122 + cout << "'a' < 'z' --> " << ('a' < 'z') << endl; // 1 + + // B). 'a' == 97, 'A' == 65 + cout << "'a' == 'A' --> " << ('a' == 'A') << endl; // 0 + + // C). 5 == 53, 7 == 55 + cout << "'5' < '7' --> " << ('5' < '7') << endl; // 1 + + // D). 'a' == 97, 'A' == 65 + cout << "'a' < 'A' --> " << ('a' < 'A') << endl; // 0 + + // E). '1' == 49, 1 == 1 + cout << "'1' == 1 --> " << ('1' == 1) << endl; // 0 + + // F). '1' == 49, 49 == 49 + cout << "'1' == 49 --> " << ('1' == 49) << endl; // 1 + + + cout << endl; + + // Output: + + // 'a' < 'z' --> 1 + // 'a' == 'A' --> 0 + // '5' < '7' --> 1 + // 'a' < 'A' --> 0 + // '1' == 1 --> 0 + // '1' == 49 --> 1 + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/4.23.cpp b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/4.23.cpp new file mode 100644 index 0000000..f163a16 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Checkpoint/4.23.cpp @@ -0,0 +1,50 @@ +/******************************************************************** +* +* Checkpoint 4.23 +* +* Indicate whether each of the following relational expressions is +* true or false. Refer to the ASCII table in Appendix B. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + string Bill = "Bill", + BILL = "BILL", + Bob = "Bob", + Mary = "Mary", + MaryEllen = "MaryEllen", + Mary_Ellen = "Mary Ellen", + num_189 = "189", + num_23 = "23"; + + // The problem + cout << endl; + cout << "\"Bill\" == \"BILL\" --> " << (Bill == BILL) << endl; + cout << "\"Bill\" < \"BIll\" --> " << (Bill < BILL) << endl; + cout << "\"Bill\" < \"Bob\" --> " << (Bill < Bob) << endl; + cout << "\"189\" > \"23\" --> " << (num_189 > num_23) << endl; + cout << "\"189\" > \"Bill\" --> " << (num_189 > Bill) << endl; + cout << "\"Mary\" < \"MaryEllen\" --> " << (Mary < MaryEllen) << endl; + cout << "\"MaryEllen\" < \"Mary Ellen\" --> " << (MaryEllen < Mary_Ellen) << endl; + cout << endl; + + // Output: + + // "Bill" == "BILL" --> 0 + // "Bill" < "BIll" --> 0 + // "Bill" < "Bob" --> 1 + // "189" > "23" --> 0 + // "189" > "Bill" --> 0 + // "Mary" < "MaryEllen" --> 1 + // "MaryEllen" < "Mary Ellen" --> 0 + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Examples/4-20.cpp b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Examples/4-20.cpp new file mode 100644 index 0000000..1f9944b --- /dev/null +++ b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Examples/4-20.cpp @@ -0,0 +1,40 @@ +//************************************************ +// This prgram demonstrates how characters can be +// compared with the relational operators. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 20, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 195-196 +//************************************************ +#include +using namespace std; + +int main() +{ + char ch; + + // Get a character from the user. + cout << "Enter a digit or a letter: "; + ch = cin.get(); + + // Determine what the user entered. + if (ch >= '0' && ch <= '9') + { + cout << "You entered a digit.\n"; + } + else if (ch >= 'A' && ch <= 'Z') + { + cout << "You entered an uppercase letter.\n"; + } + else if (ch >= 'a' && ch <= 'z') + { + cout << "You entered a lowercase letter.\n"; + } + else + { + cout << "That is not a digit or a letter.\n"; + } + + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Examples/4-21.cpp b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Examples/4-21.cpp new file mode 100644 index 0000000..6713f56 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.12 Comparing Characters and Strings/Examples/4-21.cpp @@ -0,0 +1,47 @@ +//************************************************************* +// This program uses relational operators to compare a Starting +// entered by the user with valid stereo part numbers. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 197-198 +//************************************************************* +#include +#include +#include +using namespace std; + +int main() +{ + const double PRICE_A = 249.0, + PRICE_B = 299.0; + + string partNum; // Holds a stereo part numbers + + // Display available parts and get the user's selection + cout << "The stereo part numbers are:\n" + << "Boom Box: part number S-29A \n" + << "Shelf Model: part number S-29B \n" + << "Enter the part number of the stereo you\n" + << "wish to purchase: "; + cin >> partNum; + + // Set the numeric output formatting + cout << fixed << showpoint << setprecision(2); + + // Determine and display the correct price + if (partNum == "S-29A") + { + cout << "The price is $" << PRICE_A << endl; + } + else if (partNum == "S-29B") + { + cout << "The price is $" << PRICE_B << endl; + } + else + { + cout << partNum << " is not a valid part number.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/0.00.cpp b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/0.00.cpp new file mode 100644 index 0000000..8b5bc9d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/0.00.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.24.cpp b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.24.cpp new file mode 100644 index 0000000..7d14b1b --- /dev/null +++ b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.24.cpp @@ -0,0 +1,89 @@ +/******************************************************************** +* +* Checkpoint 4.24 +* +* Rewrite the following if/else statements as conditional +* expressions: +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // A). + // Variables + int x = 29, + y = 83, + z = 0; + + // if/else statement + if (x > y) + z = 1; + else + z = 20; + + // Conditional Expression + x > y ? z = 1 : z = 20; + + + + + + // B). + // Variables + int temp = 90, + base = 50, + population; + + // if/else statement + if (temp > 45) + population = base * 10; + else + population = base * 2; + + // Conditional Expression + temp > 45 ? population = base * 10 : population == base * 2; + + + + + + // C). + // Variables + int hours = 54, + wages = 350; + + // if/else statement + if (hours > 40) + wages *= 1.5; + else + wages *= 1; + + // Conditional Expression + hours > 40 ? wages *= 1.5 : wages *= 1; + + + + + + // D). + // Variables + int result = 9; + + // if/else statement + if (result >= 0) + cout << "The result is positive.\n"; + else + cout << "The result is negative.\n"; + + // Conditional Expression + cout << "The result is " << (result >= 0 ? "positive." : "negative.") << endl; + // or + result >= 0 ? cout << "The result is positive.\n" : cout << "the result is negative.\n"; + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.25.cpp b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.25.cpp new file mode 100644 index 0000000..956070f --- /dev/null +++ b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.25.cpp @@ -0,0 +1,65 @@ +/******************************************************************** +* +* Checkpoint 4.25 +* +* The following statements use conditional expressons. Rewrite +* Rewrite each with an if/else statement. +* +* A). j = k > 90 ? 57 : 12; +* B). factor = x >= 10 ? y * 22 : y * 35; +* C). total += count == 1 ? sales : count * sales; +* D). cout << (((num % 2) == 0) ? "Even\n" : "Odd\n"); +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int j = 9, + k = 90, + x = 78, + y = 2, + factor = 1, + total = 4, + count = 0, + sales = 5, + num = 2; + + + // A). j = k > 90 ? 57 : 12; + if (k > 90) + j = 57; + else + j = 12; + + + // B). factor = x >= 10 ? y * 22 : y * 35; + if (x >= 10) + factor = y * 22; + else + factor = y * 35; + + + // C). total += count == 1 ? sales : count * sales; + if (count == 1) + total += sales; + else + total += count * sales; + + + // D). cout << (((num % 2) == 0) ? "Even\n" : "Odd\n"); + if ((num % 2) == 0) + cout << "Even\n"; + else + cout << "Odd\n"; + + // Output: + // Even + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.26.cpp b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.26.cpp new file mode 100644 index 0000000..13f5359 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.26.cpp @@ -0,0 +1,26 @@ +/******************************************************************** +* +* Checkpoint 4.26 +* +* What will the following program display? +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + const int UPPER = 8, LOWER = 2; + int num1, num2, num3 = 12, num4 = 3; + + num1 = num3 < num4 ? UPPER : LOWER; // 2 + num2 = num4 > UPPER ? num3 : LOWER; // 2 + cout << num1 << " " << num2 << endl; + // output: + // 2 2 + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Examples/4-22.cpp b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Examples/4-22.cpp new file mode 100644 index 0000000..792dec1 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.13 The Conditional Operator/Examples/4-22.cpp @@ -0,0 +1,34 @@ +//************************************************************* +// This program calculates a consultant's charges at $50 +// per hour, for a minimum of 5 hours. The ?: operator +// adjusts hours to 5 if less than 5 hours were worked. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 200-201 +//************************************************************* +#include +#include +using namespace std; + +int main() +{ + const double PAY_RATE = 50.0; // Hourly pay rate + const int MIN_HOURS = 5; // Minimum billable hours + double hours, // hours worked + charges; // Total sharges + + // Get the hours worked. + cout << "How many hours were worked? "; + cin >> hours; + + // Determine the hours to charge for. + hours = hours < MIN_HOURS ? MIN_HOURS : hours; + + // Calculate and display the charges. + charges = PAY_RATE * hours; + cout << fixed << showpoint << setprecision(2) + << "The charges are $" << charges << endl; + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/0.00.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/0.00.cpp new file mode 100644 index 0000000..8b5bc9d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/0.00.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.27.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.27.cpp new file mode 100644 index 0000000..dbfa615 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.27.cpp @@ -0,0 +1,30 @@ +/******************************************************************** +* +* Checkpoint 4.27 +* +* Explain why you cannot convert the following if/else if +* statement into a switch statement. +* +* Answer: A case statement cannot contain a relational +* expression/boolean expression. It must be a +* constant expression. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + if (temp == 100) + x = 0; + else if (population > 1000) + x = 1; + else if (rate < .1) + x = -1; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.28.cpp/4.28.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.28.cpp/4.28.cpp new file mode 100644 index 0000000..acdb98c --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.28.cpp/4.28.cpp @@ -0,0 +1,36 @@ +/******************************************************************** +* +* Checkpoint 4.28 +* +* What is wrong with the following switch statement? +* +* Answer: Each case statement contains a relational expression/ +* boolean expression. Refer to 4.27.png in file to see +* compiler error. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int temp = 90; + + // Switch statement + switch (temp) + { + case temp < 0 : cout << "Temp is negative.\n"; + break; + case temp == 0: cout << "Temp is zero.\n"; + break; + case temp > 0 : cout << "Temp is positive.\n"; + break; + } + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.28.cpp/4.28.png b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.28.cpp/4.28.png new file mode 100644 index 0000000..574683e Binary files /dev/null and b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.28.cpp/4.28.png differ diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.29.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.29.cpp new file mode 100644 index 0000000..7d6a381 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.29.cpp @@ -0,0 +1,32 @@ +/******************************************************************** +* +* Checkpoint 4.29 +* +* What will the following program display? +* +* Answer: The program will display "That is serious." +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int funny = 7, serious = 15; + + funny = serious * 2; + switch (funny) + { + case 0 : cout << "That is funny.\n"; + break; + case 30: cout << "That is serious.\n"; // This will display + break; + case 32: cout << "That is seriously funny.\n"; + break; + default: cout << funny << endl; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.30.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.30.cpp new file mode 100644 index 0000000..6f9b98b --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.30.cpp @@ -0,0 +1,49 @@ +/******************************************************************** +* +* Checkpoint 4.30 +* +* Complete the following program skeleton by writing a switch +* statement that displays "one" if the user has entered 1, "two" +* if the user entered 2, and "three" if the user has entered 3. +* If a number other than 1, 2, or 3 is entered, the program +* should display an error message. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int userNum; + cout << "Enter one of the numbers 1, 2, or 3: "; + cin >> userNum; + + // + // Write the switch statement here. vvvv + // Write the switch statement here. vvvv + // Write the switch statement here. vvvv + switch (userNum) + { + case 1: + cout << "one" << endl; + break; + case 2: + cout << "two" << endl; + break; + case 3: + cout << "three" << endl; + break; + default: + cout << "Error" << endl; + } + // Write the switch statement here. ^^^^ + // Write the switch statement here. ^^^^ + // Write the switch statement here. ^^^^ + // + + // Terminatre program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.31.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.31.cpp new file mode 100644 index 0000000..b4fea47 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Checkpoint/4.31.cpp @@ -0,0 +1,67 @@ +/******************************************************************** +* +* Checkpoint 4.31 +* +* Rewrite the following program. Use a switch statement instead +* of the if/else if statement. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Original program with if/else if statement + int selection; + cout << "Which formula do you want to see?\n\n"; + cout << "1. Area of a circle\n"; + cout << "2. Area of a rectangle\n"; + cout << "3. Area of a cylinder\n"; + cout << "4. None of them!\n"; + cin >> selection; + if (selection == 1) + cout << "Pi times radius squared\n"; + else if (selection == 2) + cout << "Length times width\n"; + else if (selection == 3) + cout << "Pi times radius squared times height\n"; + else if (selection == 4) + cout << "Well okay then, good bye!\n"; + else + cout << "Not good with number, eh?\n"; + + // Line break; + cout << endl; + + // Updated program with switch statement + int selection2; + cout << "Which formula do you want to see?\n\n"; + cout << "1. Area of a circle\n"; + cout << "2. Area of a rectangle\n"; + cout << "3. Area of a cylinder\n"; + cout << "4. None of them!\n"; + cin >> selection2; + switch (selection2) + { + case 1: + cout << "Pi times radius squared\n"; + break; + case 2: + cout << "Length times width\n"; + break; + case 3: + cout << "Pi times radius squared times height\n"; + break; + case 4: + cout << "Well okay then, good bye!\n"; + break; + default: + cout << "Not good with numbers, eh?\n"; + } + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-23.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-23.cpp new file mode 100644 index 0000000..cbe3a10 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-23.cpp @@ -0,0 +1,30 @@ +//*************************************************************** +// This switch statement in this program tells the user something +// he or she already knows: the data just entered! +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 203-204 +//*************************************************************** +#include +using namespace std; + +int main() +{ + char choice; + + cout << "Enter A, B, or C: "; + cin >> choice; + switch (choice) + { + case 'A': cout << "You entered A.\n"; + break; + case 'B': cout << "You entered B.\n"; + break; + case 'C': cout << "You entered C.\n"; + break; + default: cout << "You did not enter A, B, or C!\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-24.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-24.cpp new file mode 100644 index 0000000..6358b5a --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-24.cpp @@ -0,0 +1,29 @@ +//*************************************************************** +// The switch statement in this program tells the user something +// he or she already knows: the data just entered! +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 204-205 +//*************************************************************** +#include +using namespace std; + +int main() +{ + char choice; + + cout << "Enter A, B, or C: "; + cin >> choice; + // The following switch is + // missing its break statements! + switch (choice) + { + case 'A': cout << "You entered A.\n"; + case 'B': cout << "You entered B.\n"; + case 'C': cout << "You entered C.\n"; + default: cout << "You did not enter A, B, or C!\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-25.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-25.cpp new file mode 100644 index 0000000..23c2887 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-25.cpp @@ -0,0 +1,34 @@ +//*************************************************************** +// This program is carefully constructed to use the "fall through" +// feature of the switch statement. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 205-206 +//*************************************************************** +#include +using namespace std; + +int main() +{ + int modelNum; // Model numbers + + // Get a model number from the user. + cout << "Our TVs come in three models:\n"; + cout << "The 100, 200, and 300. Which do you want? "; + cin >> modelNum; + + // Display the model's features. + cout << "That model has the following features:\n"; + switch (modelNum) + { + case 100: cout << "\tPicture-in-a-picture.\n"; + case 200: cout << "\tStereo sound.\n"; + case 300: cout << "\tRemote control.\n"; + break; + default: cout << "You can only choose the 100,"; + cout << "200, or 300.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-26.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-26.cpp new file mode 100644 index 0000000..301098a --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-26.cpp @@ -0,0 +1,38 @@ +//**************************************************************** +// The switch statement in this program uses the "fall through" +// feature to catch both uppercase and lowercase letters entered +// by the user. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 206-207 +//**************************************************************** +#include +using namespace std; + +int main() +{ + char feedGrade; + + // Get the desired grade of feed. + cout << "Our pet food is available in three grades:\n"; + cout << "A, B, or C. Which do you want pricing for? "; + cin >> feedGrade; + + // Display the price. + switch (feedGrade) + { + case 'a': + case 'A': cout << "30 cents per pound.\n"; + break; + case 'b': + case 'B': cout << "20 cents per pound.\n"; + break; + case 'c': + case 'C': cout << "15 cents per pound.\n"; + break; + default : cout << "That is an invalid choice.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-27.cpp b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-27.cpp new file mode 100644 index 0000000..ccd6530 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.14 The switch Statement/Examples/4-27.cpp @@ -0,0 +1,72 @@ +//****************************************************** +// This program uses a switch statement to Determine +// the item selected from a menu. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 208-209 +//****************************************************** +#include +#include +using namespace std; + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold the number of months + double charges; // To hold the monthly charges + + // Constants for membership rates + const double ADULT = 40.0, + CHILD = 20.0, + SENIOR = 30.0; + + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Display the menu and get a choice. + cout << "\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; + cin >> choice; + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Respond to the user's menu selection. + switch (choice) + { + case ADULT_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * ADULT; + cout << "The total charges are $" << charges << endl; + break; + case CHILD_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * CHILD; + cout << "The total charges are $" << charges << endl; + break; + case SENIOR_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * SENIOR; + cout << "The total charges are $" << charges << endl; + break; + case QUIT_CHOICE: + cout << "Program ending.\n"; + break; + default: + cout << "The valid choices are 1 through 4. Run the\n" + << "program again and select on of those.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Checkpoint/0.00.cpp b/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Checkpoint/0.00.cpp new file mode 100644 index 0000000..8b5bc9d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Checkpoint/0.00.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-28.cpp b/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-28.cpp new file mode 100644 index 0000000..ab63e98 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-28.cpp @@ -0,0 +1,42 @@ +//************************************************************* +// This program demonstrates late variable definition +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 211 +//************************************************************* +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + // Get the annual income. + cout << "What is your annual income? "; + double income; // Variable definition + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + int years; // Variable definition + cin >> years; + + // Determine the user's loan qualifications. + if (income >= MIN_INCOME || years > MIN_YEARS) + { + cout << "You qualify.\n"; + } + else + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << " years.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-29.cpp b/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-29.cpp new file mode 100644 index 0000000..b665314 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-29.cpp @@ -0,0 +1,48 @@ +//**************************************************************** +// This program demonstrates a variable defined in an inner block. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 212-213 +//**************************************************************** +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + // Get the annual income. + cout << "What is your annual income? "; + double income; // Variable definition + cin >> income; + + if (income >= MIN_INCOME) + { + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + int years; // Variable definition + cin >> years; + + if (years > MIN_YEARS) + { + cout << "You qualify.\n"; + } + else + { + cout << "You must have been employed for\n" + << "more than " << MIN_YEARS + << " years to qualify.\n"; + } + } + else + { + cout << "You must earn at least $" << MIN_INCOME + << " to qualify.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-30.cpp b/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-30.cpp new file mode 100644 index 0000000..79052fd --- /dev/null +++ b/Chapter-4-Making-Decisions/4.15 More About Blocks and Variables Scope/Examples/4-30.cpp @@ -0,0 +1,29 @@ +//********************************************************* +// This program uses two variables with the name number. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 21, 2016 +// Used from : Gaddis, "Starting Out With C++", +// 8th Edition, Pg 213 +//********************************************************* +#include +using namespace std; + +int main() +{ + // Define a variable named number. + int number; + + cout << "Enter a number greater that 0: "; + cin >> number; + if (number > 0) + { + int number; // Another variable named number. + cout << "Now enter another number: "; + cin >> number; + cout << "The second number you entered was " + << number << endl; + } + cout << "Your first number was " << number << endl; + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.5.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.5.cpp new file mode 100644 index 0000000..d7bcf67 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.5.cpp @@ -0,0 +1,32 @@ +/******************************************************************** +* +* Checkpoint 4.5 +* +* Write an if statement that performs the following logic: if +* the variables x is equal to 20, then assign 0 to the +* variable y. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x = 20, y = 87; + + // Solution + if (x == 20) + y = 0; + + // Display solution + cout << endl; + cout << "if x = " << x << endl; + cout << "then y = " << y << endl << endl; + + // Terminate Program False + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.6.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.6.cpp new file mode 100644 index 0000000..71b39aa --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.6.cpp @@ -0,0 +1,33 @@ +/******************************************************************** +* +* Checkpoint 4.6 +* +* Write an if statement that performs the following logic: if +* the variable price is greater than 500, then assign 0.2 to +* the variable discountRate. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int price = 2000; + float discountRate; + + // Solution + if (price > 500) + discountRate = 0.2; + + // Display solution + cout << endl; + cout << "if price is greater than 500 (price = " << price << ")\n"; + cout << "then discoutRate = " << discountRate << endl << endl; + + // Terminate Program False + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.7.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.7.cpp new file mode 100644 index 0000000..6ae355b --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.7.cpp @@ -0,0 +1,43 @@ +/******************************************************************** +* +* Checkpoint 4.7 +* +* Write an if statement that multiplies payRate by 1.5 if hours +* is greater that 40. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + float payRate = 18.25, + hours = 45; + + cout << endl; + cout << "--------------------------------------" << endl; + cout << "Variables: " << endl; + cout << "hours = " << hours << endl; + cout << "payRate = " << payRate << endl; + cout << "--------------------------------------" << endl; + cout << "--------------------------------------" << endl; + cout << "if hours is greater than 40\n"; + cout << "then multiply payRate by 1.5" << endl; + cout << "payRate = "; + + // Solution + if (hours > 40) + payRate *= 1.5; + + // Display solution + cout << payRate << endl; + cout << "--------------------------------------" << endl; + cout << endl; + + // Terminate Program False + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.8.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.8.cpp new file mode 100644 index 0000000..f997f38 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.8.cpp @@ -0,0 +1,38 @@ +/******************************************************************** +* +* Checkpoint 4.8 +* +* TRUE or FALSE: Both of the following if statements perform the +* same operation. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int sales; + float commissionRate; + + // T/F Problem + if (sales > 10000) + commissionRate = 0.15; + + cout << "\ncommissionRate = " << commissionRate; + + if (sales > 10000) commissionRate = 0.15; + + cout << "\ncommissionRate = " << commissionRate << endl; + cout << endl; + + // TRUE + // TRUE + // TRUE + + // Terminate Program False + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.9.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.9.cpp new file mode 100644 index 0000000..d849caa --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.9.cpp @@ -0,0 +1,41 @@ +/******************************************************************** +* +* Checkpoint 4.9 +* +* TRUE or FALSE: Both of the following if statements perform +* the same operation. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int calls = 20; + float rate = 8.25; + + // T/F Problem + if (calls == 20) + rate *= 0.5; + + cout << "\nrate = " << rate; + + if ((calls = 20)) + rate *= 0.5; + + cout << "\nrate = " << rate << endl; + cout << endl; + + // FALSE + // FALSE + // FALSE + // added parenthesis to line 27 + // see 4.9.png in checkpoint file + + // Terminate Program False + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.9.png b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.9.png new file mode 100644 index 0000000..75601fd Binary files /dev/null and b/Chapter-4-Making-Decisions/4.2 The if Statement/Checkpoint/4.9.png differ diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-2.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-2.cpp new file mode 100644 index 0000000..7e4e7a6 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-2.cpp @@ -0,0 +1,42 @@ +//***************************************** +// This program averages three test scores +// +// By: Jesus Hilario Hernandez +// Last Updated: December 15, 2016 +//****************************************** +#include +#include +using namespace std; + +int main() +{ + const int HIGH_SCORE = 95; // A high score is 95 of greater + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average scores + + // Get the three test scores. + cout << "Enter 3 test scores and I will average the: "; + // Error Check + while (!(cin >> score1 >> score2 >> score3)) + { + // Explain Error + cout << "ERROR: three numbers must be entered: "; + // Clear previous input + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // If the average is a high score, congratulat the user. + if (average > HIGH_SCORE) + { + cout << "Congratulations! That's a high score!\n"; + } + + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-3.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-3.cpp new file mode 100644 index 0000000..4504773 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-3.cpp @@ -0,0 +1,21 @@ +//****************************************************** +// This program demonstrates how a misplaced semicolon +// prematurely terminates an if statement. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 15, 2016 +//****************************************************** +#include +using namespace std; + +int main() +{ + int x = 0, y = 10; + + cout << "x is " << x << " and y is " << y << endl; + if (x > y); //Error! Misplaced semicolon + { + cout << "x is greater the y\n"; // This is always executed. + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-4.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-4.cpp new file mode 100644 index 0000000..61fa636 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-4.cpp @@ -0,0 +1,26 @@ +//*********************************************************** +// This program demonstrates how floating-point +// round-off errors can make equality operations unreliable. +// +// By: JEsus Hilario Hernandez +// Last Updated: December 15, 2016 +//*********************************************************** +#include +using namespace std; + +int main() +{ + double a = 1.5; // a is 1.5 + double b = 1.5; // b is 1.5 + + a += 0.0000000000000001; // Add a little to a. + if (a == b) + { + cout << "Both a and b are the same.\n"; + } + else + { + cout << "a and b are not the same.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-5.cpp b/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-5.cpp new file mode 100644 index 0000000..b650853 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.2 The if Statement/Examples/4-5.cpp @@ -0,0 +1,42 @@ +//******************************************************* +// This program averages 3 test scores. The if statement +// uses the = operator, but the == operator was intended. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 15, 2016 +//******************************************************* +#include +#include +using namespace std; + +int main() +{ + int score1, score2, score3; // To hold three test scores + double average; // To hold the average scores + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + // Error Check + while (!(cin >> score1 >> score2 >> score3)) + { + // Explain the Error + cout << "ERROR: Three numbers must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // Our intention is to congratulate the user + // for having a perfect score. But, this doesn't work. + if (average = 100) // WRONG! This is an assignment! + { + cout << "Congratulations! That's a perfect score!\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/00.cpp b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/00.cpp new file mode 100644 index 0000000..ac21245 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/00.cpp @@ -0,0 +1,26 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/4.10.cpp b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/4.10.cpp new file mode 100644 index 0000000..58b855a --- /dev/null +++ b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/4.10.cpp @@ -0,0 +1,41 @@ +/******************************************************************** +* +* Checkpoint 4.10 +* +* Write an if statement that performs the following logic: if the +* variable sales is greater then 50,000, then assign 0.25 to the +* commissionRate variable, and assign 250 to the bonus variable. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + double sales = 340000, + commissionRate, + bonus; + + // The if statement + if (sales > 50000) + { + commissionRate = 0.25; + bonus = 250; + } + + // Disply + cout << endl; + cout << "sales = $" << setw(8) << sales << endl; + cout << "commissionRate = $" << setw(8) << commissionRate << endl; + cout << "bonus = $" << setw(8) << bonus << endl; + cout << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/4.11.cpp b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/4.11.cpp new file mode 100644 index 0000000..2d8fddc --- /dev/null +++ b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Checkpoint/4.11.cpp @@ -0,0 +1,41 @@ +/******************************************************************** +* +* Checkpoint 4.10 +* +* The following code segment is syntactically correct, but it +* appears to contain a logic error. Can you find the error? +* +* // Answer: missing curly braces. See updated answer @ Line 30 +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + float interestRate = .87, + balance = 78.89; + + // The if statement + + // (ORIGINAL) + // if (interestRate > .07) + // cout << "This account earns a $10 bonus.\n"; + // balance += 10.0; + + // (UPDATED) + if (interestRate > .07) + { + cout << "This account earns a $10 bonus.\n"; + balance += 10.0; + } + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Examples/4-6.cpp b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Examples/4-6.cpp new file mode 100644 index 0000000..ccb213c --- /dev/null +++ b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Examples/4-6.cpp @@ -0,0 +1,36 @@ +//******************************************* +// This program averages 3 test scores. +// It demonstrates an if statement executing +// a block of statements +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//******************************************* +#include +#include +using namespace std; + +int main() +{ + const int HIGH_SCORE = 95; // A high score is 95 or greater + double average; // To hold the average score + int score1, score2, score3; // To hold three test scores + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // If the average is high, congratulate the user. + if (average > HIGH_SCORE) + { + cout << "Congratulations!\n"; + cout << "That's a high score.\n"; + cout << "You deserve a pat on the back!\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Examples/4-7.cpp b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Examples/4-7.cpp new file mode 100644 index 0000000..17d7dc0 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.3 Expanding The if Statement/Examples/4-7.cpp @@ -0,0 +1,33 @@ +//************************************************** +// This program averages 3 test scores. The braces +// were inadvertently left out of the if statement. +// +// By: Jesus Hilario Hernandez +// Last Update: December 16, 2016 +//************************************************** +#include +#include +using namespace std; + +int main() +{ + const int HIGH_SCORE = 95; // A high score is 95 or greater + int score1, score2, score3; // To hold three test scores + double average; // To hold the average scores + + // Get three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // ERROR! This if statement is missing its braces! + if (average > HIGH_SCORE) + cout << "Congratulations!\n"; + cout << "That's a high score.\n"; + cout << "You deserve a pat on the back!\n"; + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/00.cpp b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/00.cpp new file mode 100644 index 0000000..ac21245 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/00.cpp @@ -0,0 +1,26 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.12.cpp b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.12.cpp new file mode 100644 index 0000000..09af75e --- /dev/null +++ b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.12.cpp @@ -0,0 +1,44 @@ +/******************************************************************** +* +* Checkpoint 4.12 +* +* TRUE or FALSE: The following if/else statements cause the same +* output to display. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x = 8, y = 9; + + // Statements in question + // A). + if (x > y) + cout << "x is the greater.\n"; + else + cout << "x is not the greater.\n"; // Will display + + // B). + if (y <= x) + cout << "x is not the greater.\n"; + else + cout << "x is the greater.\n"; // Will display + + // FALSE + + //----------------------- + // Output result: + //----------------------- + // x is not the greater. + // x is the greater. + //----------------------- + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.13.cpp b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.13.cpp new file mode 100644 index 0000000..412017d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.13.cpp @@ -0,0 +1,34 @@ +/******************************************************************** +* +* Checkpoint 4.13 +* +* Write an if/else statement that assigns 1 to x if y is equal +* to 100. Otherwise if shouls assign 0 to x. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x = 29, y = 67; + + // The if statement + if (y == 100) + x = 1; + else + x = 0; + + // Display + cout << endl; + cout << "x = " << x << endl; + cout << "y = " << y << endl; + cout << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.14.cpp b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.14.cpp new file mode 100644 index 0000000..d72bc22 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Checkpoint/4.14.cpp @@ -0,0 +1,36 @@ +/******************************************************************** +* +* Checkpoint 4.14 +* +* Write an if/else statement that assigns 0.10 to +* commissionRate unless sales is greater than or +* equal to 50000.00, in which case it assigns 0.20 to +* commissionRate. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + float commissionRate = 0, sales = 78900; + + // The if statement + if (sales >= 50000.00) + commissionRate = 0.20; + else + commissionRate = 0.10; + + // Display + cout << endl; + cout << "sales = " << sales << endl; + cout << "commissionRate = " << commissionRate << endl; + cout << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.4 The if:else Statement/Examples/4-8.cpp b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Examples/4-8.cpp new file mode 100644 index 0000000..0f67069 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Examples/4-8.cpp @@ -0,0 +1,28 @@ +//*************************************************************** +// This program uses the modulus operator to determine +// if a number is odd or even. If the number is evenly divisible +// by 2, it is an even number. A remainder indicates it is odd. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//*************************************************************** +#include +using namespace std; + +int main() +{ + int number; + + cout << "Enter an integer and I will tell you if it\n"; + cout << "is odd or even. "; + cin >> number; + if (number % 2 == 0) + { + cout << number << " is even.\n"; + } + else + { + cout << number << " is odd.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.4 The if:else Statement/Examples/4-9.cpp b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Examples/4-9.cpp new file mode 100644 index 0000000..bd6a517 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.4 The if:else Statement/Examples/4-9.cpp @@ -0,0 +1,40 @@ +//************************************************************ +// This program asks the user for two numbers, num1 and num2. +// num1 is divided by num2 and the result is displayed. +// Before the division operation, however, num2 is tested +// for the value 0. If it contains 0, the division does not +// take place. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//************************************************************ +#include +using namespace std; + +int main() +{ + double num1, num2, quotient; + + // Get the first number. + cout << "Enter a number: "; + cin >> num1; + + // Get the second number + cout << "Enter another number: "; + cin >> num2; + + // If num2 is not zero, perform the division + if (num2 == 0) + { + cout << "Division by zero is not possible.\n"; + cout << "Please run the program again and enter\n"; + cout << "a number other than zero.\n"; + } + else + { + quotient = num1 / num2; + cout << "The quotient of " << num1 << " divided by "; + cout << num2 << " is " << quotient << ".\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.5 Nested if Statement/Checkpoint/0.00.cpp b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Checkpoint/0.00.cpp new file mode 100644 index 0000000..8b5bc9d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Checkpoint/0.00.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.5 Nested if Statement/Checkpoint/4.15.cpp b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Checkpoint/4.15.cpp new file mode 100644 index 0000000..1dc848c --- /dev/null +++ b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Checkpoint/4.15.cpp @@ -0,0 +1,59 @@ +/******************************************************************** +* +* Checkpoint 4.15 +* +* If you executed the following code, what should it display if +* the user enters 5? What if the user enters 15? What if the +* user enters 15? What if the user enters 30? What if the user +* enters -1? +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int number; + cout << "Enter a number: "; + cin >> number; + + if (number > 0) + { + cout << "Zero\n"; + + if (number > 10) + { + cout << "Ten\n"; + + if (number > 20) + { + cout << "Twenty\n"; + } + } + } + + // When user enter 5 + // Output: + // Zero + + // When user enter 15 + // Output: + // Zero + // Ten + + // When user enter 30 + // Output: + // Zero + // Ten + // Twenty + + // When user enter -1 + // Output: + // + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-10.cpp b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-10.cpp new file mode 100644 index 0000000..96b5e80 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-10.cpp @@ -0,0 +1,35 @@ +//***************************************************** +// This program demonstrates the nested if statement. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//***************************************************** +#include +using namespace std; + +int main() +{ + char employed, // Currently employed, Y or N + recentGrad; // Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or "; + cout << "N for No.\n"; + cout << "Are you employed? "; + cin >> employed; + cout << "Have you graduated from college "; + cout << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qulaifications. + if (employed == 'Y') + { + if (recentGrad == 'Y') // Nested if + { + cout << "You qualify for the special "; + cout << "interest rate.\n"; + } + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-11.cpp b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-11.cpp new file mode 100644 index 0000000..dec616d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-11.cpp @@ -0,0 +1,45 @@ +//************************************************* +// This Program demonstrates the nest if statement +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//************************************************* +#include +using namespace std; + +int main() +{ + char employed, // Currently employed, Y or N + recentGrad;// Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or "; + cout << "N for No.\n"; + cout << "Are you employed? "; + cin >> employed; + cout << "Have you graduated from college "; + cout << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qualifications. + if (employed == 'Y') + { + if (recentGrad == 'Y') // Nested if + { + cout << "You qualify for the special "; + cout << "interest rate.\n"; + } + else // Not a recent grand, but employed + { + cout << "You must have graduated from "; + cout << "college in the past two\n"; + cout << "years to qualify.\n"; + } + } + else // Not a recent grad, but employed + { + cout << "You must be employed to qualify.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-12.cpp b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-12.cpp new file mode 100644 index 0000000..d8de445 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.5 Nested if Statement/Examples/4-12.cpp @@ -0,0 +1,57 @@ +//******************************************************** +// This program uses nested if/else statements to assign a +// letter grade (A, B, C, D, or F) to anumber test score. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//******************************************************** +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n"; + cout << "tell you the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + { + cout << "Your grade is A.\n"; + } + else + { + if (testScore >= B_SCORE) + { + cout << "Your grad is B.\n"; + } + else + { + if(testScore >= C_SCORE) + { + cout << "Your grad is C.\n"; + } + else + { + if (testScore >= D_SCORE) + { + cout << "Your grade is D.\n"; + } + else + { + cout << "Your grade is F.\n"; + } + } + } + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/0.00.cpp b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/0.00.cpp new file mode 100644 index 0000000..8b5bc9d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/0.00.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/4.16.cpp b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/4.16.cpp new file mode 100644 index 0000000..772dbe1 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/4.16.cpp @@ -0,0 +1,40 @@ +/******************************************************************** +* +* Checkpoint 4.16 +* +* What will the following code display? +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int funny = 7, serious = 15; + funny = serious % 2; + + if (funny != 1) + { + funny = 0; + serious = 0; + } + else if (funny == 2) + { + funny = 10; + serious = 10; + } + else + { + funny = 1; + serious = 1; + } + cout << funny << " " << serious << endl; + + // Output: 1 1 + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/4.17.cpp b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/4.17.cpp new file mode 100644 index 0000000..7ce8f8b --- /dev/null +++ b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Checkpoint/4.17.cpp @@ -0,0 +1,61 @@ +/******************************************************************** +* +* Checkpoint 4.17 +* +* The following code is used in a bookstore program to +* determine how many discount coupons a customer gets. +* Complete the table that appears after the program. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int numBooks, numCoupons; + + // Display + cout << "How many books are being purchased? "; + cin >> numBooks; + + // if statement + if (numBooks < 1) + numCoupons = 0; + else if (numBooks < 3) + numCoupons = 1; + else if (numBooks < 5) + numCoupons = 2; + else + numCoupons = 3; + + // Display + cout << "The number of coupons to give is " + << numCoupons << endl; + + // When user enter 1 + // Output: + // The number of coupons to give us 1 + + // When user enter 3 + // Output: + // The number of coupons to give us 2 + + // When user enter 4 + // Output: + // The number of coupons to give us 2 + + // When user enter 5 + // Output: + // The number of coupons to give is 3 + + // When user enter 10 + // Output: + // The number of coupons to give is 3 + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Examples/4-13.cpp b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Examples/4-13.cpp new file mode 100644 index 0000000..c46ebae --- /dev/null +++ b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Examples/4-13.cpp @@ -0,0 +1,48 @@ +//********************************************************** +// This program uses an if/else if statment to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell your the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + { + cout << "Your grade is A.\n"; + } + else if (testScore >= B_SCORE) + { + cout << "Your grade is B.\n"; + } + else if (testScore >= C_SCORE) + { + cout << "Your grade is C.\n"; + } + else if (testScore >= D_SCORE) + { + cout << "Your grade is D.\n"; + } + else + { + cout << "Your grade is F.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Examples/4-14.cpp b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Examples/4-14.cpp new file mode 100644 index 0000000..53fdb80 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.6 The if:else if Statememt/Examples/4-14.cpp @@ -0,0 +1,53 @@ +//*********************************************************** +// This program uses an if/else if statment to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +// USING THE TRAILING ELSE TO CATCH ERRORS!!!! +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//*********************************************************** +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell your the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + { + cout << "Your grade is A.\n"; + } + else if (testScore >= B_SCORE) + { + cout << "Your grade is B.\n"; + } + else if (testScore >= C_SCORE) + { + cout << "Your grade is C.\n"; + } + else if (testScore >= D_SCORE) + { + cout << "Your grade is D.\n"; + } + else if (testScore >= 0) + { + cout << "Your grade is F.\n"; + } + else + { + cout << "Invalid test score.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-15.cpp b/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-15.cpp new file mode 100644 index 0000000..855ffae --- /dev/null +++ b/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-15.cpp @@ -0,0 +1,39 @@ +//******************************************************** +// This program demonstrates the && logical operator. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//******************************************************** +#include +using namespace std; + +int main() +{ + char employed, // Currently, Y or N + recentGrad;// Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or N for No.\n"; + + cout << "Are you employed? "; + cin >> employed; + + cout << "Have you graduated from college " + << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qualifications + if (employed == 'Y' && recentGrad == 'Y') + { + cout << "You qualify for the special " + << "interest rate.\n"; + } + else + { + cout << "You must be employed and have\n" + << "graduated from college in the\n" + << "past two years qualify.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-16.cpp b/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-16.cpp new file mode 100644 index 0000000..915cd23 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-16.cpp @@ -0,0 +1,42 @@ +//***************************************************** +// This program demonstrates the logical || operator. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//***************************************************** +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + // Variables + double income; // Annual income + int years; // Years at the current job + + // Get the annual income + cout << "What is your annual income? "; + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + cin >> years; + + // Determine the user's loan qualifications. + if (income >= MIN_INCOME || years > MIN_YEARS) + { + cout << "You qualify.\n"; + } + else + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << " years.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-17.cpp b/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-17.cpp new file mode 100644 index 0000000..cb0f1b9 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.8 Logical Operators/Examples/4-17.cpp @@ -0,0 +1,42 @@ +//*************************************************** +// This program demonstrates the logical ! operator. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 16, 2016 +//*************************************************** +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + // Variables + double income; // Annual income + int years; // Years at the current job + + // Get the annual income + cout << "What is your annual income? "; + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + cin >> years; + + // Determine the user's loan qualifications. + if (!(income >= MIN_INCOME || years > MIN_YEARS)) + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << " years.\n"; + } + else + { + cout << "Your qualify.\n"; + } + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/0.00.cpp b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/0.00.cpp new file mode 100644 index 0000000..8b5bc9d --- /dev/null +++ b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/0.00.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* Title +* +* Description +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + + // The if statement + + // Disply + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.18.cpp b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.18.cpp new file mode 100644 index 0000000..04eda44 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.18.cpp @@ -0,0 +1,64 @@ +/******************************************************************** +* +* Checkpoint 4.18 +* +* The following truth table shows various combinations of the +* values true and false connected by a logical operator. Complete +* the table by indicating if the result of such a combination is +* TRUE or FALSE. +* +* +* *************************************************** +* Logical Expression Result(true or false) +* *************************************************** +* true && false 0 +* true && true 1 +* false && true 0 +* false && false 0 +* true || false 1 +* true || true 1 +* false || true 1 +* false || false 0 +* !true 0 +* !false 1 +* **************************************************** +* +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + cout << endl; + cout << "true && false --> " << (true && false) << endl; + cout << "true && true --> " << (true && true) << endl; + cout << "false && true --> " << (false && true) << endl; + cout << "false && false --> " << (false && false) << endl; + cout << "true || false --> " << (true || false) << endl; + cout << "true || true --> " << (true || true) << endl; + cout << "false || true --> " << (false || true) << endl; + cout << "false || false --> " << (false || false) << endl; + cout << "!true --> " << (!true) << endl; + cout << "!false --> " << (!false) << endl; + cout << endl; + + // Output: + + // true && false --> 0 + // true && true --> 1 + // false && true --> 0 + // false && false --> 0 + // true || false --> 1 + // true || true --> 1 + // false || true --> 1 + // false || false --> 0 + // !true --> 0 + // !false --> 1 + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.19.cpp b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.19.cpp new file mode 100644 index 0000000..5309e2e --- /dev/null +++ b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.19.cpp @@ -0,0 +1,39 @@ +/******************************************************************** +* +* Checkpoint 4.19 +* +* Assume the variables a = 2, b = 4, and c = 6. Indicate by +* circling the T or F if each of the following conditions is true +* or false: +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int a = 2, b = 4, c = 6; + + cout << endl; + cout << "a == 4 || b > 2 --> " << (a == 4 || b > 2) << endl; // 1 + cout << "6 <= c && a > 3 --> " << (6 <= c && a > 3) << endl; // 0 + cout << "1 != b && c != 3 --> " << (1 != b && c != 3) << endl; // 1 + cout << "a >= -1 || a <= b --> " << (a >= -1 || a <= b) << endl; // 1 + cout << "!(a > 2) --> " << (!(a > 2)) << endl; // 1 + cout << endl; + + // Output: + + // a == 4 || b > 2 --> 1 + // 6 <= c && a > 3 --> 0 + // 1 != b && c != 3 --> 1 + // a >= -1 || a <= b --> 1 + // !(a > 2) --> 1 + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.20.cpp b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.20.cpp new file mode 100644 index 0000000..5e753ea --- /dev/null +++ b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.20.cpp @@ -0,0 +1,26 @@ +/******************************************************************** +* +* Checkpoint 4.20 +* +* Write an if statement that prints the message "The number is +* valid" if the variable speed is within the range 0 through 200. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int speed = 700; + + // The if statement + if (speed >= 0 && speed <= 200) + cout << "The number is valid" << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.21.cpp b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.21.cpp new file mode 100644 index 0000000..e719622 --- /dev/null +++ b/Chapter-4-Making-Decisions/4.9 Checking Numeric Ranges with Logical Operators/Checkpoint/4.21.cpp @@ -0,0 +1,27 @@ +/******************************************************************** +* +* Checkpoint 4.21 +* +* Write an if statement that prints the message "The number is +* not valid" if the variable speed is outside the range 0 +* through 200. +* +* Jesus Hilario Hernandez +* February 13, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int speed = 403; + + // The if statement + if (speed < 0 || speed > 200) + cout << "The number is invalid.\n"; + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/00.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/00.cpp new file mode 100644 index 0000000..4e9ad01 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/00.cpp @@ -0,0 +1,8 @@ +/******************************************************************** +* +* 00. Problem +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/31.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/31.cpp new file mode 100644 index 0000000..4749fa9 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/31.cpp @@ -0,0 +1,33 @@ +/******************************************************************** +* +* 01. Write an if statement that assigns 100 to x when y is eqaul +* to 0. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int y = 0, + x = 0; + + // Solution + if (y == 0) + { + x = 100; + } + + // Display + cout << endl; + cout << "if y = " << y << endl; + cout << "then x = " << x << endl; + cout << endl; + + // Terminate program. + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/32.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/32.cpp new file mode 100644 index 0000000..751dafc --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/32.cpp @@ -0,0 +1,43 @@ +/******************************************************************** +* +* 32. Write an if/else statement that assigns 0 to x when y is equal to +* 10. Otherwise it should assign 1 to x. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x, + y = 0; + + // If y equal 10, then assign 0 to x. + if (y == 10) + { + x = 0; + // Display + cout << endl; + cout << "If y = " << y << endl; + cout << "then x = " << x << endl; + cout << endl; + } + + // else assign 1 to x. + else + { + x = 1; + // Display + cout << endl; + cout << "If y = " << y << endl; + cout << "then x = " << x << endl; + cout << endl; + } + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/33.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/33.cpp new file mode 100644 index 0000000..24b5641 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/33.cpp @@ -0,0 +1,45 @@ +/******************************************************************** +* +* 33. Using the following chart, write an if/else if statement +* that assigns .10, .15, or .20 to commission, depending on +* the value in sales. +* +========================================================+ +* Sales Commission Rate +* +--------------------------------------------------------+ +* Up to $10,000 10% +* $10,000 to $15,000 15% +* Over $15,000 20% +* +========================================================+ +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + float commission_rate, + value_of_sales; + + // Ask user for the value of sales + cout << endl; + cout << "Value of sales: "; + cin >> value_of_sales; + + // Solution + if (value_of_sales < 10000) + commission_rate = .10; + else if (value_of_sales >= 10000 && value_of_sales <= 15000) + commission_rate = .15; + else if (value_of_sales > 15000) + commission_rate = .20; + + // Display + cout << "Commission rate = " << commission_rate * 100 << '%'<< endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/34.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/34.cpp new file mode 100644 index 0000000..3d57e0b --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/34.cpp @@ -0,0 +1,47 @@ +/******************************************************************** +* +* 34. Write an if statement that sets the variable hours to 10 +* when the flag variable minimum is set. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + bool minimum; + int hours = 65; + + cout << endl; + cout << "Enter the minimum in boolean (0 or 1): "; + cin >> minimum; + + // Solution + if (minimum) + + // assign 10 to hours + hours = 10; + + // Display + if (hours == 10) + { + cout << endl; + cout << "minimum flag = " << minimum; + cout << ", hours = " << hours << endl; + cout << endl; + } + else + { + cout << endl; + cout << "minimum flag = " << minimum; + cout << ", hours = " << hours << endl; + cout << endl; + } + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/35.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/35.cpp new file mode 100644 index 0000000..437ce3d --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/35.cpp @@ -0,0 +1,49 @@ +/******************************************************************** +* +* 35. Write nested if statements that perform the following tests: +* If amount1 is greater than 10 and amount2 is less than 100, +* display the greater of the two. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int amount1, amount2; + + // Ask for amount1 and amount2 + cout << endl; + cout << "Amount 1: "; cin >> amount1; + cout << "Amount 2: "; cin >> amount2; + cout << endl; + + // Solution + if (amount1 > 10 && amount2 < 100) + { + // If amount1 is greater than amount2 + if (amount1 > amount2) + { + cout << "amount1 (" << amount1 << ") is greater than "; + cout << "amount2 (" << amount2 << ')' << endl; + } + + // If amount2 is greater than amount1 + if (amount2 > amount1) + { + cout << "amount2 (" << amount2 << ") is greater than "; + cout << "amount1 (" << amount1 << ')' << endl; + } + + } + + // Formatting + cout << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/36.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/36.cpp new file mode 100644 index 0000000..34ffed8 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/36.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* 36. Write an if statement that prints the message "The number is +* valid" if the variable grade is within the range 0 through 100. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int grade = 98; + + // Solution + if (grade >= 0 && grade <= 100) + cout << "\nThe number "<< grade <<" is valid\n" << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/37.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/37.cpp new file mode 100644 index 0000000..7f3672c --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/37.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* 37. Write an if statement that prints the message "The number is valid" +* if the variable temperature is within the range -50 through 150. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int temperature = -56; + + // Solution + if (temperature >= -50 && temperature <= 150) + cout << "\nThe number " << temperature << " is valid\n" << endl; + + // Terminate program false + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/38.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/38.cpp new file mode 100644 index 0000000..b466fe7 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/38.cpp @@ -0,0 +1,24 @@ +/******************************************************************** +* +* 38. Write an if statement that prints the message "The number is not +* valid" if the variable hours is outside the range 0 through 80. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int hours = -58; + + // Solution + if (hours <= 0 || hours >= 80) + cout << "\nThe number " << hours << " is not valid\n" << endl; + + // Terminate program false + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/39.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/39.cpp new file mode 100644 index 0000000..b6255ba --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/39.cpp @@ -0,0 +1,39 @@ +/******************************************************************** +* +* 39. Assume str1 and str2 are string objects that have been +* initialized with different values. Write an if/else +* statement that compares the two objects and displays +* the one that is alphabetically greatest. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + string str1 = "James", str2 = "Turnner"; + + // Solution + if (str1 > str2) + { + // Display + cout << "\nstr1 [" << str1 << "] "; + cout << "is greater than str2 [" << str2 << "]\n"; + } + else + { + // Display + cout << "\nstr2 [" << str2 << "] "; + cout << "is greater than str1 [" << str1 << "]\n"; + } + + // Formatting + cout << endl; + + // Terminate program false + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/40.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/40.cpp new file mode 100644 index 0000000..ec53dcf --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/40.cpp @@ -0,0 +1,65 @@ +/******************************************************************** +* +* 40. Convert the following if/else if statement into a switch statement: +* +* if (choice == 1) +* { +* cout << fixed << showpoint << setprecision(2); +* } +* else if (choice == 2 || choice == 3) +* { +* cout << fixed << showpoint << setprecision(4); +* } +* else if (choice == 4) +* { +* cout << fixed << showpoint << setprecision(6); +* } +* else +* { +* cout << fixed << showpoint << setprecision(8); +* } +* +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +#include // For formatting +using namespace std; + +int main() +{ + // Variables + int choice = 8; + float number = 89.09123843; + + // Formatting + cout << endl; + + // Solution + switch (choice) + { + case 1: + cout << fixed << showpoint << setprecision(2) << number; + break; + + case 2: + case 3: + cout << fixed << showpoint << setprecision(4) << number; + break; + + case 4: + cout << fixed << showpoint << setprecision(6) << number; + break; + + default: + cout << fixed << showpoint << setprecision(8) << number; + } + + // Formatting + cout << '\n' << endl; + + // Terminate program false + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp new file mode 100644 index 0000000..0bbf5ad --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp @@ -0,0 +1,56 @@ +/******************************************************************** +* +* 41. Match the conditional expression with the if/else +* statement that performs the same operation. +* +* A) q = x < y ? a + b : x * 2; +* B) q = x < y ? x * 2 : a + b; +* C) x < y ? q = 0 : q = 1; +* ____ if (x < y) +* q = 0; +* else +* q = 1; +* +* ____ if (x < y) +* q = a + b; +* else +* q = x * 2; +* +* ____ if (x < y) +* q = x * 2; +* else +* q = a + b; +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int a, b, q, x, y; + + // Solution for A) q = (x < y) ? (a + b) : (x * 2); + if (x < y) + q = a + b; + else + q = x * 2; + + // Solution for B) q = x < y ? x * 2 : a + b; + if (x < y) + q = x * 2; + else + q = a + b; + + // Solution for C) x < y ? q = 0 : q = 1; + if (x < y) + q = 0; + else + q = 1; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Fill-in-the-Blank/09-30.txt b/Chapter-4-Making-Decisions/Review Questions and Exercises/Fill-in-the-Blank/09-30.txt new file mode 100644 index 0000000..6f4cb92 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Fill-in-the-Blank/09-30.txt @@ -0,0 +1,47 @@ +9. An expression using the greater-than, less-than, greater-than-or-equal to, less-than-or- equal-to, equal, or not-equal to operator is called a(n) __relational__ expression. + +10. A relational expression is either __true__ or __false__. + +11. The value of a relational expression is 0 if the expression is __false__ or 1 if the expression is __true__. + +12. The if statement regards an expression with the value 0 as __false__. + +13. The if statement regards an expression with a nonzero value as __true__. + +14. For an if statement to conditionally execute a group of statements, the statements must be enclosed in a set of __{curly braces}__. + +15. In an if/else statement, the if part executes its statement or block if the expression is __true__, and the else part executes its statement or block if the expression is __false__. + +16. The trailing else in an if/else if statement has a similar purpose as the __default__ section of a switch statement. + +17. The if/else if statement is actually a form of the __nested__ if statement. + +18. If the sub-expression on the left of the __&&__ logical operator is false, the right sub-expression is not checked. + +19. If the sub-expression on the left of the __||__ logical operator is true, the right sub-expression is not checked. + +20. The __!__ logical operator has higher precedence than the other logical operators. + +21. The logical operators have __left-to-right__ associativity. + +22. The __&&__ logical operator works best when testing a number to determine if it is within a range. + +23. The __||__ logical operator works best when testing a number to determine if it is outside a range. + +24. A variable with __local__ scope is only visible when the program is executing in the block containing the variable’s definition. + +25. You use the __greater than__ operator to determine whether one string object is greater then another string object. + +26. An expression using the conditional operator is called a(n) __conditional__ expression. + +27. The expression that is tested by a switch statement must have a(n) __integer__ value. + +28. The expression following a case statement must be a(n) __constant__ __expression__. + +29. A program will “fall through†a case section if it is missing the __break__ statement. + +30. What value will be stored in the variable t after each of the following statements executes? +A) t = (12 > 1); __1__ +B) t = (2 < 0); __0__ +C) t = (5 == (3 * 2)); __0__ +D) t = (5 == 5); __1__ diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/00.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/00.cpp new file mode 100644 index 0000000..57a677f --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/00.cpp @@ -0,0 +1,8 @@ +/******************************************************************** +* +* 00. The following program has errors. Find as many as you can. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/58.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/58.cpp new file mode 100644 index 0000000..f84e7a0 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/58.cpp @@ -0,0 +1,69 @@ +/******************************************************************** +* +* 58. The following program has errors. Find as many as you can. +* // This program averages 3 test scores. +* //It uses the variable perfectScore as a flag. include +* using namespace std; +* +* int main() +* { +* cout << "Enter your 3 test scores and I will "; +* << "average them:"; +* int score1, score2, score3, +* cin >> score1 >> score2 >> score3; +* double average; +* average = (score1 + score2 + score3) / 3.0; +* if (average = 100); +* perfectScore = true; // Set the flag variable +* cout << "Your average is " << average << endl; +* bool perfectScore; +* if (perfectScore); +* { +* cout << "Congratulations!\n"; +* cout << "That's a perfect score.\n"; +* cout << "You deserve a pat on the back!\n"; return 0; +* } +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + cout << "Enter your 3 test scores and I will "; + cout << "average them:"; + + // Variables + int score1, score2, score3; + + // Receive user input for scores + cin >> score1 >> score2 >> score3; + + // Variable + double average; + + // Calculate + average = (score1 + score2 + score3) / 3.0; + + // decision structure + if (average == 100) + { + bool perfectScore = true; // Set the flag variable + cout << "Your average is " << average << endl; + + // Nested decision structure (if) + if (perfectScore) + { + cout << "Congratulations!\n"; + cout << "That's a perfect score.\n"; + cout << "You deserve a pat on the back!\n"; + } + + } + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/59.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/59.cpp new file mode 100644 index 0000000..00c83ed --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/59.cpp @@ -0,0 +1,62 @@ +/******************************************************************** +* +* 59. The following program has errors. Find as many as you can. +* // This program divides a user-supplied number by another +* // user-supplied number. It checks for division by zero. +* #include +* using namespace std; +* int main() +* { +* double num1, num2, quotient; +* +* cout << "Enter a number: "; +* cin >> num1; +* cout << "Enter another number: "; cin >> num2; +* if (num2 == 0) +* cout << "Division by zero is not possible.\n"; +* cout << "Please run the program again "; +* cout << "and enter a number besides zero.\n"; +* else +* quotient = num1 / num2; +* cout << "The quotient of " << num1 << +* cout << " divided by " << num2 << " is "; +* cout << quotient << endl; +* return 0; +* } +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + double num1, num2, quotient; + + // Ask for user input + cout << "Enter a number: "; + cin >> num1; + cout << "Enter another number: "; + cin >> num2; + + // Decision Structure (if / else) + if (num2 == 0) + { + cout << "Division by zero is not possible.\n"; + cout << "Please run the program again "; + cout << "and enter a number besides zero.\n"; + } + + else + { + quotient = num1 / num2; + cout << "The quotient of " << num1; + cout << " divided by " << num2 << " is "; + cout << quotient << endl; + } + + // Terminate Program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/60.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/60.cpp new file mode 100644 index 0000000..75b7dc5 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/60.cpp @@ -0,0 +1,66 @@ +/******************************************************************** +* +* 60. The following program has errors. Find as many as you can. +* // This program uses an if/else if statement to assign a +* // letter grade (A, B, C, D, or F) to a numeric test score. +* #include +* using namespace std; +* +* int main() +* { +* int testScore; +* cout << "Enter your test score and I will tell you\n"; +* cout << "the letter grade you earned: "; +* cin >> testScore; +* if (testScore < 60) +* cout << "Your grade is F.\n"; +* else if (testScore < 70) +* cout << "Your grade is D.\n"; +* else if (testScore < 80) +* cout << "Your grade is C.\n"; +* else if (testScore < 90) +* cout << "Your grade is B.\n"; +* else +* cout << "That is not a valid score.\n"; +* else if (testScore <= 100) +* cout << "Your grade is A.\n"; +* return 0; +* } +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +// This program uses an if/else if statement to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +#include +using namespace std; + +int main() +{ + // Variables + int testScore; + + // Ask user for test scores + cout << "Enter your test score and I will tell you\n"; + cout << "the letter grade you earned: "; + cin >> testScore; + + // Decision structure (if / else if) + if (testScore < 60) + cout << "Your grade is F.\n"; + else if (testScore < 70) + cout << "Your grade is D.\n"; + else if (testScore < 80) + cout << "Your grade is C.\n"; + else if (testScore < 90) + cout << "Your grade is B.\n"; + else if (testScore <= 100) + cout << "Your grade is A.\n"; + else + cout << "That is not a valid score.\n"; + + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/61.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/61.cpp new file mode 100644 index 0000000..c217813 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/61.cpp @@ -0,0 +1,86 @@ +/******************************************************************** +* +* 61. The following program has errors. Find as many as you can. +* // This program uses a switch-case statement to assign a +* // letter grade (A, B, C, D, or F) to a numeric test score. +* #include +* using namespace std; +* +* int main() { + +* double testScore; +* cout << "Enter your test score and I will tell you\n"; +* cout << "the letter grade you earned: "; +* cin >> testScore; +* switch (testScore) +* { +* case (testScore < 60.0): +* cout << "Your grade is F.\n"; +* break; +* case (testScore < 70.0): +* cout << "Your grade is D.\n"; +* break; +* case (testScore < 80.0): +* cout << "Your grade is C.\n"; +* break; +* case (testScore < 90.0): +* cout << "Your grade is B.\n"; +* break; +* case (testScore <= 100.0): +* cout << "Your grade is A.\n"; +* break; +* default: +* cout << "That score isn't valid\n"; +* return 0; +* } +* +* SWITCH WILL NOT WORK WITH +* RELATIONAL EXPRESSIONS +* RELATIONAL EXPRESSIONS +* RELATIONAL EXPRESSIONS +* +* (e.g. +* x > y, +* x < y, +* x >= y, +* x <= y, +* x == y, +* x != y + ) +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + double testScore; + + // Ask user for input + cout << "Enter your test score and I will tell you\n"; + cout << "the letter grade you earned: "; + + // Receive input + cin >> testScore; + + // Decision structure (if statement) + if (testScore < 60.0) + cout << "Your grade is F.\n"; + else if (testScore < 70.0) + cout << "Your grade is D.\n"; + else if (testScore < 80.0) + cout << "Your grade is C.\n"; + else if (testScore < 90.0) + cout << "Your grade is B.\n"; + else if (testScore <= 100.0) + cout << "Your grade is A.\n"; + else + cout << "That score isn't valid\n"; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/62-65.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/62-65.cpp new file mode 100644 index 0000000..6f395bc --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Find the Errors/62-65.cpp @@ -0,0 +1,54 @@ +/******************************************************************** +* +* 62. The following program has errors. Find as many as you can. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int x, + z, + a = 12, + count; + + // Formatting + cout << endl; + + // 62. The following statement should determine if x is not greater + // than 20. What is wrong with it? + // if (!x > 20) + // Solution + if (x = 12, !(x > 20)) + cout << x << " is not greater that 20\n" << endl; + + // 63. The following statement should determine if count is within the + // range of 0 through 100. What is wrong with it? + // if (count >= 0 || count <= 100) + if (count = 89, count >= 0 && count <= 100) + cout << count << " is within range.\n" << endl; + + // 64. The following statement should determine if count + // is outside the range of 0 through 100. What is wrong with it? + // if (count < 0 && count > 100) + if (count = 120, count < 0 || count > 100) + cout << count << " is out of range.\n" << endl; + + // 65. The following statement should assign 0 to z if a is + // less than 10, otherwise it should assign 7 to z. + // What is wrong with it? + // z = (a < 10) : 0 ? 7; + z = a < 10 ? 0 : 7; + cout << "z = " << z << endl; // z = 7 + + // Formatting + cout << endl; + + // Terminate program. + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/00.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/00.cpp new file mode 100644 index 0000000..a40b8ce --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/00.cpp @@ -0,0 +1,9 @@ +/******************************************************************** +* +* 00. TITLE +* Problem +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/01.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/01.cpp new file mode 100644 index 0000000..ca041fe --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/01.cpp @@ -0,0 +1,48 @@ +/******************************************************************** +* +* 01. Minimum/Maximum +* +* Write a program that asks the user to enter two numbers. +* The program should use the conditional operator to +* determine which number is the smaller and which is the larger. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int num1, num2; + + // Ask the user to enter two numbers + cout << endl; + cout << "Enter Number 1: "; + cin >> num1; + cout << "Enter Number 2: "; + cin >> num2; + + // Formatting + cout << endl; + + // Use a decision structure to determine largest and smallest num + if (num1 < num2) + { + cout << "Number 1 (" << num1 << ") is smallest" << endl; + cout << "Number 2 (" << num2 << ") is largest" << endl; + } + else + { + cout << "Number 1 (" << num1 << ") is largest" << endl; + cout << "Number 2 (" << num2 << ") is smallest" << endl; + } + + // Formatting + cout << endl; + + // Terminate + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/02.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/02.cpp new file mode 100644 index 0000000..0f5bddd --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/02.cpp @@ -0,0 +1,87 @@ +/******************************************************************** +* +* 02. Roman Numeral Converter +* +* Write a program that asks the user to enter a number +* within the range of 1 through 10. Use a switch +* statement to display the Roman numeral version of +* that number. +* +* Input Validation: Do not accept a number less than 1 or +* greater than 10. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +// Functions +void Roman_Numeral_Output (int); + +int main() +{ + // Variables + int userNum; + + // Ask the user to enter a number between 1 and 10. (within range) + cout << "Enter a number between 1 and 10: "; + cin >> userNum; + + // Use switch statement to display the Roman numeral version of that #. + switch (userNum) + { + case 1: + Roman_Numeral_Output(userNum); + cout << "I\n"; + break; + case 2: + Roman_Numeral_Output(userNum); + cout << "II\n"; + break; + case 3: + Roman_Numeral_Output(userNum); + cout << "III\n"; + break; + case 4: + Roman_Numeral_Output(userNum); + cout << "IV\n"; + break; + case 5: + Roman_Numeral_Output(userNum); + cout << "V\n"; + break; + case 6: + Roman_Numeral_Output(userNum); + cout << "VI\n"; + break; + case 7: + Roman_Numeral_Output(userNum); + cout << "VII\n"; + break; + case 8: + Roman_Numeral_Output(userNum); + cout << "VIII\n"; + break; + case 9: + Roman_Numeral_Output(userNum); + cout << "XI\n"; + break; + case 10: + Roman_Numeral_Output(userNum); + cout << "X\n"; + break; + default: + cout << "You must enter a number between 1 and 10" << endl; + cout << "Run the program over and try again." << endl; + break; + } + // Terminate program + return 0; +} + +void Roman_Numeral_Output(int x) +{ + cout << "The Roman numeral for " << x << " is "; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/03.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/03.cpp new file mode 100644 index 0000000..8a33e82 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/03.cpp @@ -0,0 +1,42 @@ +/******************************************************************** +* +* 03. Magic Dates +* +* The date June 10, 1960 is special because when we write it +* in the following format, the month times the day equals the +* year. +* +* 6/10/60 +* +* Write a program that asks the user to enter a month (in +* numeric form), a day, and a two-digit year. The program should +* then determine whether the month times the day is equal to the +* year. If so, it should display a message saying the date is +* magic. Otherwise it should display a message saying the date +* is not magic. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int month, year, day; + // Ask user to enter month, day, and year + cout << "Enter the month (e.g. January = 1, June = 6): "; + cin >> month; + cout << "Enter the day (e.g. 1, 2, 3, 4, etc..): "; + cin >> day; + cout << "Enter the year (e.g. 1978 = 78, 1991 = 91, 2016 = 16): "; + cin >> year; + + // Determine whether month * day = year + cout << endl; + cout << "The date is " << (month * day == year ? "magic" : "not magic"); + cout << endl; + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/04.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/04.cpp new file mode 100644 index 0000000..d1d1f2b --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/04.cpp @@ -0,0 +1,50 @@ +/******************************************************************** +* +* 04. Areas of Rectangles +* +* The area of a rectangle is the rectangles's length times its +* width. Write a program that asks for the length and width of +* two rectangles. The program should tell the user which +* rectangle has the greater area, or if the areas are the same. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + float l1, l2, w1, w2, rectangle1, rectangle2; + + // Ask the user for l and w of 2 rectangles + cout << endl; + cout << "What is the length of the first rectangle: "; + cin >> l1; + cout << "What is the width: "; + cin >> w1; + cout << "What is the length of the second rectangle: "; + cin >> l2; + cout << "The width: "; + cin >> w2; + cout << endl; + + // Calculate area for each triangle + rectangle1 = l1 * w1; + rectangle2 = l2 * w2; + + // Decide & display rectangle with greatest area + if (rectangle1 > rectangle2) + cout << "Area for rectangle 1 is greater." << endl; + else if (rectangle1 < rectangle2) + cout << "Area for rectangle 2 is greater." << endl; + else if (rectangle1 == rectangle2) + cout << "Area for both rectangles is the same." << endl; + + // Formatting last line. + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/05.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/05.cpp new file mode 100644 index 0000000..fb8a30b --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/05.cpp @@ -0,0 +1,55 @@ +/******************************************************************** +* +* 05. Body Mass Index +* +* Write a program that calculates and displays a person’s body +* mass index (BMI). The BMI is often used to determine whether +* a person with a sedentary lifestyle is over- weight or +* underweight for his or her height. A person’s BMI is +* calculated with the following formula: +* +* BMI = weight x 703 / height^2 +* +* where weight is measured in pounds and height is measured +* in inches. The program should display a message indicating +* whether the person has optimal weight, is under- weight, +* or is overweight. A sedentary person’s weight is considered to be +* optimal if his or her BMI is between 18.5 and 25. If the BMI is +* less than 18.5, the person is consid- ered to be underweight. +* If the BMI value is greater than 25, the person is considered to be +* overweight. +* +* Jesus Hilario Hernandez +* February 15, 2018 +* +********************************************************************/ +#include +#include // Included for using pow() function. +using namespace std; + +int main() +{ + // Variables + float BMI, weight, height; + + // Ask user for height & weight + cout << "Enter weight(in pounds): " << endl; + cin >> weight; + cout << "Enter height(in inches, e.g. 5' 9\" = 69): " << endl; + cin >> height; + + // Calculate & display the person's (BMI) + BMI = weight * (703 / pow(height, 2)); + cout << "BMI = " << BMI << endl; + + // Decision Structure + if (BMI >= 18.5 && BMI <= 25) // Optimal weight + cout << "Weight optimal." << endl; + else if (BMI >= 0 && BMI <= 18.5) + cout << "Weight underweight." << endl; + else if (BMI >= 25) + cout << "Weight overweight." << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/06.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/06.cpp new file mode 100644 index 0000000..5ba2ea7 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/06.cpp @@ -0,0 +1,52 @@ +/******************************************************************** +* +* 06. Mass and Weight +* +* Scientists measure and object's mass in kilograms and its +* weight in newtons. If you know the amount of mass that an object +* has, you can calculate its weight, in newtons, with the following +* formula: +* +* Weight = mass x 9.8; +* +* Write a program that asks the user to enter an object's mass, and +* then calculates and displays its weight. If the object weighs less +* than 10 newtons, display a message indicating that the object is +* too light. +* +* Jesus Hilario Hernandez +* February 15, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + float Weight, mass; + + // Ask the user for object's mass + cout << endl; + cout << "What is the object's mass: "; + cin >> mass; + + // Calculate object's weight + Weight = mass * 9.8; + + // Display weight. + cout << "\nObject's weight = " << Weight << '\n' << endl; + + // Decision Statement + if (Weight >= 1000) + cout << "Too heavy."; + else if (Weight <= 10) + cout << "Too light."; + else + cout << "Neither heavy or light."; + + cout << '\n' << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/07.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/07.cpp new file mode 100644 index 0000000..060f3c9 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/07.cpp @@ -0,0 +1,69 @@ +/******************************************************************** +* +* 07. Time Calculator +* +* Write a program that asks the user to enter a number of seconds. +* +* • There are 60 seconds in a minute. If the number of seconds +* entered by the user is greater than or equal to 60, the +* program should display the number of minutes in that many +* seconds. +* +* • There are 3,600 seconds in an hour. If the number of +* seconds entered by the user is greater than or equal to +* 3,600, the program should display the number of hours in that many +* seconds. +* +* • There are 86,400 seconds in a day. If the number of seconds +* entered by the user is greater than or equal to 86,400, the +* program should display the number of days in that many seconds. +* +* Jesus Hilario Hernandez +* February 15, 2018 +* +********************************************************************/ +#include +#include // For setprecision() & fixed manipulator + +using namespace std; + +int main() +{ + // Variables + int seconds; + float num_mins; + + // Ask the user to enter a number of seconds + cout << "\nEnter a number of seconds: "; + cin >> seconds; + + // Format decimal percision at 2 decimal places. + cout << setprecision(2) << fixed; + + // calculate + if (seconds <= 59) + cout << seconds << " is less that 60 seconds." << endl; + else if (seconds >= 60 && seconds < 3600) + { + num_mins = seconds / 60.0; + cout << num_mins << " minutes in " << seconds << " seconds" << endl; + } + + else if (seconds >= 3600 && seconds < 86400) + { + num_mins = seconds / 3600.0; + cout << num_mins << " hours in " << seconds << " seconds" << endl; + } + + else if (seconds >= 86400) + { + num_mins = seconds / 86400.0; + cout << num_mins << " days in " << seconds << " seconds" << endl; + } + + // Format a line break + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/08.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/08.cpp new file mode 100644 index 0000000..8c2ca7d --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/08.cpp @@ -0,0 +1,79 @@ +/******************************************************************** +* +* 08. Color Mixer +* +* The colors red, blue, and yellow are known as the primary +* colors because they cannot be made by mixing other colors. +* When you mix two primary colors, you get a second- ary color, +* as shown here: +* +* When you mix red and blue, you get purple. +* When you mix red and yellow, you get orange. +* When you mix blue and yellow, you get green. +* +* Write a program that prompts the user to enter the names +* of two primary colors to mix. If the user enters anything +* other than “red,†“blue,†or “yellow,†the program should +* display an error message. Otherwise, the program should +* display the name of the secondary color that results by +* mixing two primary colors. +* +* Jesus Hilario Hernandez +* +* February 15, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + string prime_color_1, prime_color_2; + + // Ask user for 2 primary colors + cout << endl; + cout << "Enter 1st primary color : "; + cin >> prime_color_1; + cout << "The 2nd primary color is: "; + cin >> prime_color_2; + + // Format line break + cout << endl; + + // Decision statement and display + if (prime_color_1 == "red" || prime_color_1 == "Red") + { + if (prime_color_2 == "blue" || prime_color_2 == "Blue") + cout << prime_color_1 << " & " << prime_color_2 << " = purple.\n"; + else if (prime_color_2 == "yellow" || prime_color_2 == "Yellow") + cout << prime_color_1 << " & " << prime_color_2 << " = Orange.\n"; + } + + else if (prime_color_1 == "blue" || prime_color_1 == "Blue") + { + if (prime_color_2 == "red" || prime_color_2 == "Red") + cout << prime_color_1 << " & " << prime_color_2 << " = purple.\n"; + else if (prime_color_2 == "yellow" || prime_color_2 == "Yellow") + cout << prime_color_1 << " & " << prime_color_2 << " = green.\n"; + } + else if (prime_color_1 == "yellow") + { + if (prime_color_2 == "red" || prime_color_2 == "Red" || prime_color_2 == "RED") + cout << prime_color_1 << " & " << prime_color_2 << " = orange.\n"; + else if (prime_color_2 == "blue" || prime_color_2 == "Blue") + cout << prime_color_1 << " & " << prime_color_2 << " = green.\n"; + } + else + { + cout << "Neither " << prime_color_1 << " or " << prime_color_2; + cout << " is a NOT a prime number. \nRun the program and try again.\n"; + cout << "Remember a primary color is either Red, Blue, or Yellow.\n"; + } + + // Format line break + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/09.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/09.cpp new file mode 100644 index 0000000..87bdf4c --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/09.cpp @@ -0,0 +1,70 @@ +/******************************************************************** +* +* 09. Change for a Dollar Game +* +* Create a change-counting game that gets the user to enter the +* number of coins required to make exactly one dollar. The program +* should ask the user to enter the number of pennies, nickels, +* dimes, and quarters. If the total value of the coins entered is +* equal to one dollar, the program should congratulate the user +* for winning the game. Otherwise, the program should display a +* message indicating whether the amount entered was more than or +* less than one dollar. +* +* Jesus Hilario Hernandez +* February 16, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Constant variables + const float ONE_DOLLAR = 1.00; + + // Variables + float pennies, + nickels, + dimes, + quarters, + total_coins; + + // Ask user for number of coins to a dollar + cout << "\nLet's see if your coins equal 1 dollar.\n"<< endl; + + // Ask user for number of pennies, nickels, dimes, and quarters. + cout << "How many pennies do you have? "; + cin >> pennies; + + cout << "Nickels? "; + cin >> nickels; + + cout << "Dimes? "; + cin >> dimes; + + cout << "Quarters? "; + cin >> quarters; + + cout << endl; + + // Calculate total coins + total_coins += ((pennies *= .01) + + (nickels *= .05) + + (dimes *= .10) + + (quarters *= .25)); + + // Decision statement + if (total_coins == ONE_DOLLAR) + cout << "Congrats! You've won! Coins equal a dollar." << endl; + else if (total_coins < ONE_DOLLAR) + cout << "Coins less than a dollar. Try again." << endl; + else if (total_coins > ONE_DOLLAR) + cout << "Coins greater that a dollar. Try again." << endl; + + // Format line break + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/10.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/10.cpp new file mode 100644 index 0000000..98342bc --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/10.cpp @@ -0,0 +1,99 @@ +/******************************************************************** +* +* 10. Days in a Month +* +* Write a program that asks the user to enter the month +* (letting the user enter an integer in the range of 1 +* through 12) and the year. The program should then display +* the number of days in that month. Use the following criteria to +* identify leap years: +* +* 1. Determine whether the year is divisible by 100. +* If it is, then it is a leap year if and only +* if it is divisible by 400. For example, 2000 is a +* leap year but 2100 is not. +* +* 2. If the year is not divisible by 100, then it is a +* leap year if and if only it is divisible by 4. For +* example, 2008 is a leap year but 2009 is not. +* +* Here is a sample run of the program: +* Enter a month (1-12): 2 [Enter] +* Enter a year: 2008 [Enter] +* 29 days +* +* Jesus Hilario Hernandez +* February 17, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int year, month; + + // Ask user to enter month + cout << endl; + cout << "Enter the month (1 - 12): "; + cin >> month; + cout << "Enter the year (up to 9000): "; + cin >> year; + cout << endl; + + // Error check for valid year + if (year >= 0 && year <= 9000) + { + // Decision statement for month + switch (month) + { + case 1: + case 3: + case 5: + case 7: + case 8: + case 10: + case 12: + cout << "31 days"; + break; + + case 4: + case 6: + case 9: + case 11: + cout << "30 days"; + break; + + case 2: + // Decision statement for leap year + if (year % 100 == 0) + { + if (year % 400 == 0) + cout << "29 days" << endl; + else + cout << "28 days" << endl; + } + else if (year % 100 != 0) + { + if (year % 4 == 0) + cout << "29 days" << endl; + else + cout << "28 days" << endl; + } + break; + + default: + cout << "Invalid month. Rerun program. Try again." << endl; + } + } + else + cout << "Invalid year. Rerun program. Try again." << endl; + + // Format line break + cout << endl; + + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/11.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/11.cpp new file mode 100644 index 0000000..b241380 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/11.cpp @@ -0,0 +1,71 @@ +/******************************************************************** +* +* 11. Math Tutor +* +* This is a modification of Programming Challenge 17 from Chapter 3. +* Write a program that can be used as a math tutor for a young student. +* The program should display two random numbers that are to be added, +* such as: +* 247 +* +129 +* ----- +* +* The program should wait for the student to enter the answer. If +* the answer is correct, a message of congratulations should be +* printed. If the answer is incorrect, a message should be printed +* showing the correct answer. +* +* Jesus Hilario Hernandez +* February 17, 2018 +* +********************************************************************/ +#include +#include // For rand() and srand() +#include // For time() + +using namespace std; +int main() +{ + // Constant Variables + const int MIN_NUM = 99, + MAX_NUM = 999; + + // Variables + int user_answer, + rand_num_1, + rand_num_2, + rand_num_answer; + + // Show 2 random numbers to be added + // Assign system time to a variable. + unsigned seed = time(0); + + // Seed random number generator with system time + srand(seed); + + // Generate two random numbers + rand_num_1 = (rand() % (MAX_NUM - MIN_NUM + 1)) + MIN_NUM; + rand_num_2 = (rand() % (MAX_NUM - MIN_NUM + 1)) + MIN_NUM; + + // sum of the two random numbers. + rand_num_answer = rand_num_1 + rand_num_2; + + // Display math problem & receive answer + cout << "\n " << rand_num_1 << endl; + cout << " +" << rand_num_2 << endl; + cout << "------" << endl << " "; + cin >> user_answer; + + // Decision statement (check user answer) Display: correct or incorrect + if (user_answer == rand_num_answer) + cout << "\nCongratulations!"; + else + cout << "\nOops. Correct answer here: " << rand_num_answer; + + // Format line break. + cout << endl; + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/12.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/12.cpp new file mode 100644 index 0000000..e363bf1 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/12.cpp @@ -0,0 +1,75 @@ +/******************************************************************** +* +* 12. Software Sales +* A software company sells a package that retails for $99. +* Quantity discounts are given according to the following table. +* --------------------------------------------------------------- +* Quality Discount +* --------------------------------------------------------------- +* 10-19 20% +* 20-49 30% +* 50-99 40% +* 100 or more 50% +* _______________________________________________________________ +* +* Write a program that asks for the number of units sold and computes +* the total cost of the purchase. +* +* Input Validation: Make sure the number of units is greater than 0. +* +* Jesus Hilario Hernandez +* February 19, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int units_sold, + amt_without_discount; + + // Ask user for number of units sold + cout << "\nEnter number of units sold: "; + cin >> units_sold; + + // Total amount before discount + amt_without_discount = units_sold * 99; + + // Compute total cost of the purchase. + // Decision statement to determine sales discounts + if (units_sold >= 0 && units_sold <= 9) + { + cout << "Total cost for " << units_sold << " = "; + cout << (amt_without_discount) << endl; + } + else if (units_sold >= 10 && units_sold <= 19) + { + cout << "Total cost for " << units_sold << " = "; + cout << ((amt_without_discount) - ((amt_without_discount) * .20)) << endl; + } + else if (units_sold >= 20 && units_sold <= 49) + { + cout << "Total cost for " << units_sold << " = "; + cout << ((amt_without_discount) - ((amt_without_discount) * .30)) << endl; + } + else if (units_sold >= 50 && units_sold <= 99) + { + cout << "Total cost for " << units_sold << " = "; + cout << ((amt_without_discount) - ((amt_without_discount) * .40)) << endl; + } + else if (units_sold >= 100) + { + cout << "Total cost for " << units_sold << " = "; + cout << ((amt_without_discount) - ((amt_without_discount) * .50)) << endl; + } + else + cout << "Oops. Rerun the program again. Choose a number greater that 0." << endl; + + // Format a line break + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/13.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/13.cpp new file mode 100644 index 0000000..77bdee1 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/13.cpp @@ -0,0 +1,65 @@ +/******************************************************************** +* +* 13. Book Club Points +* +* Serendipity Booksellers has a book club that awards points +* to its customers based on the number of books purchased each +* month. The points are awarded as follows: +* +* • If a customer purchases 0 books, he or she earns 0 points. +* • If a customer purchases 1 book, he or she earns 5 points. +* • If a customer purchases 2 books, he or she earns 15 points. +* • If a customer purchases 3 books, he or she earns 30 points. +* • If a customer purchases 4 or more books, he or she earns 60 points. +* +* Write a program that asks the user to enter the number of +* books that he or she has purchased this month and then displays +* the number of points awarded. +* +* Jesus Hilario Hernandez +* February 19, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + int books_purchased; + + // Get number of books user purchased this month. + cout << "\nHow many books did you purchase this month: "; + cin >> books_purchased; + + // Format a line break + cout << endl; + + // Decision statement to determine points earned + if (books_purchased == 0) + cout << "0 points earned"; + + else if (books_purchased == 1) + cout << "5 points earned"; + + else if (books_purchased == 2) + cout << "15 points earned"; + + else if (books_purchased == 3) + cout << "30 points earned"; + + else if (books_purchased >= 4) + cout << "60 points earned"; + + else + { + cout << "Oops. A number greater that 0 must be entered."; + cout << "\nPlease rerun the program and try again."; + } + + // Format two line breaks + cout << endl << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/14.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/14.cpp new file mode 100644 index 0000000..9c91bca --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/14.cpp @@ -0,0 +1,91 @@ +/******************************************************************** +* +* 14. Bank Charges +* +* A bank charges $10 per month plus the following check fees +* for a commercial checking account: +* +* $.10 each for fewer than 20 checks +* $.08 each for 20–39 checks +* $.06 each for 40–59 checks +* $.04 each for 60 or more checks +* +* The bank also charges an extra $15 if the balance of the +* account falls below $400 (before any check fees are applied). +* Write a program that asks for the beginning balance and the +* number of checks written. Compute and display the bank’s +* service fees for the month. +* +* Input Validation: Do not accept a negative value for the +* number of checks written. If a negative value is given for +* the beginning balance, display an urgent message indicating +* the account is overdrawn. +* +* Jesus Hilario Hernandez +* February 1, 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // Variables + float beginning_balance, // Beginning balance. + extra_monthly_charge = 15, // $15 extra if balance falls below $400. + total_monthly_charges = 10; // Total montly charges. Initially $10 + + int num_checks; + + // Ask for beginning balance + cout << "\nWhat is the beginning balance? $"; + cin >> beginning_balance; + + // Decision statement to decide if extra $15 apply + // If less than 400 + if (beginning_balance < 400) + { + total_monthly_charges += 15; + + // If less that 0 + if (beginning_balance < 0) + cout << "URGENT! Your account is overdrawn."; + } + + // Ask for number of checks written + cout << "\nNumber of check written? "; + cin >> num_checks; + + // Decision statement + // If less than 0 + if (num_checks < 0) + { + cout << "Oops. Number of checks written must be 0 or more.\n"; + cout << "Please rerun the program and try again."; + } + + // If greater that 0 + else + { + if (num_checks >= 0 && num_checks < 20) + total_monthly_charges += (num_checks * .10); + + else if (num_checks >= 20 && num_checks <= 39) + total_monthly_charges += (num_checks * .08); + + else if (num_checks >= 40 && num_checks <= 59) + total_monthly_charges += (num_checks * .06); + + else if (num_checks >= 60) + total_monthly_charges += (num_checks * .04); + + cout << "Bank's service fees for the month are: $"; + cout << total_monthly_charges << endl; + } + + // Format line break + cout << endl << '\n'; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/15.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/15.cpp new file mode 100644 index 0000000..0220c0e --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/15.cpp @@ -0,0 +1,87 @@ +/******************************************************************** +* +* 15. Shipping Charges +* +* The Fast Freight Shipping Company charges the following rates: +* _______________________________________________________________ +* Weight of Package (in Kilograms) Rate per 500 Miles Shipped +* --------------------------------------------------------------- +* 2 Kg or less $1.10 +* Over 2 kg but not more than 6kg $2.20 +* Over 6 kg but not more than 10 kg $3.70 +* Over 10 kg but not more than 20 kg $4.80 +* --------------------------------------------------------------- +* +* Write a program that asks for the weight of the package and the +* distance it is to be shipped, and then displays the charges. +* +* Input Validation: Do not accept values of 0 or less for the +* weight of the package. Do not accept weights of more than 20 +* kg (this is the maximum weight the company will ship). Do not +* accept distances of less than 10 miles or more than 3,000 miles. +* These are the company’s minimum and maximum shipping distances. +* +* Jesus Hilario Hernandez +* February 19, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + float package_weight, + distance, + total_charges; + + // Ask for weight of package + cout << "\nWhat is the weight of the package? "; + cin >> package_weight; + + // Decision statement + if (package_weight <= 0 || package_weight > 20) + { + cout << "\nWe're sorry, package weight must be more than 0kg." << endl; + cout << "and less than 20kg. Rerun the program and try again.\n" << endl; + } + else + { + // Ask for distance to be shipped + cout << "\nDistance? "; + cin >> distance; + + // If distance less than 10 or greater than 3000 + if (distance < 10 || distance > 3000) + { + cout << "\nWe're sorry, the distance must be within 10 and 3000 miles.\n"; + cout << "Rerun the program and try again.\n" << endl; + } + else + { + // If less than 2kg + if (package_weight <= 2) + total_charges = (distance / 5) * 1.10; + + // if over 2 kg but not more than 6kg + else if (package_weight > 2 && package_weight <= 6) + total_charges = (distance / 5) * 2.20; + + // If over 6 kg but not more than 10 kg + else if (package_weight > 6 && package_weight <= 10) + total_charges = (distance / 5) * 3.70; + + // If over 10 kg but not more than 20 kg + else if (package_weight > 10 && package_weight <= 20) + total_charges = (distance / 5) * 4.80; + + // Display total charges + cout << "Total charges are " << total_charges << endl; + cout << "For a distance of " << distance << " miles and" << endl; + cout << "a total weight of " << package_weight << " kg.\n" << endl; + } + + } + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/16-a.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/16-a.cpp new file mode 100644 index 0000000..1d2a84d --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/16-a.cpp @@ -0,0 +1,113 @@ +/******************************************************************** +* +* 16-a. Running the Race +* +* Write a program that asks for the names of three runners +* and the time it took each of them to finish a race. The +* program should display who came in first, second, and third +* place. +* +* Input Validation: Only accept positive number for the times. +* +* Jesus Hilario Hernandez +* February 20, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Constant Variables + const int NUM_OF_RUNNERS = 3; // Number of runners and times + + // Variables & Arrays + string runners[NUM_OF_RUNNERS]; // An array of 3 runners + int runners_time[NUM_OF_RUNNERS]; // An array of 3 runner times + + // Ask for names of three runners & times for each to finish race + cout << "\nEnter the names and times for 3 runners. " << endl; + + for (int i = 0; i < NUM_OF_RUNNERS; i++) + { + cout << "Runner #" << i + 1 << ": "; + getline(cin, runners[i]); + + cout << "Runner #" << i + 1 << " time: "; + cin >> runners_time[i]; + cin.ignore(); + } + + // Format line break + cout << endl; + + + // Input Valdation for positive number only + if (runners_time[0] < 0 || runners_time[1] < 0 || runners_time[2] < 0) + { + cout << "We're sorry. Only times 0 or greater will be accepted." << endl; + cout << "Rerun the program and try again." << endl; + } + else + { + // Decision statement for runner placement by time + if (runners_time[0] > runners_time[1]) + { + if (runners_time[0] > runners_time[2]) + { + cout << "First Place: " << runners[0] << " @ " << runners_time[0] << endl; + + if (runners_time[1] > runners_time[2]) + { + cout << "Second Place: " << runners[1] << " @ " << runners_time[1] << endl; + cout << "Third Place: " << runners[2] << " @ " << runners_time[2] << endl; + } + else + { + cout << "Second Place: " << runners[2] << " @ " << runners_time[2] << endl; + cout << "Third Place: " << runners[1] << " @ " << runners_time[1] << endl; + } + } + } + else if (runners_time[1] > runners_time[2]) + { + if (runners_time[1] > runners_time[0]) + { + cout << "First Place: " << runners[1] << " @ " << runners_time[1] << endl; + + if (runners_time[2] > runners_time[0]) + { + cout << "Second Place: " << runners[2] << " @ " << runners_time[2] << endl; + cout << "Third Place: " << runners[0] << " @ " << runners_time[0] << endl; + } + else + { + cout << "Second Place: " << runners[0] << " @ " << runners_time[0] << endl; + cout << "Third Place: " << runners[2] << " @ " << runners_time[2] << endl; + } + } + } + else if (runners_time[2] > runners_time[0]) + { + if (runners_time[2] > runners_time[1]) + { + cout << "First Place: " << runners[2] << " @ " << runners_time[2] << endl; + if (runners_time[0] > runners_time[1]) + { + cout << "Second Place: " << runners[0] << " @ " << runners_time[0] << endl; + cout << "Third Place: " << runners[1] << " @ " << runners_time[1] << endl; + } + else + { + cout << "Second Place: " << runners[1] << " @ " << runners_time[1] << endl; + cout << "Third Place: " << runners[0] << " @ " << runners_time[0] << endl; + } + } + } + } + + // Format line break + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/16-b.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/16-b.cpp new file mode 100644 index 0000000..9e63407 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/16-b.cpp @@ -0,0 +1,105 @@ +/******************************************************************** +* +* 16-b. Running the Race +* +* Write a program that asks for the names of three runners +* and the time it took each of them to finish a race. The +* program should display who came in first, second, and third +* place. +* +* Input Validation: Only accept positive number for the times. +* +* Jesus Hilario Hernandez +* February 20, 2018 +* +********************************************************************/ +#include +#include +using namespace std; +int main() +{ + // Constant Variables + const int NUM_OF_RUNNERS = 3; // Number of runners and times + + // Variables & Arrays + string runners[NUM_OF_RUNNERS]; // An array of 3 runners + int runners_time[NUM_OF_RUNNERS]; // An array of 3 runner times + + // Ask for names of three runners & times for each to finish race + cout << "\nEnter the names and times for 3 runners. " << endl; + + for (int i = 0; i < NUM_OF_RUNNERS; i++) + { + cout << "Runner #" << i + 1 << ": "; + getline(cin, runners[i]); + + cout << "Runner #" << i + 1 << " time: "; + cin >> runners_time[i]; + + cin.ignore(); + } + + // Format line break + cout << endl; + + // Input Valdation for positive number only + if (runners_time[0] < 0 || runners_time[1] < 0 || runners_time[2] < 0) + { + cout << "We're sorry. Only times 0 or greater will be accepted." << endl; + cout << "Rerun the program and try again." << endl; + } + else + { + // Decision statement for runner placement by time + if (runners_time[0] > runners_time[1] && runners_time[0] > runners_time[2]) + { + cout << "First Place: " << runners[0] << " @ " << runners_time[0] << endl; + + if (runners_time[1] > runners_time[2]) + { + cout << "Second Place: " << runners[1] << " @ " << runners_time[1] << endl; + cout << "Third Place: " << runners[2] << " @ " << runners_time[2] << endl; + } + else + { + cout << "Second Place: " << runners[2] << " @ " << runners_time[2] << endl; + cout << "Third Place: " << runners[1] << " @ " << runners_time[1] << endl; + } + } + else if (runners_time[1] > runners_time[2] && runners_time[1] > runners_time[0]) + { + cout << "First Place: " << runners[1] << " @ " << runners_time[1] << endl; + + if (runners_time[2] > runners_time[0]) + { + cout << "Second Place: " << runners[2] << " @ " << runners_time[2] << endl; + cout << "Third Place: " << runners[0] << " @ " << runners_time[0] << endl; + } + else + { + cout << "Second Place: " << runners[0] << " @ " << runners_time[0] << endl; + cout << "Third Place: " << runners[2] << " @ " << runners_time[2] << endl; + } + } + else if (runners_time[2] > runners_time[1] && runners_time[2] > runners_time[0]) + { + cout << "First Place: " << runners[2] << " @ " << runners_time[2] << endl; + if (runners_time[0] > runners_time[1]) + { + cout << "Second Place: " << runners[0] << " @ " << runners_time[0] << endl; + cout << "Third Place: " << runners[1] << " @ " << runners_time[1] << endl; + } + else + { + cout << "Second Place: " << runners[1] << " @ " << runners_time[1] << endl; + cout << "Third Place: " << runners[0] << " @ " << runners_time[0] << endl; + } + } + } + + // Format line break + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/17.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/17.cpp new file mode 100644 index 0000000..be33d77 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/17.cpp @@ -0,0 +1,137 @@ +/******************************************************************** +* +* 17. Personal Best +* +* Write a program that asks for the name of a pole vaulter and +* the dates and vault heights (in meters) of the athlete’s three +* best vaults. It should then report, in order of height (best +* first), the date on which each vault was made and its height. +* +* Input Validation: Only accept values between 2.0 and 5.0 for the +* heights. +* +* Jesus Hilario Hernandez +* February 20, 2018 +* +********************************************************************/ +#include +#include // For exit() function +#include // For using string variables and arrays + +using namespace std; +int main() +{ + // Constant variables + const int NUM_OF_VAULTS = 3; + + // Variables & Arrays + string pole_vaulter, // Hold pole vaulter's name + vault_date[NUM_OF_VAULTS]; // An array of vault dates. + float vault_height[NUM_OF_VAULTS]; // An array of vault heights. + + // Ask for name, dates, and vault heights (in meters) of best 3 vaults + cout << "Enter pole vaulter name: "; + getline(cin, pole_vaulter); + + // For loop to ask for 3 separate vaults & dates + for (int i = 0; i < NUM_OF_VAULTS; i++) + { + int num = i + 1; + + // Ask user for vault height + cout << "Vault #" << num << " height (in meters): "; + cin >> vault_height[i]; + cin.ignore(); + + // Input validation checks if height is within 2.0 and 5.0 range + if (vault_height[i] < 2.0 || vault_height[i] > 5.0) + { + // Explain error + cout << endl; + cout << "We're sorry, vault height must be between" << endl; + cout << "2.0 and 5.0 meters. Rerun the program and try again." << endl; + cout << endl; + exit(EXIT_SUCCESS); + } + + // Ask user for vault date + cout << "Vault #" << num << " date (e.g. 01/07/1922): "; + getline(cin, vault_date[i]); + } + cout << endl; + + if (vault_height[0] > vault_height[1]) + { + if (vault_height[0] > vault_height[2]) + { + cout << "Gold: " << vault_height[0]; + cout << " Date: " << vault_date[0] << endl; + + if (vault_height[1] > vault_height[2]) + { + cout << "Silver: " << vault_height[1]; + cout << " Date: " << vault_date[1] << endl; + cout << "Bronze: " << vault_height[2]; + cout << " Date: " << vault_date[2] << endl; + } + else + { + cout << "Silver: " << vault_height[2]; + cout << " Date: " << vault_date[2] << endl; + cout << "Bronze: " << vault_height[1]; + cout << " Date: " << vault_date[1] << endl; + } + + } + } + else if (vault_height[1] > vault_height[2]) + { + if (vault_height[1] > vault_height[0]) + { + cout << "Gold: " << vault_height[1]; + cout << " Date: " << vault_date[1] << endl; + + if (vault_height[0] > vault_height[2]) + { + cout << "Silver: " << vault_height[0]; + cout << " Date: " << vault_date[0] << endl; + cout << "Bronze: " << vault_height[2]; + cout << " Date: " << vault_date[2] << endl; + } + else + { + cout << "Silver: " << vault_height[2]; + cout << " Date: " << vault_date[2] << endl; + cout << "Bronze: " << vault_height[0]; + cout << " Date: " << vault_date[0] << endl; + } + } + } + else if (vault_height[2] > vault_height[0]) + { + if (vault_height[2] > vault_height[1]) + { + cout << "Gold: " << vault_height[2]; + cout << " Date: " << vault_date[2] << endl; + + if (vault_height[0] > vault_height[1]) + { + cout << "Silver: " << vault_height[0]; + cout << " Date: " << vault_date[0] << endl; + cout << "Bronze: " << vault_height[1]; + cout << " Date: " << vault_date[1] << endl; + } + else + { + cout << "Silver: " << vault_height[1]; + cout << " Date: " << vault_date[1] << endl; + cout << "Bronze: " << vault_height[0]; + cout << " Date: " << vault_date[0] << endl; + } + } + } + + cout << endl; + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/18.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/18.cpp new file mode 100644 index 0000000..2e0c43b --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/18.cpp @@ -0,0 +1,87 @@ +/******************************************************************** +* +* 18. Fat Gram Calculator +* +* Write a program that asks for the number of calories and fat +* grams in a food. The program should display the percentage of +* calories that come from fat. If the calories from fat are less +* than 30% of the total calories of the food, it should also +* display a message indicating that the food is low in fat. +* +* One gram of fat has 9 calories, so +* Calories from fat = fat grams * 9 +* The percentage of calories from fat can be calculated as +* Calories from fat / total calories +* +* Input Validation: Make sure the number of calories and fat +* grams are not less than 0. Also, the number of calories from +* fat cannot be greater than the total number of calories. If that +* happens, display an error message indicating that either the +* calories or fat grams were incorrectly entered. +* +* Jesus Hilario Hernandez +* February 20, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Varibles + float cal_from_fat, + fat_grams, + per_of_cal, + total_cal; + + // Ask for the number of calories & fat grams in food + cout << "\nEnter number of calories: "; + cin >> total_cal; + + if (total_cal > 0) + { + cout << "Enter number of fat grams: "; + cin >> fat_grams; + + if (fat_grams > 0) + { + // Calculate + cal_from_fat = fat_grams * 9; + per_of_cal = (cal_from_fat / total_cal) * 100; + + if (cal_from_fat > total_cal) + { + cout << "\nCalories from fat cannot be greater\n"; + cout << "then the total number of calories." << endl; + cout << "Either the total calories or fat\n"; + cout << "grams were entered incorrectly." << endl; + cout << "Rerun the program and try again." << endl << endl; + } + else + { + // Display the % of calories from fat + cout << "Total calories = " << total_cal << " cal"<< endl; + cout << "Total fat grams = " << fat_grams << " g" << endl; + cout << "Total calories from fat = " << cal_from_fat << " cal from fat"<< endl; + cout << "Total percentage of calories from fat = " << per_of_cal << '%' << endl; + cout << endl; + } + } + else + { + // Explain error and try again + cout << "We're sorry. Total fat grams must be more than 0.\n"; + cout << "Please rerun the progarm and try again." << endl; + } + } + else + { + // Explain error and try again + cout << "We're sorry. Total calories must be more than 0.\n"; + cout << "Please rerun the progarm and try again." << endl; + } + + // If calories from fat are less than 30%, display "food is low in fat" + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/19.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/19.cpp new file mode 100644 index 0000000..c6eceb8 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/19.cpp @@ -0,0 +1,46 @@ +/******************************************************************** +* +* 19. Spectral Analysis +* +* If a scientist knows the wavelength of an electromagnetic wave, +* he or she can determine what type of radiation it is. Write a +* program that asks for the wavelength of an electromagnetic wave +* in meters and then displays what that wave is according to the +* chart below. (For example, a wave with a wavelength of 1E-10 +* meters would be an X-ray.) +* +* Jesus Hilario Hernandez +* February 20, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + double wavelength; + // Ask for wavelength (in meters) + cout << "/nEnter wavelength (in meters): "; + cin >> wavelength; + + // Display the type of wave according to chart + if (wavelength >= 1E-2) + cout << "Radio Waves" << endl; + else if (wavelength <= 1E-2 && wavelength >= 1E-3) + cout << "Microwaves" << endl; + else if (wavelength <= 1E-3 && wavelength >= 7E-7) + cout << "Infrared" << endl; + else if (wavelength <= 7E-7 && wavelength >= 4E-7) + cout << "Visible Light" << endl; + else if (wavelength <= 4E-7 && wavelength >= 1E-8) + cout << "Ultraviolet" << endl; + else if (wavelength <= 1E-8 && wavelength >= 1E-11) + cout << "X Rays" << endl; + else if (wavelength <= 1E-11) + cout << "Gamma Rays" << endl; + + // Format line break + cout << endl; + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/20.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/20.cpp new file mode 100644 index 0000000..4a22fe3 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/20.cpp @@ -0,0 +1,98 @@ +/******************************************************************** +* +* 20. The Speed of Sound +* +* The following table shows the approximate speed of sound in +* air, water, and steel. +* =========================================================== +* Medium Speed +* ----------------------------------------------------------- +* Air 1,100 ft per sec. +* Water 4,900 ft per sec. +* Steel 16,400 ft per sec. +* =========================================================== +* Write a program that displays a menu allowing the user to +* select air, water, or steel. After the user has made a +* selection, he or she should be asked to enter the distance a +* sound wave will travel in the selected medium. The program +* will then display the amount of time it will take. (Round +* the answer to four decimal places.) +* +* Input Validation: Check that the user has selected one of +* the available choices from the menu. Do not accept +* distances less than 0. +* +* Jesus Hilario Hernandez +* February 21, 2018 +* +********************************************************************/ +#include +#include +using namespace std; +int main() +{ + // Variables + int user_select; + float length_of_travel, + amount_of_time; + + // Display menu + // Ask user to select from menu + cout << "===================" << endl; + cout << " Choose one: " << endl; + cout << "-------------------" << endl; + cout << " 1. Air " << endl; + cout << " 2. Water " << endl; + cout << " 3. Steel " << endl; + cout << "===================" << endl; + cin >> user_select; + + // Decision statement + switch (user_select) + { + case 1: + case 2: + case 3: + // Ask user to enter the distance sound wave will travel + cout << "\nHow far will the sound wave travel? "; + cin >> length_of_travel; + + // If less that 0, error check + if (length_of_travel < 0) + { + cout << "\nWe're sorry. Distance must be more than 0.\n"; + cout << "Rerun the program and try again.\n" << endl; + } + else + { + if (user_select == 1) + { + amount_of_time = length_of_travel / 1100; + cout << "In air "; + } + else if (user_select == 2) + { + amount_of_time = length_of_travel / 4900; + cout << "In water "; + } + else if (user_select == 3) + { + amount_of_time = length_of_travel / 16400; + cout << "In steel "; + } + + // Display amount of time it will take + cout << setprecision(4) << fixed; + cout << "the sound wave will take " << amount_of_time; + cout << " seconds to travel." << endl << endl; + } + break; + + default: + cout << "\nWe're sorry. Choose a number between 1 and 3." << endl; + cout << "Rerun the program and try again.\n" << endl; + } + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/21.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/21.cpp new file mode 100644 index 0000000..af749a6 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/21.cpp @@ -0,0 +1,124 @@ +/******************************************************************** +* +* 21. The Speed of Sound in Gases +* +* When sound travels through a gas, its speed depends +* primarily on the density of the medium. The less dense +* the medium, the faster the speed will be. The following +* table shows the approximate speed of sound at 0 degrees +* centigrade, measured in meters per second, when traveling +* through carbon dioxide, air, helium, and hydrogen. +* ========================================================== +* Medium Speed (Meters per Second) +* ---------------------------------------------------------- +* Carbon Dioxide 258.0 +* Air 331.5 +* Helium 972.0 +* Hydrogen 1,270.0 +* ========================================================== +* Write a program that displays a menu allowing the user to +* select one of these four gases. After a selection has been +* made, the user should enter the number of seconds it took for +* the sound to travel in this medium from its source to the +* location at which it was detected. The program should then +* report how far away (in meters) the source of the sound was +* from the detection location. +* +* INPUT VALIDATION: Check that the user has selected +* one of the available menu choices. Do not accept +* times less than 0 seconds or more than 30 seconds. +* +* Jesus Hilario Hernandez +* February 21, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + char user_selection; + int travel_time; + + // Display menu / receive user selection + cout << "=========================" << endl; + cout << " Medium " << endl; + cout << "-------------------------" << endl; + cout << " A. Carbon Dioxide " << endl; + cout << " B. Air " << endl; + cout << " C. Helium " << endl; + cout << " D. Hydrogen " << endl; + cout << "=========================\n" << endl; + cin >> user_selection; + + switch (user_selection) + { + case 'a': + case 'A': + + case 'b': + case 'B': + + case 'c': + case 'C': + + case 'd': + case 'D': + + // Ask user to enter number of seconds it took for. + cout << "\nEnter number of seconds it " << endl; + cout << "took for the sound to travel. "; + cin >> travel_time; + + // Error check within range 0 and 30. + if (travel_time < 0 || travel_time > 30) + { + cout << "\nWe're sorry. Number of seconds must " << endl; + cout << "be within 0 and 30 seconds." << endl << endl; + } + + // Display how far away source of sound was from location + else + { + + cout << "\nThrough "; + + if (user_selection == 'a' || user_selection == 'A') + { + travel_time *= 258.0; + cout << "Carbon Dioxide "; + } + else if (user_selection == 'b' || user_selection == 'B') + { + travel_time *= 331.5; + cout << "Air "; + } + else if (user_selection == 'c' || user_selection == 'C') + { + travel_time *= 972.0; + cout << "Helium "; + } + else if (user_selection == 'd' || user_selection == 'D') + { + travel_time *= 1270.0; + cout << "Hydrogen "; + } + + cout << "the source \nof sound is " << travel_time; + cout << " meters away.\n" << endl; + + } + break; + + default: + + // Error check if choice is any letter other than A thru D. + cout << "\nWe're sorry. A letter between A and D must be\n"; + cout << "chosen. Rerun the program dn try again.\n" << endl; + break; + } + + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/22.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/22.cpp new file mode 100644 index 0000000..f00901e --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/22.cpp @@ -0,0 +1,85 @@ +/******************************************************************** +* +* 22. Freezing and Boiling Points +* +* The following table lists the freezing and boiling points of +* several substances. Write a program that asks the user to +* enter a temperature and then shows all the substances +* that will freeze at that temperature and all that will +* boil at that temperature. For example, if the user +* enters −20 the program should report that water will +* freeze and oxygen will boil at that temperature. +* ================================================================= +* Substance Freezing Point (F) Boiling Point (F) +* ----------------------------------------------------------------- +* Ethyl alcohol -173 172 +* Mercury -38 676 +* Oxygen -362 -306 +* Water 32 212 +* ============================================================= +* +* Jesus Hilario Hernandez +* February 21, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + float user_temp; + + // Ask the user for temp. + cout << "Enter temperature: "; cin >> user_temp; + + // Display all substances that will freeze or boil + cout << "\nAt " << user_temp << " F these substances will either freeze or boil.\n"; + + if (user_temp <= 32) + { + cout << "\nFreeze:\n"; + cout << "--------" << endl; + cout << "Water" << endl; + + if (user_temp <= -38) + { + cout << "Mercury" << endl; + + if (user_temp <= -173) + { + cout << "Ethyl alcohol" << endl; + + if (user_temp <= -362) + { + cout << "Oxygen" << endl; + } + } + } + cout << endl; + } + + if (user_temp >= -306) + { + cout << "Boil: \n"; + cout << "--------" << endl; + cout << "Oxygen." << endl; + + if (user_temp >= 172) + { + cout << "Ethyl alcohol." << endl; + + if (user_temp >= 212) + { + cout << "Water" << endl; + + if (user_temp >= 676) + { + cout << "Mercury" << endl; + } + } + } + cout << endl; + } + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/23.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/23.cpp new file mode 100644 index 0000000..4ed9e6b --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/23.cpp @@ -0,0 +1,192 @@ +/******************************************************************** +* +* 23. TITLE +* +* Write a program that displays the following menu: +* +* Geometry Calculator +* +* 1. Calculate the Area of a Circle +* 2. Calculate the Area of a Rectangle +* 3. Calculate the Area of a Triangle +* 4. Quit +* +* Enter your choice (1-4): +* +* If the user enters 1, the program should ask for the radius of +* the circle and then display its area. Use the following formula: +* +* area = Ï€r2 +* +* Use 3.14159 for Ï€ and the radius of the circle for r. If the user +* enters 2, the program should ask for the length and width of +* the rectangle and then display the rectangle’s area. Use the following +* formula: +* +* area = length * width +* +* If the user enters 3 the program should ask for the +* length of the triangle’s base and its height, and then +* display its area. Use the following formula: +* +* area = base * height * .5 +* +* If the user enters 4, the program should end. +* +* Input Validation: Display an error message if the user +* enters a number outside the range of 1 through 4 when +* selecting an item from the menu. Do not accept negative +* values for the circle’s radius, the rectangle’s length or +* width, or the triangle’s base or height. +* +* Jesus Hilario Hernandez +* February 23, 2018 +* +********************************************************************/ +#include +#include // for pow() function + +using namespace std; +int main() +{ + // Constant Variables + const float PI = 3.14159; + + // Variables + int user_choice; + + // Display menu + cout << endl << "Geometry Calculator\n" << endl; + cout << " 1. Calculate the Area of a Cricle" << endl; + cout << " 2. Calculate the Area of a Rectangle" << endl; + cout << " 3. Calculate the Area of a Triangle" << endl; + cout << " 4. Quit" << endl; + cout << endl << "Enter you choice (1-4): "; + cin >> user_choice; + cout << endl; + + // Decision statement --> menu selection + switch (user_choice) + { + // Switch Variables + float area; + + case 1: + // case 1 Variables; + int radius; + + // Ask for radius + cout << "What is the radius: "; + cin >> radius; + + // Validate radius + if (radius < 0) + { + cout << "We're sorry. \nThe radius must be a positive number." << endl; + cout << "Rerun the program and try again.\n" << endl; + } + else + { + // Calculate area + area = PI * pow(radius, 2); + + // Display area + cout << "The area of the circle is " << area << endl; + } + break; + + case 2: + // case 2 variables + float width, length; + + // Ask for length + cout << "What is the length? " << endl; + cin >> length; + + // Validate length + if (length > 0) + { + // Ask for width + cout << "Width? " << endl; + cin >> width; + + // Validate width + if (width > 0) + { + // Calculate Area + area = length * width; + + // Display area of user rectangle + cout << "The area of rectangle is " << area << endl; + } + else + { + // Explain error + cout << "\nWe're sorry. \nWidth must be greater than 0." << endl; + cout << "Rerun the program and try again." << endl; + } + } + else + { + // Explain error + cout << "\nWe're sorry. \nLength must be greater that 0." << endl; + cout << "Rerun the program and try again." << endl; + } + break; + + case 3: + // case 3 variables + float height, + base; + + // Ask for length of triangle's base and height + cout << "What is base length? "; + cin >> base; + + // Validate bas|ze + if (base > 0 |}) + { + // Ask for height + cout << "Height? "; + cin >> height; + + // Validate height + if (height > 0) + { + // Calculate area + area = (base * height) * .5; + + // Display area + cout << "Area of triangle is " << area << endl; + } + else + { + // Explain base error + cout << "\nWe're sorry. \nHeight must be greater than 0." << endl; + cout << "Rerun the program and try again." << endl; + } + } + else + { + // Explain height error + cout << "\nWe're sorry. \nBase length must be greater than 0." << endl; + cout << "Rerun the program and try again." << endl; + } + break; + + case 4: + // Salutation + cout << "Good-bye." << endl; + break; + + // Validate user_choice + default: + cout << "We're sorry. \nYour choice must between 1 and 4.\n"; + cout << "Rerun the program and try again." << endl; + break; + } + + cout << endl; + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/24.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/24.cpp new file mode 100644 index 0000000..9e8d2e3 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/24.cpp @@ -0,0 +1,111 @@ +/******************************************************************** +* +* 24. Long-Distance Calls +* +* A long-distance carrier charges the following rates for +* telephone calls: +* +* ============================================================ +* Starting Time of Call Rate per Minute +* ------------------------------------------------------------ +* 00:00-06:59 0.05 +* 07:00-19:00 0.45 + 19:01-23:59 0.20 +* ============================================================ +* +* Write a program that asks for the starting time and the number +* of minutes of the call, and displays the charges. The program +* should ask for the time to be entered as a floating- point +* number in the form HH.MM. For example, 07:00 hours will be +* entered as 07.00, and 16:28 hours will be entered as 16.28. +* +* Input Validation: The program should not accept times that are +* greater than 23:59. Also, no number whose last two digits are +* greater than 59 should be accepted. Hint: Assuming num is a +* floating-point variable, the following expression will give you +* its fractional part: +* +* num − static_cast(num) +* +* Jesus Hilario Hernandez +* February 24, 2018 +* +********************************************************************/ +#include +#include // setprecision(), fixed + +using namespace std; +int main() +{ + // Variables + float starting_time; + + // Ask for starting_time + cout << "\nWhat is the starting time? (HH.MM) \n"; + cout << "e.g. 07.46 is 7 hours and 46 minutes: "; + cin >> starting_time; + cout << endl; + + // Validate starting_time + if (starting_time > 23.59) + { + cout << "We're sorry, time must not exceed 23.59.\n"; + cout << "Rerun the program and try again." << endl; + } + else + { + // Validate last two numbers + if ((starting_time - static_cast(starting_time)) > .59) + { + cout << "We're sorry, the last two digits must not be\n"; + cout << "greater than 59. Rerun the program and\n"; + cout << "try again.\n"; + } + else + { + // Variables + float num_mins; + + // Ask for num_mins + cout << "How long did the call last? (HH.MM): "; + cin >> num_mins; + cout << endl; + + // Validate last two numbers + if ((num_mins - static_cast(num_mins)) > .59) + { + cout << "We're sorry, the last two digits must not be\n"; + cout << "greater than 59. Rerun the program and try again.\n"; + } + else + { + // Variables + float total_charges; + + // Display charges + cout << setprecision(2) << fixed; + cout << "Total charges = $"; + + if (starting_time >= 00.00 && starting_time <= 06.59) + { + total_charges = num_mins * 0.05; + cout << total_charges << endl; + } + else if (starting_time >= 07.00 && starting_time <= 19.00) + { + total_charges = num_mins * 0.45; + cout << total_charges << endl; + } + else if (starting_time >= 19.01 && starting_time <= 23.59) + { + total_charges = num_mins * 0.20; + cout << total_charges << endl; + } + } + } + } + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/25.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/25.cpp new file mode 100644 index 0000000..66f7d83 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/25.cpp @@ -0,0 +1,101 @@ +/******************************************************************** +* +* 25. Mobile Service Provider +* +* A mobile phone service provider has three different +* subscription packages for its customers: +* +* Package A: For $39.99 per month 450 minutes are provided. +* Additional minutes are $0.45 per minute. +* Package B: For $59.99 per month 900 minutes are provided. +* Additional minutes are $0.40 per minute. +* Package C: For $69.99 per month unlimited minutes provided. +* +* Write a program that calculates a customer’s monthly bill. +* It should ask which package the customer has purchased and how +* many minutes were used. It should then display the total amount +* due. +* +* Input Validation: Be sure the user only selects package A, B, or +* C. +* +* Jesus Hilario Hernandez +* February 26, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + char menu_choice; + + // Display menu + cout << "\nPackage A: For $39.99 per month 450 minutes are provided." << endl; + cout << " Additional minutes are $0.45 per minute." << endl; + cout << "Package B: For $59.99 per month 900 minutes are provided." << endl; + cout << " Additional minutes are $0.40 per minute." << endl; + cout << "Package C: For $69.99 per month unlimited minutes provided.\n" << endl; + + // Ask for package customer purchased + cout << "Choose package: "; + cin >> menu_choice; + cout << endl; + + // Validate menu_choice + switch (menu_choice) + { + // Variables + int mins_used; + float total_charges; + + case 'a': + case 'A': + case 'B': + case 'b': + case 'c': + case 'C': + // Ask how many minutes used + cout << "How many minutes used? "; + cin >> mins_used; + cout << endl; + + // Validate mins_used + if (mins_used < 0) + { + cout << "We're sorry. Minutes must be greater than 0.\n"; + cout << "Rerun the program and try again." << endl; + } + else + { + // Display total amount due + cout << "Total monthly charges: "; + + // Calculates customer's monthly bill (choice A) + if (menu_choice == 'a' || menu_choice == 'A') + total_charges = mins_used > 450 ? 39.99 + ((mins_used - 450) * .45) : 39.99; + + // Calculates customer's monthly bill (choice B) + else if (menu_choice == 'b' || menu_choice == 'B') + total_charges = mins_used > 900 ? 59.99 + ((mins_used - 900) * .40) : 59.99; + + // Calculates customer's monthly bill (choice C) + else if (menu_choice == 'c' || menu_choice == 'C') + total_charges = 69.99; + + // Display total charges + cout << total_charges << endl; + } + break; + + default: + // Display error. + cout << "We're sorry. Menu choice must be A, B, or C.\n"; + cout << "Rerun the program and try again." << endl; + } + + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/26.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/26.cpp new file mode 100644 index 0000000..1efb3c8 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/26.cpp @@ -0,0 +1,130 @@ +/******************************************************************** +* +* 26. Mobile Service Provider, Part 2 +* +* Modify the Program in Programming Challenge 25 so that +* it also displays how much money Package A customers would +* save if they purchased packages B or C, and how much money +* Package B customers would save if they purchased Package C. +* If there would be no savings, no message should be printed. +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; +int main() +{ + // Constant Variables + const float A_CHARGES = 39.99, + + A_ADD = .45, + A_MINS = 450, + B_CHARGES = 59.99, + B_ADD = .40, + B_MINS = 900, + + C_CHARGES = 69.99; + + // Variables + char menu_choice; + + // Display menu + cout << "\nPackage A: For $39.99 per month 450 minutes are provided." << endl; + cout << " Additional minutes are $0.45 per minute." << endl; + cout << "Package B: For $59.99 per month 900 minutes are provided." << endl; + cout << " Additional minutes are $0.40 per minute." << endl; + cout << "Package C: For $69.99 per month unlimited minutes provided.\n" << endl; + + // Ask for package customer purchased + cout << "Choose package: "; + cin >> menu_choice; + cout << endl; + + // Validate menu_choice + switch (menu_choice) + { + + // Variables + int mins_used; + float total_charges_A, + total_charges_B, + total_charges_C; + + case 'a': + case 'A': + case 'B': + case 'b': + case 'c': + case 'C': + // Ask how many minutes used + cout << "How many minutes used? "; + cin >> mins_used; + cout << endl; + + // Validate mins_used + if (mins_used < 0) + { + cout << "We're sorry. Minutes must be greater than 0.\n"; + cout << "Rerun the program and try again." << endl; + } + else + { + // Display total amount due + cout << setprecision(2) << fixed; + + // Conditional Statement for each Package + total_charges_A = mins_used > A_MINS ? A_CHARGES + ((mins_used - A_MINS) * A_ADD) : A_CHARGES; + total_charges_B = mins_used > B_MINS ? B_CHARGES + ((mins_used - B_MINS) * B_ADD) : B_CHARGES; + total_charges_C = C_CHARGES; + + // Calculates customer's monthly bill (choice A) + if (menu_choice == 'a' || menu_choice == 'A') + { + cout << "Package A monthly charges: $" << total_charges_A << endl; + cout << endl; + + // Decides if Package A is greater than B + if (total_charges_A > total_charges_B) + { + cout << "You could have saved $" << total_charges_A - total_charges_B; + cout << " with Package B." << endl; + cout << "You could have saved $" << total_charges_A - total_charges_C; + cout << " with Package C." << endl; + } + + } + // Calculates customer's monthly bill (choice B) + else if (menu_choice == 'b' || menu_choice == 'B') + { + cout << "Package B monthly charges: $" << total_charges_B << endl; + + // Decides if Package B is greater than B + if (total_charges_B > total_charges_C) + { + cout << "You could have saved $" << total_charges_B - total_charges_C; + cout << " with Package C." << endl; + } + + } + // Calculates customer's monthly bill (choice C) + else if (menu_choice == 'c' || menu_choice == 'C') + cout << "Package C monthly charges: $" << total_charges_C << endl; + + } + break; + + default: + // Display error. + cout << "We're sorry. Menu choice must be A, B, or C.\n"; + cout << "Rerun the program and try again." << endl; + } + + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/27.cpp b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/27.cpp new file mode 100644 index 0000000..3e8dd6c --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/27.cpp @@ -0,0 +1,225 @@ +/******************************************************************** +* +* 27. Mobile Service Provider, Part 3 +* +* Months with 30 days have 720 hours, and months with 31 days +* have 744 hours. February, with 28 days, has 672 hours. You can +* calculate the number of minutes in a month by multiplying its +* number of hours by 60. Enhance the input validation of the +* Mobile Service Provider program by asking the user for the +* month (by name), and validating that the number of minutes +* entered is not more than the maximum for the entire month. +* Here is a table of the months, their days, and number of hours +* in each. +* +* ============================================================== +* Month Days Hours +* ------------------------------------------------------------- +* January 31 744 +* February 28 672 +* March 31 744 +* April 30 720 +* May 31 744 +* June 30 720 +* July 31 744 +* August 31 744 +* September 30 720 +* October 31 744 +* November 30 720 +* December 31 744 +* ============================================================== +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include +#include + +using namespace std; +int main() +{ + // Constant Variables + const float A_CHARGES = 39.99, + A_ADD = .45, + A_MINS = 450, + B_CHARGES = 59.99, + B_ADD = .40, + B_MINS = 900, + C_CHARGES = 69.99, + _30_DAYS = 30, + _31_DAYS = 31, + _28_DAYS = 28, + NUM_MINS_IN_28_DAYS = 672 * 60, + NUM_MINS_IN_30_DAYS = 720 * 60, + NUM_MINS_IN_31_DAYS = 744 * 60; + + + // Variables + char menu_choice; // Menu selection (menu_choice) + string month; // User (month) + + // Display menu + cout << "\nPackage A: For $39.99 per month 450 minutes are provided." << endl; + cout << " Additional minutes are $0.45 per minute." << endl; + cout << "Package B: For $59.99 per month 900 minutes are provided." << endl; + cout << " Additional minutes are $0.40 per minute." << endl; + cout << "Package C: For $69.99 per month unlimited minutes provided.\n" << endl; + + // Ask for package customer purchased + cout << "Choose package: "; + cin >> menu_choice; + cout << endl; + + // Validate menu_choice + switch (menu_choice) + { + + // Variables + int counter; + float total_charges_A, + total_charges_B, + total_charges_C; + + case 'a': + case 'A': + case 'B': + case 'b': + case 'c': + case 'C': + + // Ask for (month) + cout << "Choose a month" << endl; + cin >> month; + + // Validate (month) + if (month == "January" || month == "january") + counter = _31_DAYS; + else if (month == "February" || month == "february") + counter = _28_DAYS; + else if (month == "March" || month == "march") + counter = _31_DAYS; + else if (month == "April" || month == "april") + counter = _30_DAYS; + else if (month == "May" || month == "may") + counter = _31_DAYS; + else if (month == "June" || month == "june") + counter = _30_DAYS; + else if (month == "July" || month == "july") + counter = _31_DAYS; + else if (month == "August" || month == "august") + counter = _31_DAYS; + else if (month == "September" || month == "september") + counter = _30_DAYS; + else if (month == "October" || month == "october") + counter = _31_DAYS; + else if (month == "November" || month == "november") + counter = _30_DAYS; + else if (month == "December" || month == "december") + counter = _31_DAYS; + else + { + // Explain input error (month) + cout << "Invalid month. Check spelling, rerun program "; + cout << "and try again." << endl; + } + + // Check if (counter) is between 28 and 31 + if (counter >= _28_DAYS && counter <= _31_DAYS) + { + // Variables + int mins_used; // Minutes used + + // Ask how many (mins_used) + cout << "How many minutes used? "; + cin >> mins_used; + cout << endl; + + // Validate (mins_used) + if (mins_used < 0) + { + // Explain input error (mins_used) + cout << "We're sorry. Minutes must be greater than 0.\n"; + cout << "Rerun the program and try again." << endl; + } + else + { + // Validate (mins_used) + if (counter == _31_DAYS && mins_used > NUM_MINS_IN_31_DAYS) + { + // Explain error (mins_used) to (NUM_MINS_IN_31_DAYS) + cout << "We're sorry. Minutes must be " << NUM_MINS_IN_31_DAYS; + cout << " or less.\nRerun the program and try again." << endl; + } + else if (counter == _30_DAYS && mins_used > NUM_MINS_IN_30_DAYS) + { + // Explain error (mins_used) to (NUM_MINS_IN_30_DAYS) + cout << "We're sorry. Minutes must be " << NUM_MINS_IN_30_DAYS; + cout << " or less.\nReturn the program and try again." << endl; + } + else if (counter == _28_DAYS && mins_used > NUM_MINS_IN_28_DAYS) + { + // Explain error (mins_used) to (NUM_MINS_IN_28_DAYS) + cout << "We're sorry. Minutes must be " << NUM_MINS_IN_28_DAYS; + cout << " or less.\nReturn the program and try again." << endl; + } + else + { + // Format precision + cout << setprecision(2) << fixed; + + // Conditional Statement for each Package + total_charges_A = mins_used > A_MINS ? A_CHARGES + ((mins_used - A_MINS) * A_ADD) : A_CHARGES; + total_charges_B = mins_used > B_MINS ? B_CHARGES + ((mins_used - B_MINS) * B_ADD) : B_CHARGES; + total_charges_C = C_CHARGES; + + // Calculates customer's monthly bill (choice A) + if (menu_choice == 'a' || menu_choice == 'A') + { + cout << "Package A monthly charges: $" << total_charges_A << endl; + cout << endl; + + // Decides if Package A is greater than B + if (total_charges_A > total_charges_B) + { + cout << "You could have saved $" << total_charges_A - total_charges_B; + cout << " with Package B." << endl; + cout << "You could have saved $" << total_charges_A - total_charges_C; + cout << " with Package C." << endl; + } + + } + // Calculates customer's monthly bill (choice B) + else if (menu_choice == 'b' || menu_choice == 'B') + { + cout << "Package B monthly charges: $" << total_charges_B << endl; + + // Decides if Package B is greater than B + if (total_charges_B > total_charges_C) + { + cout << "You could have saved $" << total_charges_B - total_charges_C; + cout << " with Package C." << endl; + } + + } + // Calculates customer's monthly bill (choice C) + else if (menu_choice == 'c' || menu_choice == 'C') + cout << "Package C monthly charges: $" << total_charges_C << endl; + + } + } + } + break; + + default: + // Display error (menu_choice). + cout << "We're sorry. Menu choice must be A, B, or C.\n"; + cout << "Rerun the program and try again." << endl; + } + + cout << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/Short Answer/01-08.txt b/Chapter-4-Making-Decisions/Review Questions and Exercises/Short Answer/01-08.txt new file mode 100644 index 0000000..351aa0d --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/Short Answer/01-08.txt @@ -0,0 +1,23 @@ +1. Describe the difference between the if/else if statement and a series of if statements. +ANSWER NO. 1: In a series of if statements, the program runs through each if statement and does something if the condition is true. In an if/else if statement, if the initial if statement is true then the following else if statements are bypassed. If the initial if statement is not true, the else if statement check if true. If true block within that else if statement is executed. + +2. In an if/else if statement, what is the purpose of a trailing else? +ANSWER NO. 2: The block of code within the trailing else is executed when all other previous if and else if statements are false. + +3. What is a flag and how does it work? +ANSWER NO. 3: A flag is a Boolean or integer variable that signals when a condition exists. + + 4. Can an if statement test expressions other than relational expressions? Explain. + ANSWER NO. 4: An if statement can test any expression that ultimates to a boolean expression. + +5. Briefly describe how the && operator works. +ANSWER NO. 5: The && operator returns true if both expression on either side of the && operator are true. If either side of the && operator is false, it returns false. + +6. Briefly describe how the || operator works. +ANSWER NO. 6: The || operator returns false if both sides are false. And returns true if either side is true. + +7. Why are the relational operators called relational? +ANSWER NO. 7: Relational operators are relational because they compare the values between two variables. + +8. Why do most programmers indent the conditionally executed statements in a decision structure? +ANSWER NO. 8: The conditionally executed statement is normally indented so that you can tell at a glance what part of the program the if statement executes. It stands out visually. diff --git a/Chapter-4-Making-Decisions/Review Questions and Exercises/True or False/42-57.txt b/Chapter-4-Making-Decisions/Review Questions and Exercises/True or False/42-57.txt new file mode 100644 index 0000000..4abd494 --- /dev/null +++ b/Chapter-4-Making-Decisions/Review Questions and Exercises/True or False/42-57.txt @@ -0,0 +1,31 @@ +42. FALSE The = operator and the == operator perform the same + operation when used in a Boolean expression. +43. FALSE A variable defined in an inner block may not have + the same name as a variable defined in the outer block. + +44. FALSE A conditionally executed statement should be indented one level + from the if statement. + +45. FALSE All lines in a block should be indented one level. + +46. TRUE It’s safe to assume that all uninitialized + variables automatically start with 0 as their value. + +47. TRUE When an if statement is nested in the if part of another + statement, the only time the inner if is executed is when the + expression of the outer if is true. + +48. FALSE When an if statement is nested in the else part of + another statement, as in an if/else if, the only time the + inner if is executed is when the expression of the outer + if is true. + +49. TRUE The scope of a variable is limited to the block in which it is defined. + +50. TRUE You can use the relational operators to compare string objects. + +51. TRUE x != y is the same as (x > y || x < y) + +52. FALSE y < x is the same as x >= y + +53. TRUE x >= y is the same as (x > y && x = y) diff --git a/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Checkpoint/5.1.cpp b/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Checkpoint/5.1.cpp new file mode 100644 index 0000000..d7c3196 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Checkpoint/5.1.cpp @@ -0,0 +1,57 @@ +/******************************************************************** +* +* 5.1 What will the following program segments display? +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // What will the following program segments display? + + // A) + int x = 2, + y = x++; + + cout << x << y << endl; // 32 + + // B) + int a = 2, + b = ++a; + + cout << a << b << endl; // 33 + + // C) + int c = 2, + d = 4; + + cout << c++ << --d << endl; // 23 + + // D) + int e = 2, + f = 2 * e++; + + cout << e << f << endl; // 34 + + // E) + int g = 99; + + if (g++ < 100) + cout << "It is true!\n"; // "It is true!" + else + cout << "It is false!\n"; + + // F) + int h = 0; + + if (++h) + cout << "It is true!\n"; // "It is true!" + else + cout << "It is false!\n"; + + // Terminate Program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Examples/5-1.cpp b/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Examples/5-1.cpp new file mode 100644 index 0000000..18d13a8 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Examples/5-1.cpp @@ -0,0 +1,40 @@ +//***************************************************** +// This program demonstrates the ++ and -- operators +// +// By: Jesus Hilario Hernandez +// Last Updated: December 29, 2016 +// +// Used from: Gaddis, "Starting Out With C++", +// 8th Edition, Pg. 228 +//***************************************************** +#include +using namespace std; + +int main() +{ + int num = 4; // num startes out with 4. + + // Display the value in num. + cout << "The variable num is " << num << endl; + cout << "I will now increment num.\n\n"; + + // Use postfix ++ to increment num. + num++; + cout << "Now the variable num is " << num << endl; + cout << "I will increment num again.\n\n"; + + // Use prefix ++ to increment num. + ++num; + cout << "Now the variable is " << num << endl; + cout << "I will decrement num.\n\n"; + + // Use postfix -- to decrement num. + num--; + cout << "Now the variable num is " << num << endl; + cout << "I will decrement num agian.\n\n"; + + // Use prefix -- to increment num. + --num; + cout << "Now the variabe num is " << num << endl; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Examples/5-2.cpp b/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Examples/5-2.cpp new file mode 100644 index 0000000..ef28344 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.1-increment-and-decrement-operators/Examples/5-2.cpp @@ -0,0 +1,30 @@ +//************************************************** +// This program demonstrates the prefix and postfix +// modes of the increment and decrement operators. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 29, 2016 +// +// Used from: Gaddis, "Starting Out With C++", +// 8th Edition, Pg. 229-230 +//************************************************** +#include +using namespace std; + +int main() +{ + int num = 4; + + cout << num << endl; // Displays 4 + cout << num++ << endl; // Displays 4, and then add 1 to num + cout << num << endl; // Displays 5 + cout << ++num << endl; // Adds 1 to num, then displays 6 + cout << endl; // Displays a blank line + + cout << num << endl; // Display 6 + cout << num-- << endl; // Displays 6, then subtracts 1 from num + cout << num << endl; // Displays 5 + cout << --num << endl; // Subracts 1 from num, then diplays 4 + + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.10-Nested-Loops/5-14.cpp b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/5-14.cpp new file mode 100644 index 0000000..e224d49 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/5-14.cpp @@ -0,0 +1,48 @@ +//************************************************************** +// This program averages test scores. It asks the user for the +// number of students and the number of test scores per student. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 10, 2017 +//*************************************************************** +#include +#include +using namespace std; + +int main() +{ + int numStudents, // Number of students + numTests; // Number of tests per student + double total, // Accumulator for total scores + average; // Average test score + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Get the number of students. + cout << "This program averages test scores.\n"; + cout << "For how many students do you have scores? "; + cin >> numStudents; + + // Get the number of test scores per student. + cout << "How many test scores does each student have? "; + cin >> numTests; + + // Determine each student's average score. + for (int student = 1; student <= numStudents; student++) + { + total = 0; // Initialize the accumulator. + for (int test = 1; test <= numTests; test++) + { + double score; + cout << "Enter score " << test << " for "; + cout << "student " << student << ": "; + cin >> score; + total += score; + } + average = total / numTests; + cout << "The average score for student " << student; + cout << " is " << average << ".\n\n"; + } + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/5-14.cpp b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/5-14.cpp new file mode 100644 index 0000000..e224d49 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/5-14.cpp @@ -0,0 +1,48 @@ +//************************************************************** +// This program averages test scores. It asks the user for the +// number of students and the number of test scores per student. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 10, 2017 +//*************************************************************** +#include +#include +using namespace std; + +int main() +{ + int numStudents, // Number of students + numTests; // Number of tests per student + double total, // Accumulator for total scores + average; // Average test score + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Get the number of students. + cout << "This program averages test scores.\n"; + cout << "For how many students do you have scores? "; + cin >> numStudents; + + // Get the number of test scores per student. + cout << "How many test scores does each student have? "; + cin >> numTests; + + // Determine each student's average score. + for (int student = 1; student <= numStudents; student++) + { + total = 0; // Initialize the accumulator. + for (int test = 1; test <= numTests; test++) + { + double score; + cout << "Enter score " << test << " for "; + cout << "student " << student << ": "; + cin >> score; + total += score; + } + average = total / numTests; + cout << "The average score for student " << student; + cout << " is " << average << ".\n\n"; + } + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Hours.cpp b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Hours.cpp new file mode 100644 index 0000000..3da599a --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Hours.cpp @@ -0,0 +1,31 @@ +/******************************************************************** +* +* This program simulates a digital clock. It displays the +* seconds from 0 to 59. +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include +using namespace std; +int main() +{ + cout << fixed << right; + cout.fill('0'); + for (int hours = 0; hours < 24; hours++) + { + for (int minutes = 0; minutes < 60; minutes++) + { + for (int seconds = 0; seconds < 60; seconds++) + { + cout << setw(2) << hours << ':'; + cout << setw(2) << minutes << ':'; + cout << setw(2) << seconds << endl; + } + } + } + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Minutes.cpp b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Minutes.cpp new file mode 100644 index 0000000..f3d79f0 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Minutes.cpp @@ -0,0 +1,27 @@ +/******************************************************************** +* +* This program simulates a digital clock. It displays the +* seconds from 0 to 59. +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include +using namespace std; +int main() +{ + cout << fixed << right; + cout.fill('0'); + for (int minutes = 0; minutes < 60; minutes++) + { + for (int seconds = 0; seconds < 60; seconds++) + { + cout << setw(2) << minutes << ":"; + cout << setw(2) << seconds << endl; + } + } + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Seconds.cpp b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Seconds.cpp new file mode 100644 index 0000000..746e7a5 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.10-Nested-Loops/Examples/Digital Clock/Seconds.cpp @@ -0,0 +1,22 @@ +/******************************************************************** +* +* This program simulates a digital clock. It displays the +* seconds from 0 to 59. +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include // setw() +using namespace std; +int main() +{ + cout << fixed << right; + cout.fill('0'); + for (int seconds = 0; seconds < 60; seconds++) + cout << setw(2) << seconds << endl; + + // Terminate + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.16 - 5.21.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.16 - 5.21.txt new file mode 100644 index 0000000..7a8185e --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.16 - 5.21.txt @@ -0,0 +1,66 @@ +5.16 + + a). What is an output file? + An output file is a file that data is written to. + b). What is an input file? + An input is a file that data is read from. + + + + +5.17 + + What three steps must be taken when a file is used by a program? + + 1. Open the file. - Creates a connection between the file and the program. + 2. Process the file. - Data is written or read + 3. Close the file. - Disconncts the file from the program. + + + + +5.18 + + What is the difference between a text file and a binary file? + + A (text file) can be read, while the binary file has not been decoded + and cannot be read by the program, unless decoded. + + - A (text file) contains data that has been encoded as text + - A (binary file) contains data that has not been converted to text. + + Thus, you cannot view the contents of a (binary file) with a text + editor. + + + + +5.19 + + What is the difference between sequential access and random access? + + - (Sequential access) accessess data from the beginning to the end + of a file. + + - (Random access) can jump directly to any piece of data in a file + without reading the data that comes before it. + + + + +5.20 + + What type of file stream object do you create if you want to write data + to a file? + + ofstream // to create and write + + + + +5.21 + + What type of file stream object do you create if you want to read data + from a file? + + ifstream // to open and read diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.22.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.22.cpp new file mode 100644 index 0000000..b4c3c10 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.22.cpp @@ -0,0 +1,44 @@ +/******************************************************************** +* +* 5.22 +* +* Write a short program that uses a (for) loop to write the +* numbers 1 through 10 to a file. +* +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include // ofstream, open() +#include // setw() + +using namespace std; +int main() +{ + // Define output file stream object to link numbers.txt file + ofstream output_file; + + // 1. Open file numbers.txt through file stream object (output_file) + // 1. Open file numbers.txt through file stream object (output_file) + output_file.open("numbers.txt"); + + // Format fixed right with 0 fill + output_file << fixed << right; + output_file.fill('0'); + + // 2. Process file numbers.txt through file stream object (output_file) + // 2. Process file numbers.txt through file stream object (output_file) + for (int num = 1; num <= 10; num++) + { + output_file << setw(2) << num << endl; + } + + // 3. Close file numbers.txt through file stream object (output_file) + // 3. Close file numbers.txt through file stream object (output_file) + output_file.close(); + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.23.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.23.cpp new file mode 100644 index 0000000..a4f5431 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/5.23.cpp @@ -0,0 +1,41 @@ +/******************************************************************** +* +* 5.23 Write a short program that opens the file created by the +* program you wrote for Checkpoint 5.22, reads all of the +* numbers from the file, and displays them. +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include +using namespace std; +int main() +{ + int number; + + // Declate input file stream object. + ifstream inputFile; + + + // 1. Open file + inputFile.open("numbers.txt"); + + + // 2. Process file + cout << endl; + + while (inputFile >> number) + cout << number << endl; + + cout << endl; + + + // 3. Close file + inputFile.close(); + + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/numbers.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/numbers.txt new file mode 100644 index 0000000..bce7098 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Checkpoint/numbers.txt @@ -0,0 +1,10 @@ +01 +02 +03 +04 +05 +06 +07 +08 +09 +10 diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-15.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-15.cpp new file mode 100644 index 0000000..402fbdc --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-15.cpp @@ -0,0 +1,29 @@ +//*********************************************************** +// This program writes data to a file. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + outputFile.open("demofile.txt"); + + cout << "Now writing data to a file.\n"; + + // Write four names to the file. + outputFile << "Bach\n"; + outputFile << "Beethoven\n"; + outputFile << "Chopin\n"; + outputFile << "Mozart\n"; + outputFile << "Brahms\n"; + + // Close the file + outputFile.close(); + cout << "Done.\n"; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-16.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-16.cpp new file mode 100644 index 0000000..c29e9e0 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-16.cpp @@ -0,0 +1,29 @@ +//*********************************************************** +// This program writes data to a single line in a file. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + outputFile.open("demofile2.txt"); + + cout << "Now writing data to a file.\n"; + + // Write four names to the file. + outputFile << "Bach "; + outputFile << "Beethoven "; + outputFile << "Chopin "; + outputFile << "Mozart "; + outputFile << "Brahms "; + + // Close the file + outputFile.close(); + cout << "Done.\n"; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-17.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-17.cpp new file mode 100644 index 0000000..0062e61 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-17.cpp @@ -0,0 +1,58 @@ +//*********************************************************** +// This program writes user input to a file. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +using namespace std; + +int inputVal(int); + +int main() +{ + ofstream outputFile; + int number1, number2, number3; + + // Open output file. + outputFile.open("Numbers.txt"); + + // Get three numbers from the user. + cout << "Enter a number: "; + number1 = inputVal(number1); + cout << "Enter another number: "; + number2 = inputVal(number2); + cout << "Enter the last number: "; + number3 = inputVal(number3); + + // Write the numbers to the file. + outputFile << number1 << endl + << number2 << endl + << number3 << endl; + cout << "The numbers were saved to a file.\n"; + + // Close the file + outputFile.close(); + cout << "Done\n"; + return 0; +} + +//*************************************************** +// The inputVal function checks for valid input. * +// In this case an int. If the user chooses anything* +// other than an int, they will be prompted to * +// chose valid input. * +//*************************************************** + +int inputVal(int num) +{ + while (!(cin >> num)) + { + cout << "I'm sorry, a number must be entered\n" + << "Try again: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-18.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-18.cpp new file mode 100644 index 0000000..41b69d3 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-18.cpp @@ -0,0 +1,31 @@ +//*********************************************************** +// This program writes user input to a file +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + + // Open an output file + outputFile.open("Friends2.txt"); + + // Get the names of three friends + cout << "Enter the names of 10 friends.\n"; + for (int num = 0; num < 10; num++) + { + string name; + cout << "Friend #" << (num + 1) << ": "; + cin >> name; + outputFile << name << endl; + } + cout << "The names were saved to a file.\n"; + outputFile.close(); + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-19.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-19.cpp new file mode 100644 index 0000000..b16b306 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-19.cpp @@ -0,0 +1,31 @@ +//*********************************************************** +// This program reads data from a file. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + string name; + + + inputFile.open("Friends2.txt"); + cout << "Reading data from the file.\n"; + + int count = 1; + while (inputFile >> name) // While there is data in Friends2.txt file + { + cout << count << ". "<< name << endl; + count++; + } + + cout << "File closed." << endl; + inputFile.close(); + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-20.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-20.cpp new file mode 100644 index 0000000..3e8b504 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-20.cpp @@ -0,0 +1,32 @@ +//*********************************************************** +// This program reads numbers from a file. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int value, sum; + + // Open inputFile + inputFile.open("NumericData.txt"); + + // Read number in NumericData.txt file + cout << "Here are the numbers: " << endl; + while (inputFile >> value) + { + cout << value << endl; + sum += value; + } + cout << "Their sum is: " << sum < +#include +using namespace std; + + +int inputVal(int); // Input validation (int) +double inputVal(double); // Input validation (double) + +int main() +{ + ofstream outputFile; // File stream object + int numberOfDays; // Number of days of sales + double sales; // Sales amount for a days + + // Get the number of days. + cout << "For how many days do you have sales? "; + numberOfDays = inputVal(numberOfDays); + + // Open Sales.txt file + outputFile.open("Sales.txt"); + + // Get and write sales for each day + for (int count = 1; count <= numberOfDays; count++) + { + // Get the sales for a day. + cout << "Enter the sales for day " + << count << ": "; + sales = inputVal(sales); + + // Write sales to file. + outputFile << sales << endl; + } + + // Close file!! + outputFile.close(); + cout << "Data written to Sales.txt file.\n"; + return 0; +} + +//******************************************************* +// The inputVal(int) function check for valid input. * +// If the users types anything other than an integer, * +// they will be promted to enter valid data type. * +//******************************************************* + +int inputVal(int num) +{ + while (!(cin >> num)) + { + cout << "I'm sorry, please type in a number: " << endl; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} + +//******************************************************* +// The inputVal(double) function check for valid input. * +// If the users types anything other than an double, * +// they will be promted to enter valid data type. * +//******************************************************* + +double inputVal(double num) +{ + while (!(cin >> num)) + { + cout << "I'm sorry, please type in a number: " << endl; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-22.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-22.cpp new file mode 100644 index 0000000..a59453c --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-22.cpp @@ -0,0 +1,29 @@ +//*********************************************************** +// This program reads data from a file. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int number; + + // Open file + inputFile.open("ListOfNumbers.txt"); + + // Read the numbers from the file and display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close file! + inputFile.close(); + cout << "File closed." << endl; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-23.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-23.cpp new file mode 100644 index 0000000..f55011d --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-23.cpp @@ -0,0 +1,38 @@ +//*********************************************************** +// This program reads data from a file. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int number; + + // Open File + inputFile.open("NonExistentFile.txt"); + + // If the file opend, process it. + if (inputFile) + { + // Read data from file and display + while (inputFile >> number) + { + cout << number << endl; + } + + // Close File!! + inputFile.close(); + } + else + { + // Display an error message. + cout << "Error opening the file.\n" + << "File does not exist or may be in a different location.\n"; + } + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-24.cpp b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-24.cpp new file mode 100644 index 0000000..a771b8d --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/5-24.cpp @@ -0,0 +1,45 @@ +//*********************************************************** +// This program reads data from a file. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 1, 2016 +//*********************************************************** +#include +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + string filename; + int number; + + // Get filename from user. + cout << "Enter the filename: "; + cin >> filename; + + // Open file + inputFile.open(filename); + + // If the file opens, process it. + if (inputFile) + { + // Read number from file and display them + while (inputFile >> number) + { + cout << number << endl; + } + + // Close file!! + inputFile.close(); + cout << "File closed." << endl; + } + else + { + // Display an error message. + cout << "Error opening the file.\n" + << "File does not exist or may have different filename.\n"; + } + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Friends.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Friends.txt new file mode 100644 index 0000000..7c59791 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Friends.txt @@ -0,0 +1,10 @@ +Grant +Hugh +Jackman +Tyler +Bonny +Clyde +Jimmy +James +Terry +Robert diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Friends2.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Friends2.txt new file mode 100644 index 0000000..0d87b04 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Friends2.txt @@ -0,0 +1,10 @@ +Grand +Gronny +Group +Great +Clip +Chip +Tip +Mimp +Toony +Ray diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/ListOfNumbers.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/ListOfNumbers.txt new file mode 100644 index 0000000..1ed04e6 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/ListOfNumbers.txt @@ -0,0 +1,7 @@ +100 +200 +300 +400 +500 +600 +700 diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Numbers.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Numbers.txt new file mode 100644 index 0000000..ec2a244 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Numbers.txt @@ -0,0 +1,3 @@ +540 +640 +740 diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/NumericData.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/NumericData.txt new file mode 100644 index 0000000..64ef8c8 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/NumericData.txt @@ -0,0 +1,36 @@ +233 +432 +345 +654 +567 +876 +789 +980 +132 +432 +354 +645 +765 +867 +987 +890 +124 +125 +126 +127 +128 +129 +1234 +2345 +3456 +4567 +4567 +5678 +6789 +9876 +8765 +7654 +3645 +2543 +1423 +1234 diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Sales.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Sales.txt new file mode 100644 index 0000000..189aceb --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/Sales.txt @@ -0,0 +1,5 @@ +1000.99 +2000.98 +3000.97 +4500.96 +6500.97 diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/demofile.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/demofile.txt new file mode 100644 index 0000000..b68324d --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/demofile.txt @@ -0,0 +1,5 @@ +Bach +Beethoven +Chopin +Mozart +Brahms diff --git a/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/demofile2.txt b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/demofile2.txt new file mode 100644 index 0000000..a71450c --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.11-Using-Files-for-Data-Storage/Examples/demofile2.txt @@ -0,0 +1 @@ +Bach Beethoven Chopin Mozart Brahms \ No newline at end of file diff --git a/Chapter-5-Loops-and-Files/5.12-Opt-Topics-Breaking-and-Continuing-a-Loop/5-25.cpp b/Chapter-5-Loops-and-Files/5.12-Opt-Topics-Breaking-and-Continuing-a-Loop/5-25.cpp new file mode 100644 index 0000000..800be24 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.12-Opt-Topics-Breaking-and-Continuing-a-Loop/5-25.cpp @@ -0,0 +1,54 @@ +//****************************************************** +// This program raises the user's number to the powers +// of 0 through 10. +// +// By: Jesus Hilario Hernandez +// Last updated: Novermber 1, 2016 +//****************************************************** +#include +#include +using namespace std; + +double inputVal(double); // Input validation (double) + +int main() +{ + double value; + char choice; + + cout << "Enter a number: "; + value = inputVal(value); + cout << "This program will raise " << value; + cout << " to the pwers of 0 through 10.\n"; + for (int count = 0; count <= 10; count++) + { + cout << value << " raised to the power of "; + cout << count << " is " << pow(value, count); + cout << "\nEnter Q to quit or any other key "; + cout << "to continue. "; + cin >> choice; + if (choice == 'Q' || choice == 'q') + { + break; + } + } + return 0; +} + +//*************************************************** +// The inputVal function checks for validate input. * +// In this case a double. If an double is not * +// typed in, the user will be promted to enter * +// valid data. * +//*************************************************** + +double inputVal(double num) +{ + while (!(cin >> num)) + { + cout << "I'm sorry. A number must be entered: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-5-Loops-and-Files/5.12-Opt-Topics-Breaking-and-Continuing-a-Loop/5-26.cpp b/Chapter-5-Loops-and-Files/5.12-Opt-Topics-Breaking-and-Continuing-a-Loop/5-26.cpp new file mode 100644 index 0000000..d689a4e --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.12-Opt-Topics-Breaking-and-Continuing-a-Loop/5-26.cpp @@ -0,0 +1,92 @@ +//****************************************************** +// This program calculates the charges for DVD rentals. +// Every thrid DVD is free. +// +// By: Jesus Hilario Hernandez +// Last updated: Novermber 1, 2016 +//****************************************************** +#include +#include +using namespace std; + +int inputVal(int); // Input validation (int) +char inputVal2(char); // Input Valication (char) + +int main() +{ + int dvdCount = 1; // DVD counter + int numDVDs; // Number of DVDs rented + double total = 0.0; // Accumulator + char current; // Current release, (Y/N) + + // Get the number of DVDs. + cout << "How many DVDs are being rented? "; + numDVDs = inputVal(numDVDs); + + // Determine the charges. + do + { + if ((dvdCount % 3) == 0) + { + cout << "DVD #" << dvdCount << " is free!\n"; + continue; // Immediately start the newt iteration + } + cout << "Is DVD #" << dvdCount; + cout << " a current release? (Y/N) "; + cin >> current; + current = inputVal2(current); + if (current == 'Y' || current == 'y') + { + total += 3.50; + } + else + { + total += 2.50; + } + } while (dvdCount++ < numDVDs); + + // Display the total. + cout << fixed << showpoint << setprecision(2); + cout << "The total is $" << total << endl; + return 0; +} + +//*************************************************** +// The inputVal function checks for validate input. * +// In this case an integer. If an integer is not * +// typed in, the user will be promted to enter * +// valid data. * +//*************************************************** + +int inputVal(int num) +{ + while (!(cin >> num)) + { + cout << "I'm sorry. A number must be entered: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} + +//*************************************************** +// The inputVal function checks for validate input. * +// In this case the letters Y or N. If neither is * +// typed in, the user will be promted to input * +// the valid data. * +//*************************************************** + +char inputVal2(char letter) +{ + while(!(letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N')) + { + cout << "\n\t\tError: choose either Y or N."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + // Re-enter input + cin >> letter; + } + return letter; +} diff --git a/Chapter-5-Loops-and-Files/5.2-Intro-to-Loops-The-While-Loop/Examples/5-3.cpp b/Chapter-5-Loops-and-Files/5.2-Intro-to-Loops-The-While-Loop/Examples/5-3.cpp new file mode 100644 index 0000000..8377727 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.2-Intro-to-Loops-The-While-Loop/Examples/5-3.cpp @@ -0,0 +1,24 @@ +//************************************************ +// This program demonstrates a simple while loop +// +// By: Jesus Hilario Hernandez +// Last Updated: December 29, 2016 +// +// Used from: Gaddis, "Starting Out With C++", +// 8th Edition, Pg 234 +//************************************************ +#include +using namespace std; + +int main() +{ + int number = 0; + + while (number < 5) + { + cout << "Hello\n"; + number++; + } + cout << "That's all!\n"; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.2-Intro-to-Loops-The-While-Loop/Examples/5-4.cpp b/Chapter-5-Loops-and-Files/5.2-Intro-to-Loops-The-While-Loop/Examples/5-4.cpp new file mode 100644 index 0000000..5c7db00 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.2-Intro-to-Loops-The-While-Loop/Examples/5-4.cpp @@ -0,0 +1,40 @@ +//*************************************************** +// This program assists a technician in the process +// of checking a substance's temperature. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 29, 2016 +// +// Used from: Gaddis, "Starting Out With C++", +// 8th Edition, Pg.238 +//*************************************************** +#include +using namespace std; + +int main() +{ + const double MAX_TEMP = 102.5; // Maximum temperature + double temperature; // To hold the temperature + + // Get the current temperature. + cout << "Enter the substance's Celsius temperature: "; + cin >> temperature; + + // As long as necessary, instruct the technician + // to adjust the thermostat. + while (temperature > MAX_TEMP) + { + cout << "The temperature is too high. Turn the\n"; + cout << "thermostat down and wait 5 minutes.\n"; + cout << "The take the celsius temperature again\n"; + cout << "and enter it here: "; + cin >> temperature; + } + + // Remind the technician to check the temperature + // again in 15 minutes. + cout << "The temperature is acceptable.\n"; + cout << "Check it again in 15 minutes.\n"; + + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.3-Using-While-Loop-for-Input-Validation/Checkpoint/5.2-5.4.cpp b/Chapter-5-Loops-and-Files/5.3-Using-While-Loop-for-Input-Validation/Checkpoint/5.2-5.4.cpp new file mode 100644 index 0000000..beed665 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.3-Using-While-Loop-for-Input-Validation/Checkpoint/5.2-5.4.cpp @@ -0,0 +1,88 @@ +/******************************************************************** +* +* 5.2 Write an input validation loop that asks the user to +* enter a number in the range of 10 through 25. +* +* 5.3 Write an input validation loop that asks the user to +* enter‘Y’, ‘y’, ‘N’, or ‘n’. +* +* 5.4 Write an input validation loop that asks the user to +* enter “Yes†or “Noâ€. +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + /**************************************************** + * (5.2) * + * Write an input validation loop that asks the * + * user to enter a number in the range of 10 * + * through 25. * + * * + ****************************************************/ + + // Variables + int number; + + // Ask for (number) + cout << "Enter a number in the range of 10-25: "; + cin >> number; + + // Validate (number) + while (number < 10 || number > 25) + { + cout << "ERROR: Enter a value in the range 10-25. "; + cin >> number; + } + + /**************************************************** + * (5.3) * + * Write an input validation loop that asks the * + * user to enter‘Y’, ‘y’, ‘N’, or ‘n’. * + * * + ****************************************************/ + + // Variables + char user_letter; + + // Ask for (user_letter) + cout << "Enter yes or no (y/n): "; + cin >> user_letter; + + // Validate (user_letter) + while (user_letter != 'Y' && user_letter != 'y' && user_letter != 'N' && user_letter != 'n') + { + cout << "ERROR: Enter either 'Y' or 'N'."; + cin >> user_letter; + } + + /**************************************************** + * (5.4) * + * Write an input validation loop that asks the * + * user to enter “Yes†or “Noâ€. * + * * + ****************************************************/ + // Variables + string user_answer; + + // Ask for (user_answer) + cout << "Enter \"Yes\" or \"No\": "; + cin >> user_answer; + + // Validate (user_answer) + while (user_answer != "Yes" && user_answer != "yes" && user_answer != "no" && user_answer != "No") + { + cout << "ERROR: Enter either \"Yes\" or \"No\"."; + cin >> user_answer; + } + + // Terminate Program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.3-Using-While-Loop-for-Input-Validation/Examples/5-5.cpp b/Chapter-5-Loops-and-Files/5.3-Using-While-Loop-for-Input-Validation/Examples/5-5.cpp new file mode 100644 index 0000000..202011c --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.3-Using-While-Loop-for-Input-Validation/Examples/5-5.cpp @@ -0,0 +1,63 @@ +//**************************************************** +// This program calculates the number of soccer teams +// that a youth league may create from the number of +// available players. Input validation is demonstrated +// with while loops. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 1, 2017 +//**************************************************** +#include +using namespace std; + +int main() +{ + // Constants for minimum and maximum players + const int MIN_PLAYERS = 9, + MAX_PLAYERS = 15; + + // Variables + int players, // Number of available players + teamPlayers,// Number of desired players per team + numTeams, // Number of teams + leftOver; // Number of players left over + + // Get the number of players per team. + cout << "How many players do you wish per team? "; + cin >> teamPlayers; + + // Validate the input + while (teamPlayers < MIN_PLAYERS || teamPlayers > MAX_PLAYERS) + { + // Explain the error. + cout << "You should have at least " << MIN_PLAYERS + << " but no more than " << MAX_PLAYERS << " per team.\n"; + + // Get the input again. + cout << "How many players do you wish per team? "; + cin >> teamPlayers; + } + + // Get the number of players available. + cout << "How many players available? "; + cin >> players; + + // Validate the input + while (players <= 0) + { + // Get the input again. + cout << "Please enter 0 or greater: "; + cin >> players; + } + + // Calculate the number of teams. + numTeams = players / teamPlayers; + + // Calculate the number of leftover players. + leftOver = players % teamPlayers; + + // Display the results. + cout << "There will be " << numTeams << " teams with " + << leftOver << " players left over.\n"; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.4-Counters/Examples/5-6.cpp b/Chapter-5-Loops-and-Files/5.4-Counters/Examples/5-6.cpp new file mode 100644 index 0000000..6f3a9c6 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.4-Counters/Examples/5-6.cpp @@ -0,0 +1,26 @@ +//********************************************* +// This program displayes a list of number and +// their squares. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 1, 2017 +//********************************************* +#include +using namespace std; + +int main() +{ + const int MIN_NUMBER = 1, // Starting number to square + MAX_NUMBER = 10; // Maximum number to square + + int num = MIN_NUMBER; // counter + + cout << "Number Number Squared\n"; + cout << "--------------------------\n"; + while (num <= MAX_NUMBER) + { + cout << num << "\t\t" << (num * num) << endl; + num++; // Increment the counter. + } + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Checkpoint/5.5.cpp b/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Checkpoint/5.5.cpp new file mode 100644 index 0000000..fbb087c --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Checkpoint/5.5.cpp @@ -0,0 +1,52 @@ +/******************************************************************** +* +* 5.5 What will the following program segments display? +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + // (A) // + // Variables + int count = 10; + + // Pretest loop + do + { + cout << "Hello World\n"; + count++; + } while (count < 1); // Hello World 1x + + + // (B) // + // Variables + int v = 10; + + // Pretest loop + do + cout << v << endl; + while (v < 5); // 10 1x + + + // (C) // + // Variables + int count_2 = 0, number = 0, limit = 4; + + // Pretest loop (user controlled loop) + do + { + number += 2; + count_2++; + } while (count_2 < limit); + cout << number << " " << count_2 << endl; // 8 4 + + // Terminate Program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Examples/5-7.cpp b/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Examples/5-7.cpp new file mode 100644 index 0000000..ece0cf2 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Examples/5-7.cpp @@ -0,0 +1,32 @@ +//**************************************************** +// This program averages 3 test scores. It repeats as +// many times as the user wishes. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 1, 2017 +//**************************************************** +#include +using namespace std; + +int main() +{ + int score1, score2, score3; // Three scores + double average; // Average scores + char again; // To hold Y or N + + do + { + // Get three scores. + cout << "Enter 3 scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average. + average = (score1 + score2 + score3) / 3.0; + cout << "The average is " << average << ".\n"; + + // Does the user want to average another set? + cout << "Do you want to average another set? (Y/N)"; + cin >> again; + } while (again == 'Y' || again == 'y'); + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Examples/5-8.cpp b/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Examples/5-8.cpp new file mode 100644 index 0000000..9d6348c --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.5-Do-While-Loop/Examples/5-8.cpp @@ -0,0 +1,79 @@ +//*************************************************** +// This program displays a menu and asks the user +// to make a selection. A do-while loop repeats the +// program until the user selects item 4 from the +// menu. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 1, 2017 +//**************************************************** +#include +#include +using namespace std; + +int main() +{ + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Constants for membership rates + const double ADULT = 40.0, + CHILD = 20.0, + SENIOR = 30.0; + + // Variables + int choice; // Menu choices + int months; // Number of months + double charges; // Monthly charges + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu. + cout << "\n\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; + cin >> choice; + + // Validate the menu selection. + while (choice < ADULT_CHOICE || choice > QUIT_CHOICE) + { + cout << "Please enter a valid menu choice: "; + cin >> choice; + } + + // Process the user's choice. + if (choice != QUIT_CHOICE) + { + // Get the number of months. + cout << "For how many months?"; + cin >> months; + + // Respond to the user's manu selection. + switch (choice) + { + case ADULT_CHOICE: + charges = months * ADULT; + break; + case CHILD_CHOICE: + charges = months * CHILD; + break; + case SENIOR_CHOICE: + charges = months * SENIOR; + } + + // Display the monthly charges. + cout << "The total charges are $" + << charges << endl; + } + } while (choice != QUIT_CHOICE); + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Checkpoint/5.6-5.11.cpp b/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Checkpoint/5.6-5.11.cpp new file mode 100644 index 0000000..8465d61 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Checkpoint/5.6-5.11.cpp @@ -0,0 +1,115 @@ +/******************************************************************** +* +* 5.6 - 5.11 +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + /**************************************************** + * (5.6) * + * Name the three expressions that appear inside * + * the parentheses in the for loop's header. * + * * + ****************************************************/ + // ANSWER: + // for (initialization, test, update) + + /**************************************************** + * (5.7) * + * You want to write a for loop that displays "I * + * love to program" 50 times. Assume that you will * + * use a counter variable named (count). * + * * + ****************************************************/ + // A) What initialization expression will you use? + // ANSWER: count = 1; + + // B) What test expression will you use? + // ANSWER: count <= 50; + + // C) What update expression will you use? + // ANSWER: count++; + + // D) Write the loop. + for (int count = 1; count <= 50; count++) + cout << count << ". I love to program" << endl; + + /**************************************************** + * (5.8) * + * What will the following program segments * + * display? + * * + ****************************************************/ + /******* + * A. * + *******/ + for (int count = 0; count < 6; count++) + cout << (count + count); + + // ANSWER: + // 0246810 + + /******* + * B. * + *******/ + for (int value = -5; value < 5; value++) + cout << value; + + // ANSWER: + // -5-4-3-2-101234 + // Line break + cout << endl; + + + /******* + * C. * + *******/ + int x; + for (x = 5; x <= 14; x += 3) + cout << x << endl; + cout << x << endl; + + // ANSWER: + // 5 + // 8 + // 11 + // 14 + // 17 + + /**************************************************** + * (5.9) * + * write a for loops that displays your name * + * 10 times. * + ****************************************************/ + for (int i = 1; i <= 10; i++) + cout << i << ". Jesus Hilaro Hernandez" << endl; + + /**************************************************** + * (5.10) * + * Write a for loop that displays all of the odd * + * numbers, 1 through 49. * + ****************************************************/ + for (int i = 1; i <= 49; i += 2) + cout << i << ". Odd numbers." << endl; + + /**************************************************** + * (5.11) * + * Write a for loop that displays every fifth * + * number, zero through 100. * + ****************************************************/ + for (int i = 0; i <= 100; i += 5) + cout << i << ". Every 5th number through 0 and 100." << endl; + + + + // Terminate Program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-10.cpp b/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-10.cpp new file mode 100644 index 0000000..f6193a3 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-10.cpp @@ -0,0 +1,34 @@ +//************************************************* +// This program demonstrates a user controlled for +// loop. +// +// By: Jesus Hilario HERNANDEZ +// Last Updated: January 10, 2017 +//************************************************** +#include +using namespace std; + +int main() +{ + int minNumber, // Starting number to square + maxNumber; // Maximum number to square + + // Get the minimum and maximum values to display. + cout << "I will display a table of numbers and " + << "their squares.\n" + << "Enter the starting number: "; + cin >> minNumber; + cout << "Enter the ending number: "; + cin >> maxNumber; + + // Display the table. + cout << "Number Number Squared\n" + << "--------------------------\n"; + + for (int num = minNumber; num <= maxNumber; num++) + { + cout << num << "\t\t" << (num * num) << endl; + } + + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-11.cpp b/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-11.cpp new file mode 100644 index 0000000..790db91 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-11.cpp @@ -0,0 +1,44 @@ +//************************************** +// This program converts the speeds 60 +// kph through 130 kph (in 10 kph +// increments) to mph. +// +// By : Jesus Hilario Hernandez +// Last Updated: January 10, 2017 +//************************************** +#include +#include +using namespace std; + +int main() +{ + // Constants for the speeds + const int START_KPH = 60, // Starting speed + END_KPH = 130, // Ending speed + INCREMENT = 10; // Speed INCREMENT + + // Constants for the conversion factor + const double CONVERSION_FACTOR = 0.6214; + + // Variables + int kph; // To hold speeds in kph + double mph; // To hold speeds in mph + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Display the table headings. + cout << "KPH\tMPH\n"; + cout << "---------------\n"; + + // Display the speeds. + for (kph = START_KPH; kph <= END_KPH; kph += INCREMENT) + { + // Calculate mph + mph = kph * CONVERSION_FACTOR; + + // Display the speeds in kph and mph. + cout << kph << "\t" << mph << endl; + } + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-9.cpp b/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-9.cpp new file mode 100644 index 0000000..908c803 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.6-The-For-Loop/Examples/5-9.cpp @@ -0,0 +1,27 @@ +//************************************* +// This program displays the number 1 +// through 10 and their squares. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 1, 2017 +// Used from Gaddis, "Starting out with C++", +// 8th Edition, Pg 249 +//************************************* +#include + using namespace std; + + int main() + { + const int MIN_NUMBER = 1, // Starting value + MAX_NUMBER = 10; // Ending value + int num; + + cout << "Number Number Squared\n"; + cout << "------------------------\n"; + + for (num = MIN_NUMBER; num <= MAX_NUMBER; num++) + { + cout << num << "\t\t" << (num * num) << endl; + } + return 0; + } diff --git a/Chapter-5-Loops-and-Files/5.7-Keeping-Running-Total/Examples/5-12.cpp b/Chapter-5-Loops-and-Files/5.7-Keeping-Running-Total/Examples/5-12.cpp new file mode 100644 index 0000000..3db0abd --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.7-Keeping-Running-Total/Examples/5-12.cpp @@ -0,0 +1,34 @@ +//*********************************************** +// This program takes daily sales figures over a +// period of time and calculates their total. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 10, 2017 +//*********************************************** +#include +#include +using namespace std; + +int main() +{ + int days; // Number of days + double total = 0.0; // Accumulator, initialized with 0. + + // Get the number of days. + cout << "for how many days do you have sales figures? "; + cin >> days; + + // Get the sales for each day and accumulate a total. + for (int count = 1; count <= days; count++) + { + double sales; + cout << "Enter the sales for day " << count << ": "; + cin >> sales; + total += sales; // Accumulate the running total + } + + // Display the total sales. + cout << fixed << showpoint << setprecision(2); + cout << "The total sales are $" << total << endl; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.8-Sentinels/Checkpoint/5.12-5.15.cpp b/Chapter-5-Loops-and-Files/5.8-Sentinels/Checkpoint/5.12-5.15.cpp new file mode 100644 index 0000000..2a94d86 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.8-Sentinels/Checkpoint/5.12-5.15.cpp @@ -0,0 +1,110 @@ +/******************************************************************** +* +* 5.12 - 5.15 +* +* Jesus Hilario Hernandez +* February 28, 2018 +* +********************************************************************/ +#include +#include + +using namespace std; + +int main() +{ + /**************************************************** + * (5.12) * + * Write a for loop that repeats seven times, * + * asking the user to enter a number. The loop * + * should also calculate the sum of the numbers * + * entered. * + * * + ****************************************************/ + // Variables + double total_of_7_nums = 0; + int number; + for (int i = 1; i <= 7; i++) + { + cout << "Enter a Number: "; + cin >> number; + total_of_7_nums += number; + } + cout << "Sum of all numbers = " << total_of_7_nums << endl; + + + + /**************************************************** + * (5.13) * + * In the following program segment, which * + * variable and which is the accumulator? * + * * + ****************************************************/ + + // Variables + int a, x, y = 0; + for (x = 0; x < 10; x++) + { + cout << "Enter a number: "; + cin >> a; + y += a; + } + cout << "The sum of those numbers is " << y << endl; + + // ANSWER: y + + + + /**************************************************** + * (5.14) * + * * + * Why should you be careful when choosing a * + * sentinel value? * + * * + ****************************************************/ + // ANSWER: Be sure that the sentinel value is not part of a + // list of number used. Or that it is not part of the + // running total. + + + + /*************************************************** + * (5.15) * + * * + * How would you modify Program 5-13 so any * + * negative value is a sentinel? * + * * + ****************************************************/ + // Variables + int c, d, f = 0; + + cout << "Enter a number: "; + cin >> c; + + // pretest loop (any negative value [sentinel]) + while (c > 0) + { + f += c; + cout << "Enter a number: "; + cin >> c; + } + + cout << "The sum of those numbers is " << f << endl; + + + // Variables + int r = 0, s, t = 0; + + // Or + do + { + t += r; + cout << "Enter a number: "; + cin >> r; + } while (r > 0); + + cout << "Total sum of number is " << t << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.8-Sentinels/Examples/5-13.cpp b/Chapter-5-Loops-and-Files/5.8-Sentinels/Examples/5-13.cpp new file mode 100644 index 0000000..026b1e5 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.8-Sentinels/Examples/5-13.cpp @@ -0,0 +1,32 @@ +//********************************************************** +// This program calculates the total number of points a +// soccer team has earned over a series of games. The user +// enters a series of point values, then -1 when finished. +// +// By: Jesus Hilario Hernandez +// Last Updated: January 10, 2017 +//********************************************************** +#include +using namespace std; + +int main() +{ + int game = 1, // Game counter + points, // To hold a number of points + total = 0; // Accumulator + + cout << "Enter the number of points your team has earned\n"; + cout << "so far in the season, then enter -1 when finished.\n\n"; + cout << "Enter the points for game " << game << ": "; + cin >> points; + + while (points != -1) + { + total += points; + game++; + cout << "Enter the points for game " << game << ": "; + cin >> points; + } + cout << "\nThe total points are " << total << endl; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/5.9-Focus-On-Software-Egineering-Deciding-Which-Loop-To-Use/Deciding-Which-Loop-To-Use.txt b/Chapter-5-Loops-and-Files/5.9-Focus-On-Software-Egineering-Deciding-Which-Loop-To-Use/Deciding-Which-Loop-To-Use.txt new file mode 100644 index 0000000..3a53307 --- /dev/null +++ b/Chapter-5-Loops-and-Files/5.9-Focus-On-Software-Egineering-Deciding-Which-Loop-To-Use/Deciding-Which-Loop-To-Use.txt @@ -0,0 +1,37 @@ +CONCEPT: Although most repetitive algorithms can be written with any of the + three types of loops, each works best in different situations. + + The ideal to use in different situations: + + 1. - The (while) loop. The (while) loop is a conditional loop, which means + it repeats as long as a particular condit exists. It is also a pretest + loop, so it is + + IDEAL in situations where you do not want to loop to + iterate if the condition is false from the beginning. + + For example, validating input that has been read and reading lists of + data terminated by a sentinel value are good applications of the + (while) loop. + + + + 2. - The (do-while) loop. The (do-while) loop is also a conditional loop. + (while) loop, however, (do-while) is a posttest loop. It is + + IDEAL in situations where you always want the loop to iterate at least + once. The (do-while) loop is a good choice for repeating a menu. + + + + 3. - The (for) loop. The (for) loop is a pretest loop that has built-in + expressions for initializing, testing, and updating. These expressions + make it very convenient to use counter variable to control the number + of iterations that the loop performs. The initialization expression + can initialize the counter variable to a starting value, the test + expression can test the counter variable to determine whether it holds + the maximum value, and the update expression can increment the counter + variable. The (for) loop is + + IDEAL in situations where the exact number + of iterations is known. diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/35.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/35.cpp new file mode 100644 index 0000000..800c257 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/35.cpp @@ -0,0 +1,35 @@ +/******************************************************************** +* +* 35. +* Write a while loop that lets the user enter a number. +* The number should be multiplied by 10, and the result +* stored in the variable product. The loop should +* iterate as long as product contains a value less than 100. +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + int num, // User number + product = 0; // Accumulator + + // While running total is less than 100. + while (product < 100) + { + // Ask for number + cout << "Enter a number: "; + cin >> num; + product += num; + } + + // Check running total (product) + cout << "product = " << product << endl << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/36.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/36.cpp new file mode 100644 index 0000000..0e03dc6 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/36.cpp @@ -0,0 +1,48 @@ +/******************************************************************** +* +* 36. +* Write a (do-while loop) that asks the user to enter two +* numbers. The numbers should be added and the sum +* displayed. The user should be asked if he or she wishes to +* perform the operation again. If so, the loop should +* repeat; otherwise it should terminate. +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + int number_1, + number_2, + sum; // Sum of (number_1) && (number_2) + char another; // Yes or No (y/n) choice. + + // Ask user if wish to quit program. + do + { + // Ask for 2 numbers (number_1 & number_2) + cout << "Enter two numbers.\n"; + cout << "#1: "; + cin >> number_1; + cout << "#2: "; + cin >> number_2; + + // Caclculate the (sum) + sum = number_1 + number_2; + + // Display (sum) + cout << "Sum of #1 and #2 is " << sum << endl; + + // Ask user if repeat + cout << "Would you like to sum another 2 numbers? (Y/N)"; + cin >> another; + + } while(another == 'Y' || another == 'y'); + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/37.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/37.cpp new file mode 100644 index 0000000..66516e9 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/37.cpp @@ -0,0 +1,34 @@ +/******************************************************************** +* +* 37. +* Write a for loop that displays the following set of +* numbers: 0, 10, 20, 30, 40, 50 . . . 1000 +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + cout << endl; + + // Pretest loop, count-controlled loop, + for (int i = 0; i <= 1000; i += 10) + { + cout << i; + if (i != 1000) + { + cout << ", "; + + if (i % 120 == 0 && i != 0) + cout << endl; + } + } + + cout << '\n' << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/38.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/38.cpp new file mode 100644 index 0000000..ec08c8a --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/38.cpp @@ -0,0 +1,33 @@ +/******************************************************************** +* +* 38. +* Write a loop that asks the user to enter a number. +* The loop should iterate 10 times and keep a running +* total of the numbers entered. +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + int number, + total = 0; + + // Pretest loop, counter controlled loop (10) + for (int i = 1; i <= 10; i++) + { + // Ask for a number + cout << "Enter a number: "; + cin >> number; + total += number; + } + + // Display total + cout << "Total = is " << total << endl; + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/39.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/39.cpp new file mode 100644 index 0000000..e3734f8 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/39.cpp @@ -0,0 +1,37 @@ +/******************************************************************** +* +* 39. +* Write a nested loop that displays 10 rows of ‘#’ +* characters. There should be 15 ‘#’ characters in each +* row. +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + for (int i = 1; i <= 10; i++) + { + for (int j = 1; j <= 15; j++) + cout << "#"; + + cout << endl; + } + + cout << endl; + + // Alternative. Consider (Intialization & Test) + for (int row = 0; row < 10; row++) + { + for (int column = 0; column < 15; column++) + cout << "#"; + + cout << endl; + } + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/40.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/40.cpp new file mode 100644 index 0000000..2b6c162 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/40.cpp @@ -0,0 +1,32 @@ +/******************************************************************** +* +* 40. +* Convert the following while loop to a do-while loop: +* int x = 1; +* while (x > 0) +* { +* cout << "enter a number: "; +* cin >> x; +* } +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + int x = 1; + + // User controlled loop, posttest loop + do + { + cout << "Enter a number: "; + cin >> x; + } while(x > 0); + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/41.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/41.cpp new file mode 100644 index 0000000..4d91171 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/41.cpp @@ -0,0 +1,33 @@ +/******************************************************************** +* +* 41. +* Convert the following do-while loop to a while loop: +* +* char sure; +* do +* { +* cout << "Are you sure you want to quit? "; +* cin >> sure; +* } while (sure != 'Y' && sure != 'N'); +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + char sure; + + // While loop, Pretest loop, conditional loop + while (sure != 'Y' && sure != 'N') + { + cout << "Are you sure you want to quit?"; + cin >> sure; + } + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/42.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/42.cpp new file mode 100644 index 0000000..b56cc2d --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/42.cpp @@ -0,0 +1,28 @@ +/******************************************************************** +* +* 42. +* Convert the following while loop to a for loop: +* +* int count = 0; +* +* while (count < 50) +* { +* cout << "count is " << count << endl; +* count++; +* } +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // For loop, pretest loop, count controlled loop + for (int count = 0; count < 50; count++) + cout << "(count) is " << count << endl; + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/43.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/43.cpp new file mode 100644 index 0000000..2ea536c --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/43.cpp @@ -0,0 +1,30 @@ +/******************************************************************** +* +* 43. +* Convert the following for loop to a while loop: +* +* for (int x = 50; x > 0; x−−) +* { +* cout << x << " seconds to go.\n"; +* } +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + int x = 50; + + // While loop, condition controlled loop, pretest loop + while (x > 0) + { + cout << x << " seconds to go.\n"; + x--; + } + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/44.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/44.cpp new file mode 100644 index 0000000..b0d9fd5 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/44.cpp @@ -0,0 +1,34 @@ +/******************************************************************** +* +* 44. Write code that does the following: Opens an output file +* with the filename Numbers.txt, uses a loop to write the +* numbers 1 through 100 to the file, and then closes the file. +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +#include +using namespace std; + +int main() +{ + // Define file stream object for outputting data + ofstream output_file; + + // Open file "Numbers.txt" through file stream object (output_file) + output_file.open("Numbers.txt"); + + // (for loop), count controlled loop, pretest loop (1 - 100) + for (int i = 1; i <= 100; i++) + { + output_file << i << endl; + } + + // Close file "Numbers.txt" through file stream object (output_file) + output_file.close(); + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/45.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/45.cpp new file mode 100644 index 0000000..8b4b132 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/45.cpp @@ -0,0 +1,38 @@ +/******************************************************************** +* +* 45. Write code that does the following: Opens the Numbers.txt +* file that was created by the code you wrote in question 44, +* reads all of the numbers from the file and displays them, +* and then closes the file. +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +#include +using namespace std; +int main() +{ + // Create file stream object (input_file) + ifstream input_file; + + // Open "Numbers.txt" through file stream object (input_file) + input_file.open("Numbers.txt"); + + // Process information in "Numbers.txt", through file + // stream object (input_file), with a pretest, condition controlled, + // (while loop). + int i; + while (input_file >> i) + { + cout << i << endl; + } + + // Close "Numbers.txt" file through file stream object (input_file) + // with .close() function. + input_file.close(); + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/46.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/46.cpp new file mode 100644 index 0000000..e2a4698 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/46.cpp @@ -0,0 +1,37 @@ +/******************************************************************** +* +* 46. Modify the code that you wrote in question 45 so it adds +* all of the numbers read from the file and displays their +* total. +* +* Jesus Hilario Hernandez +* March 10th 2018 +* +********************************************************************/ +#include +#include +using namespace std; +int main() +{ + // Define input stream object + ifstream input_file; + // Variables + int number, // number from file "Numbers.txt" + total = 0; // total of all numbers in "Numbers.txt" + + // Open "Numbers.txt" through input file stream object (input_file) + input_file.open("Numbers.txt"); + + // Process file using a while loop + while (input_file >> number) + total += number; + + // Display total + cout << "\nTotal = " << total << '\n' << endl; + + // Close "Numbers.txt" file with .close() function + input_file.close(); + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/Numbers.txt b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/Numbers.txt new file mode 100644 index 0000000..190423f --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Algorithm Workbench/Numbers.txt @@ -0,0 +1,100 @@ +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Fill-in-the-Blank/16-34.txt b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Fill-in-the-Blank/16-34.txt new file mode 100644 index 0000000..e1333f7 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Fill-in-the-Blank/16-34.txt @@ -0,0 +1,46 @@ +<-- Fill-in-the-Blank --> + +16. To __(increment)__ a value means to increase it by one, and to __(decrement)__ a value means +to decrease it by one. + +17. When the increment or decrement operator is placed before the operand (or to the +operand’s left), the operator is being used in __(prefix mode)__ mode. + +18. When the increment or decrement operator is placed after the operand (or to the oper- +and’s right), the operator is being used in __(postfix mode)__ mode. + +19. The statement or block that is repeated is known as the __(body)__ of the loop. + +20. Each repetition of a loop is known as a(n) __(iteration)__. + +21. A loop that evaluates its test expression before each repetition is a(n) __(pretest)__ loop. + +22. A loop that evaluates its test expression after each repetition is a(n) __(posttest)__ loop. + +23. A loop that does not have a way of stopping is a(n) __(infinite)__ loop. + +24. A(n) __(counter)__ is a variable that “counts†the number of times a loop repeats. + +25. A(n) __(running total)__ is a sum of numbers that accumulates with each iteration of a loop. + +26. A(n) __(counter)__ is a variable that is initialized to some starting value, usually zero, +and then has numbers added to it in each iteration of a loop. + +27. A(n) __(sentinel)__ is a special value that marks the end of a series of values. + +28. The __(posttest)__ loop always iterates at least once. + +29. The __(for)__ and __(while)__ loops will not iterate at all if their test expressions +are false to start with. + +30. The __(for)__ loop is ideal for situations that require a counter. + +31. Inside the for loop’s parentheses, the first expression is the __(initialization)__ , the second +expression is the __(test)__ , and the third expression is the __(update)__. + +32. A loop that is inside another is called a(n) __(nested)__ loop. + +33. The __(break)__ statement causes a loop to terminate immediately. + +34. The __(continue)__ statement causes a loop to skip the remaining statements in the cur- +rent iteration. diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/00.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/00.cpp new file mode 100644 index 0000000..d24c0f0 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/00.cpp @@ -0,0 +1,8 @@ +/******************************************************************** +* +* 00. Find as many errors as you can. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/65.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/65.cpp new file mode 100644 index 0000000..237175b --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/65.cpp @@ -0,0 +1,22 @@ +/******************************************************************** +* +* 65. Find as many errors as you can. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + int num1 = 0, + num2 = 10, + result; + + num1++; + // result = ++(num1 + num2); // Error + result = 1 + (num1 + num2); // Correction + cout << num1 << " " << num2 << " " << result; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/65_error.png b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/65_error.png new file mode 100644 index 0000000..c565cb0 Binary files /dev/null and b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/65_error.png differ diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/66.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/66.cpp new file mode 100644 index 0000000..4c6a011 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/66.cpp @@ -0,0 +1,44 @@ +/******************************************************************** +* +* 66. Find as many errors as you can. +* // This program adds two numbers entered by the user +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + int num1, num2; + char again; + + // ERROR: NO CURLY BRACES TO ENCAPSULATE LOOP'S BODY + /* + while (again == 'y' || again == 'Y') + cout << "Enter a number: "; + cin >> num1; + cout << "Enter another number: "; + cin >> num2; + cout << "Their sum is << (num1 + num2)" << endl; + cout << "Do you want to do this again? "; + cin >> again; + */ + + + // CORRECTION: ADDED CURLY BRACES + while (again == 'y' || again == 'Y') + { + cout << "Enter a number: "; + cin >> num1; + cout << "Enter another number: "; + cin >> num2; + cout << "Their sum is << (num1 + num2)" << endl; + cout << "Do you want to do this again? "; + cin >> again; + } + + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/67.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/67.cpp new file mode 100644 index 0000000..eeaeaea --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/67.cpp @@ -0,0 +1,53 @@ +/******************************************************************** +* +* 00. Find as many errors as you can. +* // This program uses a loop to raise a number to a power. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; + +int main() +{ + // ERROR: + /* + int num, bigNum, power, count; + + cout << "Enter an integer: "; + cin >> num; + cout << "What power do you want it raised to? "; + cin >> power; + bigNum = num; + while (count++ < power); + bigNum *= num; + cout << "The result is << bigNum << endl; + return 0; + */ + + // CORRECTION: + int num, + bigNum, + power, + count = 1; // Initialize to 1 + + cout << "Enter an integer: "; + cin >> num; + cout << "What power do you want it raised to? "; + cin >> power; + bigNum = num; + while (count++ < power) // Removed (;) semicolon + bigNum *= num; + cout << "The result is " << bigNum << endl; // Added (") character + + + + // Alternative (for) loop, user controlled loop, for processing + for ( ; count < power; count++) + bigNum *= num; + + cout << "The result is " << bigNum << endl; + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/67_error.png b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/67_error.png new file mode 100644 index 0000000..655d73e Binary files /dev/null and b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/67_error.png differ diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/68.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/68.cpp new file mode 100644 index 0000000..85a7815 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/68.cpp @@ -0,0 +1,50 @@ +/******************************************************************** +* +* 68. Find as many errors as you can. + // This program averages a set of numbers. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // ERROR: + /* + int numCount, total; + double average; + cout << "How many numbers do you want to average? "; + cin >> numCount; + for (int count = 0; count < numCount; count++) + { + int num; + cout << "Enter a number: "; + cin >> num; + total += num; + count++; + } + average = total / numCount; + cout << "The average is << average << endl; + return 0; + */ + + // CORRECTION: + int numCount, + total = 0; // Initialized (total) with 0. + double average; + cout << "How many numbers do you want to average? "; + cin >> numCount; + for (int count = 0; count < numCount; count++) + { + int num; + cout << "Enter a number: "; + cin >> num; + total += num; + // count++; Removed this line + } + average = (static_cast(total) / numCount); // Static casted total + cout << "The average is " << average << endl; // Added (") character + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/68_error.png b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/68_error.png new file mode 100644 index 0000000..c584133 Binary files /dev/null and b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/68_error.png differ diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/69.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/69.cpp new file mode 100644 index 0000000..1f2305f --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/69.cpp @@ -0,0 +1,45 @@ +/******************************************************************** +* +* 69. Find as many errors as you can. +* // This program displays the sum of two numbers. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // ERROR + /* + int choice, num1, num2; + do + { + cout << "Enter a number: "; + cin >> num1; + cout << "Enter another number: "; + cin >> num2; + cout << "Their sum is " << (num1 + num2) << endl; + cout << "Do you want to do this again?\n"; + cout << "1 = yes, 0 = no\n"; + cin >> choice; + } while (choice = 1) + return 0; + */ + + // CORRECTION: + int choice, num1, num2; + do + { + cout << "Enter a number: "; + cin >> num1; + cout << "Enter another number: "; + cin >> num2; + cout << "Their sum is " << (num1 + num2) << endl; + cout << "Do you want to do this again?\n"; + cout << "1 = yes, 0 = no\n"; + cin >> choice; + } while (choice == 1); // Added (;) semicolon and changed (=) to (==). + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/69_error.png b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/69_error.png new file mode 100644 index 0000000..da3d3d4 Binary files /dev/null and b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/69_error.png differ diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/70.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/70.cpp new file mode 100644 index 0000000..2c46fd0 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Find the Errors/70.cpp @@ -0,0 +1,42 @@ +/******************************************************************** +* +* 70. Find as many errors as you can. +* // This program displays the sum of the numbers 1-100. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // ERROR: + /* + int count = 1, total; + while (count <= 100) + total += count; + cout << "The sum of the numbers 1-100 is "; + cout << total << endl; + return 0; + */ + + // CORRECTION: + int count = 1, total = 0; + while (count <= 100) // Added curly braces...Multiple lines in body. + { + total += count; + count++; // incremented counter variable (count) + } + cout << "The sum of the numbers 1-100 is "; + cout << total << endl; + + // Alternative counter controlled (for) loop. + for ( ; count <= 100; count++) + total += count; + cout << "The sum of the numbers 1-100 is "; + cout << total << endl; + + // Terminat Program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/000.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/000.cpp new file mode 100644 index 0000000..d24c0f0 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/000.cpp @@ -0,0 +1,8 @@ +/******************************************************************** +* +* 00. Find as many errors as you can. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/001.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/001.cpp new file mode 100644 index 0000000..a117d38 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/001.cpp @@ -0,0 +1,46 @@ +/******************************************************************** +* +* 001. SUM OF NUMBERS +* +* Write a program that asks the user for a positive integer +* value. The program should use a loop to get the sum of +* all the integers from 1 up to the number entered. For +* example, if the user enters 50, the loop will find the +* sum of 1, 2, 3, 4, ... 50. +* +* Input Validation: Do not accept a negative starting number. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + int positive_num, // User input + total = 0; // Initialize total + + // Ask user for a positive integer value + cout << "\nEnter a positive number: "; + cin >> positive_num; + + // Validate (positive_num) + while (positive_num < 0) + { + cout << "ERROR: a positive number must be chosen" << endl; + cout << "Enter a positive number: "; + cin >> positive_num; + } + + // Sum all numbers from 1 to (positive_num) + for (int i = 1; i <= positive_num; i++) + { + total += i; + } + + // Display total + cout << "Total = " << total << endl; + cout << endl; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/002.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/002.cpp new file mode 100644 index 0000000..10a5b2b --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/002.cpp @@ -0,0 +1,35 @@ +/******************************************************************** +* +* 02. Characters for the ASCII Codes +* +* Write a program that uses a loop to display the +* characters for the ASCII codes 0 through 127. Display 16 +* characters on each line. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Variables + char ascii_code_number; + + // Display ASCII codes 0 through 127 + for (int i = 0; i <= 127; i++) + { + ascii_code_number = i; + cout << ascii_code_number << " "; + + if (i % 16 == 0) + cout << endl; + } + + // Line break; + cout << endl; + + // Terminate Program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp new file mode 100644 index 0000000..79ae537 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp @@ -0,0 +1,38 @@ +/******************************************************************** +* +* 003. Ocean Levels +* +* Assuming the ocean’s level is currently rising at +* about 1.5 millimeters per year, write a program that +* displays a table showing the number of +* millimeters that the ocean will have risen each year for +* the next 25 years. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Constants + const float MIL_PER_YEAR = 1.5; // 1.5 millimeters per year. + + // Variables + float num_of_mil_each_year = 0; // Initialize counter. + + + // Display a table of mil risen each year (25 years) + cout << "--------------------------------------------------\n"; + for (int i = 1; i <= 25; i++) + { + num_of_mil_each_year += MIL_PER_YEAR; + cout << "Year " << i << ": " << num_of_mil_each_year << endl; + } + cout << "--------------------------------------------------\n"; + + + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/004.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/004.cpp new file mode 100644 index 0000000..ba990ab --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/004.cpp @@ -0,0 +1,34 @@ +/******************************************************************** +* +* 004. Calories Burned +* +* Running on a particular treadmill you burn 3.6 calories +* per minute. Write a program that uses a loop to display +* the number of calories burned after 5, 10, 15, 20, 25, +* and 30 minutes. +* +* Jesus Hilario Hernandez +* March 13th 2018 +* +********************************************************************/ +#include +using namespace std; +int main() +{ + // Constants + const float CALS_BURNED_PER_MIN = 3.6; + // Variables + float calories_burned = 0; + + // Display calories burned after 5, 10, 15, 20, 25, and 30 mins. + for (int i = 5; i <= 30; i += 5) + { + // Calories burned for (i) minutes. + calories_burned = (i * CALS_BURNED_PER_MIN); + + // Display (calories_burned). + cout << "Calories burned after " << i << " minutes = " << calories_burned << endl; + } + // Terminate program + return 0; +} diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/005.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/005.cpp new file mode 100644 index 0000000..49b27d5 --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/005.cpp @@ -0,0 +1,15 @@ +/******************************************************************** +* +* 05. Membership Fees Increase +* +* A country club, which currently charges $2,500 per year +* for membership, has announced it will increase its +* membership fee by 4% each year for the next six years. +* Write a program that uses a loop to display the +* projected rates for the next six years. +* +* Jesus Hilario Hernandez +* March 12th 2018 +* +********************************************************************/ +dsf diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Short Answer/01-15.txt b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Short Answer/01-15.txt new file mode 100644 index 0000000..12d08ca --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Short Answer/01-15.txt @@ -0,0 +1,137 @@ +<-- Short Answer --> + +1. Why should you indent the statements in the body of a loop? + +ANSWER: You indent the statements within the body of a loop so that your program + becomes more readable, they stand out visually. The body of the loop + is visually set apart from the surrounding code. + + + + +2. Describe the difference between pretest loops and posttest loops. + +ANSWER: A pretest loop evaluates the test expression before it's initial + iteration. A posttest loop evaluates the test expression after + it's initial iteration. A posttest loop iterates at least once, + then the expression is tested. + + + + +3. Why are the statements in the body of a loop called conditionally executed statements? + +ANSWER: The statements within the body of a loop are called conditionally + executed statements because they are performed only when the expression + within the paretheses is true. + + + + +4. What is the difference between the while loop and the do-while loop? + +ANSWER: The (while) loop is iterated through as long as it's expression is true. + The do-while loop is iterated through at least once, then it's + expression is tested. + + + + +5. Which loop should you use in situations where you wish the loop to repeat +until the test expression is false, and the loop should not execute if the test +expression is false to begin with? + +ANSWER: I'll use a (while) loop if I want the loop to repeat until the test + expression is false, and if I want the loop to not execute at all if + the test expression is fals to begin with. + + + + +6. Which loop should you use in situations where you wish the loop to repeat until the +test expression is false, but the loop should execute at least one time? + +ANSWER: I'll use a (do-while) loop when I want the loop to exicute at least once + and to iterate until the test expression is false. + + + +7. Which loop should you use when you know the number of required iterations? + +ANSWER: I'll use a (for) loop when I know the number of iterations are required. + + + + +8. Why is it critical that counter variables be properly initialized? + +ANSWER: Is is critial because variables defined within a function have no + guaranteed starting value. + + + + +9. Why is it critical that accumulator variables be properly initialized? + +ANSWER: It is critical that the accumulator variable be properly initialzed + to 0 so that it will contain the correct total when the loop ends. + + + + +10. Why should you be careful not to place a statement in the body of a for loop that +changes the value of the loop’s counter variable? + +ANSWER: If the counter variable is modified within the body of a loop, the loop + may not terminate when you expect it to. + + + + +11. What header file do you need to include in a program that performs file operations? + +ANSWER: The header file needs to be included in order to perform file + operations. + + + + +12. What data type do you use when you want to create a file stream object that + can write data to a file? + +ANSWER: I'll use the (ofstream) data type when I want to create a file stream + object that can write data to a file. + + + + +13. What data type do you use when you want to create a file stream object that + can read data from a file? + +ANSWER: I'll use the (ifstream) data type when I want to create a file stream + object that can read data to a file. + + + + +14. Why should a program close a file when it’s finished using it? + +ANSWER: Closing a file causes unsaved data that is still in the buffer to be + saved to it's file. Because of this data in the file will be in the file + if you need to read it later in the same program. Close file for saving + data still in the buffer, in case you need to read it later in then same + program. + + + + +15. What is a file’s read position? Where is the read position when a file is + first opened for reading? + +ANSWER: a). The read position marks the location of the next byte that will be + read from the file. + + b). When an input file is opened, its read position is set to the first + byte in the file... + + c). The first read operation extracts data starting at the first byte. diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/True or False/47-64.txt b/Chapter-5-Loops-and-Files/Review Questions and Exercises/True or False/47-64.txt new file mode 100644 index 0000000..730eddf --- /dev/null +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/True or False/47-64.txt @@ -0,0 +1,119 @@ +47. The operand of the increment and decrement operators can be any valid + mathematical expression. + + FALSE + + + +48. The cout statement in the following program segment will display 5: + int x = 5; + cout << x++; + + TRUE + + + +49. The cout statement in the following program segment will display 5: + int x = 5; + cout << ++x; + + FALSE + + + +50. The while loop is a pretest loop. + + TRUE + + + +51. The do-while loop is a pretest loop. + + FALSE + + + +52. The for loop is a posttest loop. + + FALSE + + + +53. It is not necessary to initialize counter variables. + + FALSE + + + +54. All three of the for loop’s expressions may be omitted. + + TRUE + + + +55. One limitation of the for loop is that only one variable may be initialized in + the initialization expression. + + FALSE + + + +56. Variables may be defined inside the body of a loop. + + TRUE + + + +57. A variable may be defined in the initialization expression of the for loop. + + TRUE + + + + +58. In a nested loop, the outer loop executes faster than the inner loop. + + FALSE + + + + +59. In a nested loop, the inner loop goes through all of its iterations for every + single iteration of the outer loop. + + TRUE + + + +60. To calculate the total number of iterations of a nested loop, add the number + of iterations of all the loops. + + FALSE: multiply instead + + + +61. The break statement causes a loop to stop the current iteration and begin + the next one. + + FALSE: (break) statement causes the loop to terminate, while the program + continue. + + + +62. The continue statement causes a terminated loop to resume. + + FALSE: (continue) cause it's current iteration to cease, while continuing + through the loops next iteration. + + + +63. In a nested loop, the break statement only interrupts the loop it is placed in. + + TRUE + + + +64. When you call an ofstream object’s open member function, the specified file + will be erased if it already exists. + + TRUE: Yes, because you will be writing to it. diff --git a/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-1.cpp b/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-1.cpp new file mode 100644 index 0000000..63fd8d5 --- /dev/null +++ b/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-1.cpp @@ -0,0 +1,30 @@ +//************************************************************ +// This program has two functions: main and displayMessage +// +// By: Jesus Hilario Hernandez +// Last Updated: November 1, 2016 +//************************************************************ +#include +using namespace std; + +// ****************************************** +// Definition of function displayMessage * +// This function displays a greeting. * +//******************************************* + +void displayMessage() +{ + cout << "Hello from the function displayMessage.\n"; +} + +//******************************************* +// Function main * +//******************************************* + +int main() +{ + cout << "Hello from main.\n"; + displayMessage(); + cout << "Back in function main again.\n"; + return 0; +} diff --git a/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-2.cpp b/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-2.cpp new file mode 100644 index 0000000..48a14fe --- /dev/null +++ b/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-2.cpp @@ -0,0 +1,34 @@ +//************************************************************ +// The function displayMessage is repeatedly called from +// a loop. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 1, 2016 +//************************************************************ +#include +using namespace std; + +//*************************************** +// Defintion of function displayMessage * +// This function displays a greeting. * +//*************************************** + +void displayMessage() +{ + cout << "Hello from the function displayMessage.\n"; +} + +//*************************************** +// Function main * +//*************************************** + +int main() +{ + cout << "Hello from main.\n"; + for (int count = 0; count < 5; count++) + { + displayMessage(); // Call displayMessage + } + cout << "Back in function main again.\n"; + return 0; +} diff --git a/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-3.cpp b/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-3.cpp new file mode 100644 index 0000000..04bbb5f --- /dev/null +++ b/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-3.cpp @@ -0,0 +1,41 @@ +//************************************************************ +// This program has three functions: main, first, and second. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 1, 2016 +//************************************************************ +#include +using namespace std; + +//*************************************** +// Defintion of functions first * +// This function displays a message * +//*************************************** + +void first() +{ + cout << "I am now inside the function first.\n"; +} + +//*************************************** +// Definition of function second * +// This function displays a message. * +//*************************************** + +void second() +{ + cout << "I am now inside the function second.\n"; +} + +//*************************************** +// Function main * +//*************************************** + +int main() +{ + cout << "I am starting in function main.\n"; + first(); // Call function first + second(); // Call function second + cout << "Back in function main again. \n"; + return 0; +} diff --git a/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-4.cpp b/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-4.cpp new file mode 100644 index 0000000..8998514 --- /dev/null +++ b/Chapter-6-Functions/6.2-Defining-and-Calling-Functions/6-4.cpp @@ -0,0 +1,42 @@ +//********************************************************* +// Thid program has three functions: main, deep, and deeper +// +// By: Jesus Hilario Hernandez +// Last Updated: November 1,2016 +//********************************************************* +#include +using namespace std; + +//*********************************** +// Definition of function deeper * +// This function displays a message * +//*********************************** + +void deeper() +{ + cout << "I am now inside the function deeper.\n"; +} + +//*********************************** +// Definition of function deep * +// This function displays a message.* +//*********************************** + +void deep() +{ + cout << "I am now inside the function deep.\n"; + deeper(); // Call function deeper + cout << "Now I am back in deep.\n"; +} + +//*********************************** +// Function main * +//*********************************** + +int main() +{ + cout << "I am starting in function main.\n"; + deep(); // Call function deep + cout << "Back in function main again.\n"; + return 0; +} diff --git a/Chapter-6-Functions/6.3-Function-Prototypes/6-5.cpp b/Chapter-6-Functions/6.3-Function-Prototypes/6-5.cpp new file mode 100644 index 0000000..c872d7a --- /dev/null +++ b/Chapter-6-Functions/6.3-Function-Prototypes/6-5.cpp @@ -0,0 +1,41 @@ +//*********************************************************** +// This program has three functions: main, first, and second. +// +// By: Jesus Hilario Hernandez +// Last Updated November 1, 2016 +//*********************************************************** +#include +using namespace std; + +// Function Prototypes +void first(); +void second(); + +int main() +{ + cout << "I am starting in function main.\n"; + first(); // Call function first + second(); // Call function second + cout << "Back in function main again.\n"; + return 0; +} + +//*************************************** +// Definition of function first. * +// This function displays a message. * +//*************************************** + +void first() +{ + cout << "I am now inside the function first.\n"; +} + +//*************************************** +// Definition of function second. * +// This function displays a message. * +//*************************************** + +void second() +{ + cout << "I am now inside the function second.\n"; +} diff --git a/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-6.cpp b/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-6.cpp new file mode 100644 index 0000000..503f4eb --- /dev/null +++ b/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-6.cpp @@ -0,0 +1,29 @@ +//******************************************************* +// This program demonstrates a function with a parameter. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 1, 2016 +//******************************************************* +#include +using namespace std; + +// Function Prototype +void displayValue(int); + +int main() +{ + cout << "I am passing 5 to displayValue.\n"; + displayValue(5); // Call displayValue with argument 5 + cout << "Now I am back in main.\n"; + return 0; +} + +//*********************************************************** +// Definition of function displayValue. * +// It uses an integer parameter whoes value is displayed. * +//*********************************************************** + +void displayValue(int num) +{ + cout << "The value is " << num << endl; +} diff --git a/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-7.cpp b/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-7.cpp new file mode 100644 index 0000000..14416c4 --- /dev/null +++ b/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-7.cpp @@ -0,0 +1,33 @@ +//******************************************************* +// This program demonstrates a function with a parameter. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 2, 2016 +//******************************************************* +#include +using namespace std; + +// Function Prototype +void displayValue(int); + +int main() +{ + cout << "I am passing several values to displayVaule.\n"; + displayValue(5); // Call displayValue with argument 5 + displayValue(10); // Call displayValue with argument 10 + displayValue(2); // Call displayValue with argument 2 + displayValue(16); // Call displayValue with argument 16 + cout << "Now I am back in main.\n"; + cout << "Thanks! Have a nice day!"; + return 0; +} + +//*********************************************************** +// Definition of function displayValue * +// It uses an integer parameter whose value is displayed. * +//*********************************************************** + +void displayValue(int num) +{ + cout << "The value is " << num << endl; +} diff --git a/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-8.cpp b/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-8.cpp new file mode 100644 index 0000000..a0db3b6 --- /dev/null +++ b/Chapter-6-Functions/6.4-Sending-Data-into-a-Function/6-8.cpp @@ -0,0 +1,57 @@ +//************************************************************ +// This program demonstrates a function with three parameters. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 2, 2016 +//************************************************************ +#include +using namespace std; + +// Function Prototype +void showSum(int, int, int); +int inputVal(int); // Used for error checking + +int main() +{ + int value1, value2, value3; + + // Get three integers. + cout << "Enter three integers and I will display "; + cout << "their sum: " << endl; + value1 = inputVal(value1); + value2 = inputVal(value2); + value3 = inputVal(value3); + + // Call showSum passing three arguments. + cout << "The sum of your values is "; + showSum(value1, value2, value3); + return 0; +} + +//*************************************************************** +// Definition of function showSum. * +// It uses three integer parameters. Their sum is displayed. * +//*************************************************************** + +void showSum(int num1, int num2, int num3) +{ + cout << (num1 + num2 + num3) << endl; +} + +//*************************************************************** +// The inpuVal function checks for valid user input. In This * +// case an integer must be entered. If the user type something * +// other than an integer, then they will be promted to input * +// valid data type. * +//*************************************************************** + +int inputVal(int num) +{ + while (!(cin >> num)) + { + cout << "I'm sorry, a number must be entered. Try again: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-6-Functions/6.5-Passing-Data-by-Value/6-9.cpp b/Chapter-6-Functions/6.5-Passing-Data-by-Value/6-9.cpp new file mode 100644 index 0000000..870768d --- /dev/null +++ b/Chapter-6-Functions/6.5-Passing-Data-by-Value/6-9.cpp @@ -0,0 +1,42 @@ +//******************************************************* +// This program demonstrates that changes to a function +// parameter have no effect on the original argument. +// +// by: Jesus Hernandez +// Last Updated: November 2, 2016 +//****************************************************** +#include +using namespace std; + +// Function Prototype +void changeMe(int); + +int main() +{ + int number = 12; + + // Display the value in number. + cout << "number is " << number << endl; + + // Call changeMe passing the value in number as an argument. + changeMe(number); + + // Display the value in number again. + cout << "Now back in main again, the value of "; + cout << "number is " << number << endl; + return 0; +} + +//*********************************************************** +// Definition of function changeMe. * +// This function changes the value of the parmeter myValue. * +//*********************************************************** + +void changeMe(int myValue) +{ + // Change the value in myValue to 0. + myValue = 0; + + // Display the value in myValue. + cout << "Now the value is " << myValue << endl; +} diff --git a/Chapter-6-Functions/6.6-FSE-Using-Functions-in-a-Menu-Driven-Program/6-10.cpp b/Chapter-6-Functions/6.6-FSE-Using-Functions-in-a-Menu-Driven-Program/6-10.cpp new file mode 100644 index 0000000..5371403 --- /dev/null +++ b/Chapter-6-Functions/6.6-FSE-Using-Functions-in-a-Menu-Driven-Program/6-10.cpp @@ -0,0 +1,113 @@ +//********************************************************** +// This is a menu-driven- program that makes a function call +// for each selection the user makes. +// +// by: Jesus Hilario Hernandez +// Last Updated: November 2. 2016 +//********************************************************** +#include +#include +using namespace std; + +// Function Prototypes +void showMenu(); +void showFees(double, int); +int inputVal(int); // For error checking + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold a number of monthes + + // Constants for the menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Constants for membership rates + const double ADULT = 40.0, + CHILD = 20.0, + SENIOR = 30.0; + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu and get the user's choice. + showMenu(); + choice = inputVal(choice); + + // Validate the menu selection + while(choice < ADULT_CHOICE || choice > QUIT_CHOICE) + { + cout << "Please enter a number in the range of 1 through 4: "; + choice = inputVal(choice); + } + + // If the user does not want to quit, proceed. + if (choice != QUIT_CHOICE) + { + // Get the number of months. + cout << "For how many months? "; + months = inputVal(months); + + // Display the membership + switch (choice) + { + case ADULT_CHOICE: + showFees(ADULT, months); + break; + case CHILD_CHOICE: + showFees(CHILD, months); + break; + case SENIOR_CHOICE: + showFees(SENIOR, months); + } + } + } while (choice != QUIT_CHOICE); + return 0; +} + +//*********************************************************** +// Definition of function showMenu which displays the menu. * +//*********************************************************** + +void showMenu() +{ + cout << "\n\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n"; +} + +//******************************************************************* +// Definition of function showFees. The memberRate parameter holds * +// the monthly membership rate and the months parameter holds the * +// number of months. The function diaplays the total charges. * +//******************************************************************* + +void showFees(double memberRate, int months) +{ + cout << "The total charges are $" + << (memberRate * months) << endl; +} + +//******************************************************************* +// Defintion of function inputVal. inputVal check for and validates * +// user input. If the user type any other data type other that an * +// int, they will be promted to enter the valid data type. * +//******************************************************************* + +int inputVal(int num) +{ + while (!(cin >> num)) + { + cout << "Please enter a number: "; + cin .clear(); + cin.ignore(123,'\n'); + } + return num; +} diff --git a/Chapter-6-Functions/6.7-The-Return-Statement/6-11.cpp b/Chapter-6-Functions/6.7-The-Return-Statement/6-11.cpp new file mode 100644 index 0000000..0d7cee2 --- /dev/null +++ b/Chapter-6-Functions/6.7-The-Return-Statement/6-11.cpp @@ -0,0 +1,58 @@ +//************************************************************** +// This program uses a function to perform division. If division +// by zero is detected, the function returns. +// +// by: Jesus Hilario Hernandez +// last updated: November 2, 2016 +//************************************************************** +#include +using namespace std; + +// Function prototype. +void divide(double, double); +double inputVal(double); // For error Checking + +int main() +{ + double num1, num2; + + cout << "Enter tow numbers and I will divide the first\n"; + cout << "number by the second number: "; + num1 = inputVal(num1); + num2 = inputVal(num2); + divide(num1, num2); + return 0; +} + +//******************************************************************* +// Definition of function divide. * +// Uses two parameters: arg1 and arg2. The function divides arg1 * +// by arg2 and shows the result. If arg2 is zero, however, the * +// function returns. * +//******************************************************************* + +void divide(double arg1, double arg2) +{ + if (arg2 == 0.0) + { + cout << "Sorry, I cannot divide by zero.\n"; + return; + } + cout << "The quotient is " << (arg1 / arg2) << endl; +} + +//******************************************************************* +// Function inputVal prompts the user to enter valid input data. * +// In this case the double data type is accepted only. * +//******************************************************************* + +double inputVal(double num) +{ + while (!(cin >> num)) + { + cout << "I'm sorry a number must be entered: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-6-Functions/6.8-Returning-a-Value-from-a-Function/6-12.cpp b/Chapter-6-Functions/6.8-Returning-a-Value-from-a-Function/6-12.cpp new file mode 100644 index 0000000..e69de29 diff --git a/Chapter-6-Functions/Functions/JHernandezCW2.cpp b/Chapter-6-Functions/Functions/JHernandezCW2.cpp new file mode 100644 index 0000000..20252d7 --- /dev/null +++ b/Chapter-6-Functions/Functions/JHernandezCW2.cpp @@ -0,0 +1,101 @@ +//********************************************* +// Chapter 6, Programming Challenge 2 +// +// By: JESUS HILARIO HERNANDEZ +// Last modified: October 12, 2016 +//********************************************* +#include +using namespace std; + +// Write the prototypes for the getLength, +// getWidth, getArea, and displayData +// functions here. +double getLength(); // Return length +double getWidth(); // Return width +double getArea(double, double); // Return Area +void displayData(double, double, double); // Display Data + +int main() +{ + double length, // The rectangle's length + width, // The rectangle's width + area; // The rectangle's area + + // Get the rectangle's length. + length = getLength(); + + // Get the rectangle's width. + width = getWidth(); + + // Get the rectangle's area. + area = getArea(length, width); + + // Display the rectangle's data. + displayData(length, width, area); + + return 0; +} + +//*************************************************** +// Definition of function getLength function. * +// getLength is a local variable. It's value is * +// assigned to length variable in int main() * +// function. * +//*************************************************** +double getLength() +{ + double num; + cout << "Enter the length: "; + while (!(cin >> num)) + { + //Explain Error + cout << "ERROR: a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + return num; +} +//*************************************************** +// Definition of function getWidth function. * +// getLength is a local variable. It's value is * +// assigned to width variable in int main() * +// function. * +//*************************************************** +double getWidth() +{ + double num; + cout << "Enter the width: "; + while (!(cin >> num)) + { + //Explain Error + cout << "ERROR: a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + return num; +} +//*************************************************** +// Definition of function getArea function. * +// getArea is a local variable. It's value is * +// assigned to area variable in int main() * +// function. * +//*************************************************** +double getArea(double length, double width) +{ + return length * width; +} +//*************************************************** +// Definition of function displayData function. * +// displayData uses length, width, and area * +// variables to display them the the user. * +//*************************************************** +void displayData(double length, double width, double area) +{ + cout << "The length is " << length << "." << endl; + cout << "The width is " << width << "." << endl; + cout << "The area of this rectangle is " << area << endl; +} diff --git a/Chapter-6-Functions/a-driver-program-for-testing-a-function.cpp b/Chapter-6-Functions/a-driver-program-for-testing-a-function.cpp new file mode 100644 index 0000000..3e1a0eb --- /dev/null +++ b/Chapter-6-Functions/a-driver-program-for-testing-a-function.cpp @@ -0,0 +1,50 @@ +//************************************************************ +// This program is a driver for testing the showFees function. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//************************************************************ +#include +using namespace std; + +// Prototype +void showFees(double, int); + +int main() +{ + // Constants for membership rates + const double ADULT = 40.0; + const double SENIOR = 30.0; + const double CHILD = 20.0; + + // Perform a test for adult membership. + cout << "Testing an adult membership...\n" + << "Calling the showFees function with arguments " + << ADULT << " and 10.\n"; + showFees(ADULT, 10); + + // Perform a test for senior citizen membership. + cout << "\nTesting a senior citizen membership...\n" + << "Calling the showFees function with arguments " + << SENIOR << " and 10.\n"; + showFees(SENIOR, 10); + + // Perform a test for child membership. + cout << "\nTesting a child membership...\n" + << "\nCalling the showFees function with arguments " + << CHILD << " and 10.\n"; + showFees(CHILD, 10); + return 0; +} + +//******************************************************************* +// Definition of function showFees. The memberRate parameter holds * +// the monthly membership rate and the months parameter holds the * +// number of months. The function displays the total charges. * +//******************************************************************* + +void showFees(double memberRate, int months) +{ + cout << "The total charges are $" + << (memberRate * months) << endl; +} diff --git a/Chapter-6-Functions/a-function-that-returns-a-bool-value.cpp b/Chapter-6-Functions/a-function-that-returns-a-bool-value.cpp new file mode 100644 index 0000000..f160603 --- /dev/null +++ b/Chapter-6-Functions/a-function-that-returns-a-bool-value.cpp @@ -0,0 +1,76 @@ +//*********************************************************** +// This program uses a function that returns true or false. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 21st, 2016 +//*********************************************************** +#include +using namespace std; + +// Function prototype +int inputVal(int); +bool isEven(int); + +int main() +{ + int val; + + // Get a number from the user. + cout << "Enter an integer and I will tell you " + << "if it is even or odd: "; + // Input validation function + val = inputVal(val); + + // Indicate wheter it is even or odd. + if (isEven(val)) + { + cout << val << " is even.\n"; + } + else + { + cout << val << " is odd.\n"; + } + return 0; +} + +//*********************************************************** +// This function is for input validation. If the user * +// enters a value that is not an int. The input stream * +// will be cleared and ignored. * +//*********************************************************** +int inputVal(int num) +{ + while (!(cin >> num)) + { + // Explain error + cout << "I'm sorry, a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + return num; +} + +//*********************************************************** +// Definition of function isEven. This function accepts an * +// integer argument and test it to be even or odd. The * +// function returns true if the argument is even or false if* +// if the argument is odd. The return is a bool. * +//*********************************************************** + +bool isEven(int number) +{ + //local variable + bool status; + + if (number % 2 == 0) + { + status = true; // The number is even if there is no remainder. + } + else + { + status = false; // Otherwise, the number is odd. + } + return status; +} diff --git a/Chapter-6-Functions/a-function-with-3-parameters.cpp b/Chapter-6-Functions/a-function-with-3-parameters.cpp new file mode 100644 index 0000000..3d6a1e4 --- /dev/null +++ b/Chapter-6-Functions/a-function-with-3-parameters.cpp @@ -0,0 +1,35 @@ +//************************************************************** +// This program demonstrates a function with three parameters. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//************************************************************** +#include +using namespace std; + +// Function Prototypes +void showSum(int, int, int); + +int main() +{ + int value1, value2, value3; + + // Get three integers. + cout << "Enter three integers and I will display "; + cout << "their sum: "; + cin >> value1 >> value2 >> value3; + + // Call showSum passing three arguments. + showSum(value1, value2, value3); + return 0; +} + +//************************************************************ +// Definition of function showSum. * +// It uses three integer parameters. Their sum is displayed. * +//************************************************************ + +void showSum(int num1, int num2, int num3) +{ + cout << (num1 + num2 + num3) << endl; +} diff --git a/Chapter-6-Functions/a-function-with-a-parameter-1.cpp b/Chapter-6-Functions/a-function-with-a-parameter-1.cpp new file mode 100644 index 0000000..9d9d194 --- /dev/null +++ b/Chapter-6-Functions/a-function-with-a-parameter-1.cpp @@ -0,0 +1,28 @@ +//*********************************************************** +// This program demonstrates a function with a parameter +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//*********************************************************** +#include +using namespace std; + +// Function Prototypes +void displayValue(int); + +int main() +{ + cout << "I am passing 5 to displayValue.\n"; + displayValue(5); // Call displayValue with argument 5 + cout << "Now I am back in main.\n"; + return 0; +} +//********************************************************* +// Definition of function displayValue. * +// It uses an integer parameter whose value is displayed. * +//********************************************************* + +void displayValue(int num) +{ + cout << "The value is " << num << endl; +} diff --git a/Chapter-6-Functions/a-function-with-a-parameter-2.cpp b/Chapter-6-Functions/a-function-with-a-parameter-2.cpp new file mode 100644 index 0000000..99770e9 --- /dev/null +++ b/Chapter-6-Functions/a-function-with-a-parameter-2.cpp @@ -0,0 +1,31 @@ +//*********************************************************** +// This program demonstrates a function with a parameter +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//*********************************************************** +#include +using namespace std; + +// Function Prototypes +void displayValue(int); + +int main() +{ + cout << "I am passing several values to displayValue.\n"; + displayValue(5); // Call displayValue with argument 5 + displayValue(10); // Call displayValue with argument 10 + displayValue(2); // Call displayValue with argument 2 + displayValue(16); // Call displayValue with argument 16 + cout << "Now I am back in main.\n"; + return 0; +} +//********************************************************* +// Definition of function displayValue. * +// It uses an integer parameter whose value is displayed. * +//********************************************************* + +void displayValue(int num) +{ + cout << "The value is " << num << endl; +} diff --git a/Chapter-6-Functions/a-local-variable-can-shadow-the-name-of-a-global-constant.cpp b/Chapter-6-Functions/a-local-variable-can-shadow-the-name-of-a-global-constant.cpp new file mode 100644 index 0000000..f833bbf --- /dev/null +++ b/Chapter-6-Functions/a-local-variable-can-shadow-the-name-of-a-global-constant.cpp @@ -0,0 +1,36 @@ +//*********************************************************** +// This program demonstrates how a local variable +// can shadow the name of a global constant. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +// Global constant. +const int BIRDS = 500; + +// Function prototype +void california(); + +int main() +{ + cout << "In main there are " << BIRDS + << " birds.\n"; + california(); + cout << "In main, again, there are " << BIRDS + << " birds.\n"; + return 0; +} + +// ****************************************** +// califonia function * +//******************************************* + +void california() +{ + const int BIRDS = 10000; + cout << "In california ther are " << BIRDS + << " birds\n"; +} diff --git a/Chapter-6-Functions/a-menu-driven-modular-program.cpp b/Chapter-6-Functions/a-menu-driven-modular-program.cpp new file mode 100644 index 0000000..ae24863 --- /dev/null +++ b/Chapter-6-Functions/a-menu-driven-modular-program.cpp @@ -0,0 +1,96 @@ +//************************************************************** +// This is a menu-driven program that makes a function call +// for each selection the user will make. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//************************************************************** +#include +#include +using namespace std; + +// Function prototypes +void showMenu(); +void showFees(double, int); + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold a number of months + + // Constants for the menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Constants for membership rates + const double ADULT = 40.0, + CHILD = 20.0, + SENIOR = 30.0; + + // Set up numeric output formatiing. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu and get the user's choice. + showMenu(); + cin >> choice; + + // Validate the menu selections. + while (choice < ADULT_CHOICE || choice > QUIT_CHOICE) + { + cout << "Please enter a valid menu choice: "; + cin >> choice; + } + + // If the user does not want to quit, proceed. + if (choice != QUIT_CHOICE) + { + // Get the number of months. + cout << "For how many months? "; + cin >> months; + + // Display the membership fees. + switch (choice) + { + case ADULT_CHOICE: + showFees(ADULT, months); + break; + case CHILD_CHOICE: + showFees(CHILD, months); + break; + case SENIOR_CHOICE: + showFees(SENIOR, months); + } + } + } while(choice != QUIT_CHOICE); + return 0; +} + +//************************************************************* +// Definition of function showMenu which displays the menu. * +//************************************************************* + +void showMenu() +{ + cout << "\n\t\tHealth Club Memebership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; +} + +//******************************************************************* +// Difinition of function showFees. The mamberRate parameter holds * +// the monthly membership rate and the months parameter holds the * +// number of months. The function displays the total charges. * +//******************************************************************* + +void showFees(double memberRate, int months) +{ + cout << "The total charges are $" + << (memberRate * months) << endl; +} diff --git a/Chapter-6-Functions/calling-a-function-from-a-loop.cpp b/Chapter-6-Functions/calling-a-function-from-a-loop.cpp new file mode 100644 index 0000000..d719deb --- /dev/null +++ b/Chapter-6-Functions/calling-a-function-from-a-loop.cpp @@ -0,0 +1,33 @@ +//************************************************************* +// This function displayMessage is repeatedly called from loop. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//************************************************************* +#include +using namespace std; + +//***************************************** +// Definition of function displayMessage * +// This function displays a greeting. * +//***************************************** + +void displayMessage() +{ + cout << "Hello from the functions displayMessage.\n"; +} + +//****************************************** +// Function main * +//****************************************** + +int main() +{ + cout << "Hello from main.\n"; + for (int count = 0; count < 5; count++) + { + displayMessage(); // Call displayMessage + } + cout << "Back in function main again.\n"; + return 0; +} diff --git a/Chapter-6-Functions/calling-a-function.cpp b/Chapter-6-Functions/calling-a-function.cpp new file mode 100644 index 0000000..df3694d --- /dev/null +++ b/Chapter-6-Functions/calling-a-function.cpp @@ -0,0 +1,31 @@ +//*********************************************************** +// This program has two functions: main and displayMessage +// and how they are called. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//*********************************************************** +#include +using namespace std; + +//***************************************** +// Definition of function displayMessage * +// This function displays a greeting. * +//***************************************** + +void displayMessage() +{ + cout << "Hello from the functions displayMessage.\n"; +} + +//****************************************** +// Function main * +//****************************************** + +int main() +{ + cout << "Hello from main.\n"; + displayMessage(); + cout << "Back in function main again.\n"; + return 0; +} diff --git a/Chapter-6-Functions/calling-a-value-returning-function.cpp b/Chapter-6-Functions/calling-a-value-returning-function.cpp new file mode 100644 index 0000000..5667c70 --- /dev/null +++ b/Chapter-6-Functions/calling-a-value-returning-function.cpp @@ -0,0 +1,38 @@ +//************************************************************** +// This program uses a function to perform division. If division +// by zero is detected, the function returns. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 20th, 2016 +//************************************************************** +#include +using namespace std; + +// Function prototype +int sum(int, int); +int main() +{ + int value1 = 20, // The first value + value2 = 40, // The second value + total; // To hold the total + + // Call the sum function, passing the contents of + // value1 and value2 as arguments. Assign the return + // value to the total variable. + total = sum(value1, value2); + + // Display the sum of the values. + cout << "The sum of " << value1 << " and " + << value2 << " is " << total << endl; + return 0; +} + +//***************************************************** +// Definition of function sum. This function returns * +// the sum of its two parameters. * +//***************************************************** + +int sum(int num1, int num2) +{ + return num1 + num2; +} diff --git a/Chapter-6-Functions/changes-to-a-function-parameter.cpp b/Chapter-6-Functions/changes-to-a-function-parameter.cpp new file mode 100644 index 0000000..6a7836c --- /dev/null +++ b/Chapter-6-Functions/changes-to-a-function-parameter.cpp @@ -0,0 +1,43 @@ +//************************************************************** +// This program demonstrates that changes to a function +// parameter have no effect on the original argument. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//************************************************************** + #include + using namespace std; + + // Function Prototype + void changeMe(int); + + int main() + { + int number = 12; + + // Display the value in number. + cout << "number is " << number << endl; + + // Call changeMe, passing the value in number as an + // argument. + changeMe(number); + + // Display the value in number again. + cout << "Now back in main again, the value of "; + cout << "number is " << number << endl; + return 0; + } + + //************************************************************* + // Definition of function changeMe. * + // This function changes the value of the parameter myValue. * + //************************************************************* + + void changeMe(int myValue) + { + // Change the value of myValue to 0. + myValue = 0; + + //Display the value in myValue. + cout << "Now the value is " << myValue << endl; + } diff --git a/Chapter-6-Functions/converting-cups-to-fluid-ounces.cpp b/Chapter-6-Functions/converting-cups-to-fluid-ounces.cpp new file mode 100644 index 0000000..3a24502 --- /dev/null +++ b/Chapter-6-Functions/converting-cups-to-fluid-ounces.cpp @@ -0,0 +1,78 @@ +//*************************************************** +// This program converts cups to fluid ounces. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 21st, 2016 +//*************************************************** +#include +#include +using namespace std; + +// Function prototypes +void showIntro(); +double getCups(); +double cupsToOunces(double); + +int main() +{ + //Variables for the cups and ounces + double cups, ounces; + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Display an intro screen. + showIntro(); + + // Get the number of cups. + cups = getCups(); + + // Convert cups to fluid ounces. + ounces = cupsToOunces(cups); + + // Display the number of ounces. + cout << cups << " cups equals " + << ounces << " ounces.\n"; + + return 0; +} + +//*************************************** +// The showIntro function displays an * +// intoductory screen. * +//*************************************** + +void showIntro() +{ + cout << "This program converts measurements\n" + << "in cups to fluid ounces. For your\n" + << "reference the formula is:\n" + << " 1 cup = 8 fluid ounces\n\n"; +} + +//******************************************* +// The getcups function prompts the user * +// to enter the number of cups and then * +// returns that value as a double. * +//******************************************* + +double getCups() +{ + double numCups; // getCups local variable + + cout << "Enter the number of cups: "; + cin >> numCups; + return numCups; +} + +//******************************************* +// The cupstoOunces function accepts a * +// number of cups as an argument and * +// returns the equivalent number of fluid * +// ounces as a double. * +//******************************************* + +double cupsToOunces(double numCups) +{ + return numCups * 8.0; +} diff --git a/Chapter-6-Functions/default-function-arguments.cpp b/Chapter-6-Functions/default-function-arguments.cpp new file mode 100644 index 0000000..d37d76f --- /dev/null +++ b/Chapter-6-Functions/default-function-arguments.cpp @@ -0,0 +1,41 @@ +//*********************************************************** +// This program demonstrates default function arguments. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +// Function prototype with default arguments +void displayStars(int = 10, int = 1); + +int main() +{ + displayStars(); // Use default values for cols and rows. + cout << endl; + displayStars(5); // Use default value for rows. + cout << endl; + displayStars(7, 3); // Use 7 for cols and 3 for rows. + return 0; +} + +//*********************************************************** +// Definition of function displayStars. * +// The default argument for cols is 10 and for rows is 1. * +// This function displays a square made of asterisks. * +//*********************************************************** + +void displayStars(int cols, int rows) +{ + // Nested loop. The outer loop controls the rows + // and the inner loop controls the columns. + for (int down = 0; down < rows; down++) + { + for (int across = 0; across < cols; across++) + { + cout << "*"; + } + cout << endl; + } +} diff --git a/Chapter-6-Functions/functions-called-in-a-layered-fashion.cpp b/Chapter-6-Functions/functions-called-in-a-layered-fashion.cpp new file mode 100644 index 0000000..70ea083 --- /dev/null +++ b/Chapter-6-Functions/functions-called-in-a-layered-fashion.cpp @@ -0,0 +1,42 @@ +//************************************************************* +// This program has three functions: main, deep, and deeper. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//************************************************************* +#include +using namespace std; + +//***************************************** +// Definition of function deeper * +// This function displays a message. * +//***************************************** + +void deeper() +{ + cout << "I am now inside the function deeper.\n"; +} + +//****************************************** +// Definition of function deep * +// This function displays a message. * +//****************************************** + +void deep() +{ + cout << "I am now inside the function deep.\n"; + deeper(); // Call function deeper + cout << "Now I am back in deep\n"; +} + +//****************************************** +// Function main. * +//****************************************** + +int main() +{ + cout << "I am starting in function main.\n"; + deep(); // Call function deep + cout << "Back in function main again. \n"; + return 0; +} diff --git a/Chapter-6-Functions/global-constants.cpp b/Chapter-6-Functions/global-constants.cpp new file mode 100644 index 0000000..717b018 --- /dev/null +++ b/Chapter-6-Functions/global-constants.cpp @@ -0,0 +1,120 @@ +//*********************************************************** +// This program calculates gross pay and also introduces +// and uses global constants to do so. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 21st, 2016 +//*********************************************************** +#include +#include +using namespace std; + +// Global constants +const double PAY_RATE = 22.55; // Hourly pay rate +const double BASE_HOURS = 40.0; // Max non-overtime hours +const double OT_MULTIPLIER = 1.5; // Overtime multiplier + +// Function prototypes +double inputVal(double); +double getBasePay(double); +double getOvertimePay(double); + + +int main() +{ + double hours, // Hours worked + basePay, // Base pay + overtime = 0.0, // Overtime pay + totalPay; // Total pay + + // Get the number of hours worked. + cout << "How many hours did you work? "; + hours = inputVal(hours); + + // Get the amount of base pay. + basePay = getBasePay(hours); + + // Get ovetime pay, if any. + if (hours > BASE_HOURS) + { + overtime = getOvertimePay(hours); + } + + // Calculate the total pay. + totalPay = basePay + overtime; + + // Set up numeric output formatting. + cout << setprecision(2) << fixed << showpoint; + + // Display the pay. + cout << "Base pay: $" << basePay << endl + << "Overtime pay $" << overtime << endl + << "Total pay $" << totalPay << endl; + return 0; +} + +//*************************************************** +// The inputVal function check for input validation * +// checks the error and askes the user to enter * +// valid information * +//*************************************************** + +double inputVal(double num) +{ + while (!(cin >> num)) + { + // Explain error + cout << "I'm sorry, please enter a number: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + // return valid input + return num; +} + +//*********************************************** +// The getBasePay function accepts the number of* +// hours worked as an argument and returns the * +// emplyees's pay for non-overtime hours. * +//*********************************************** + +double getBasePay(double hoursWorked) +{ + double basePay; // To hold base pay + + // Determine base pay. + if (hoursWorked > BASE_HOURS) + { + basePay = BASE_HOURS * PAY_RATE; + } + else + { + basePay = hoursWorked * PAY_RATE; + } + + return basePay; +} + +//*************************************************** +// The getOvertimePay function accepts the number * +// of hours worked as an argument and returns the * +// emplyee's overitme pay. * +//*************************************************** + +double getOvertimePay(double hoursWorked) +{ + double overtimePay; // To hold overtime pay + + // Determine overtime pay. + if (hoursWorked > BASE_HOURS) + { + overtimePay = (hoursWorked - BASE_HOURS) * PAY_RATE * OT_MULTIPLIER; + } + else + { + overtimePay = 0.0; + } + return overtimePay; +} diff --git a/Chapter-6-Functions/global-variables.cpp b/Chapter-6-Functions/global-variables.cpp new file mode 100644 index 0000000..5df9589 --- /dev/null +++ b/Chapter-6-Functions/global-variables.cpp @@ -0,0 +1,16 @@ +//*********************************************************** +// This program has an uninitialized global variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 21st, 2016 +//*********************************************************** +#include +using namespace std; + +int globalNum; // Global variable, automatically set to zero + +int main() +{ + cout << "globalNum is " << globalNum << endl; + return 0; +} diff --git a/Chapter-6-Functions/overloaded-functions-with-user-input.cpp b/Chapter-6-Functions/overloaded-functions-with-user-input.cpp new file mode 100644 index 0000000..82faefe --- /dev/null +++ b/Chapter-6-Functions/overloaded-functions-with-user-input.cpp @@ -0,0 +1,102 @@ +//************************************************************* +// This program demonstrates overloaded functions to calculate +// the gross pay of hourly paid or salaried employees. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//************************************************************* +#include +#include +using namespace std; + +// Function prototypes +void getChoice(char &); +double calcWeeklyPay(int, double); +double calcWeeklyPay(double); + +int main() +{ + char selection; // Menu selection + int worked; // Hours worked + double rate; // Hourly pay rate + double yearly; // Yearly salary + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the menu and get a selections. + cout << "Do you want to calculate the weekly pay of\n"; + cout << "(H) an hourly paid emplyee, or \n"; + cout << "(S) a salaried employee?\n"; + getChoice(selection); + + // Process the menu selection. + switch (selection) + { + // Hourlypaid employees + case 'H' : + case 'h' : cout << "How many hours were worked? "; + cin >> worked; + cout << "What is the hourly pay rate? "; + cin >> rate; + cout << "The gross weekly pay is $"; + cout << calcWeeklyPay(worked, rate) << endl; + break; + + // Salaried employee + case 'S' : + case 's' : cout <<"What is the annual salary? "; + cin >> yearly; + cout << "The gross weekly pay is $"; + cout << calcWeeklyPay(yearly) << endl; + break; + } + return 0; +} + +//*********************************************************** +// Definition of function getChoice. * +// The parameter letter is a reference to a char. * +// This function asks the user for an H or an S and returns * +// the validated input. * +//*********************************************************** + +void getChoice(char & letter) +{ + // Get the user's selection. + cout << "Enter your choice (H or S): "; + cin >> letter; + + // Validate the selection. + while (letter != 'H' && letter != 'h' && + letter != 'S' && letter != 's') + { + cout << "Please enter H or S: "; + cin >> letter; + } +} + +//*********************************************************** +// Definition of overload function calcWeeklyPay. * +// This function calculates the gross weekly pay of * +// an hourly paid employee. The parameter hours holds the * +// number of hours worked. The parameter payRate holds the * +// hourly pay rate. The function returns the weekly salary. * +//*********************************************************** + +double calcWeeklyPay(int hours, double payRate) +{ + return hours * payRate; +} + +//*********************************************************** +// Definition of overloaded function calcWeeklyPay. * +// This function calculates the gorss weekly pay of * +// a salaried employee. The parameter holds the employee's * +// annual salary. The function returns the weekly salary. * +//*********************************************************** + +double calcWeeklyPay(double annSalary) +{ + return annSalary / 52; +} diff --git a/Chapter-6-Functions/return-statement-in-a-void-function.cpp b/Chapter-6-Functions/return-statement-in-a-void-function.cpp new file mode 100644 index 0000000..f110e9e --- /dev/null +++ b/Chapter-6-Functions/return-statement-in-a-void-function.cpp @@ -0,0 +1,40 @@ +//************************************************************** +// This program uses a function to perform division. If division +// by zero is detected, the function returns. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 20th, 2016 +//************************************************************** +#include +using namespace std; + +// Function prototype. +void divide(double, double); + +int main() +{ + double num1, num2; + + cout << "Enter two numbers and I will divide the first\n"; + cout << "number by the second number: "; + cin >> num1 >> num2; + divide(num1, num2); + return 0; +} + +//***************************************************************** +// Definition of function divide. * +// Uses two parameters: arg1 and arg2. The function divides arg1 * +// by arg2 and shows the result. If arg2 is zero, however, the * +// function returns. * +//***************************************************************** + +void divide(double arg1, double arg2) +{ + if (arg2 == 0.0) + { + cout << "Sorry, I cannot divide by zero.\n"; + return; + } + cout << "The quotient is " << (arg1/ arg2) << endl; +} diff --git a/Chapter-6-Functions/static-local-variable-initialization.cpp b/Chapter-6-Functions/static-local-variable-initialization.cpp new file mode 100644 index 0000000..e2b20d5 --- /dev/null +++ b/Chapter-6-Functions/static-local-variable-initialization.cpp @@ -0,0 +1,34 @@ +//*********************************************************** +// This program uses a static local variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +void showStatic(); // Function prototype + +int main() +{ + // Call the showStatic function five times. + for (int count = 0; count <= 5; count++) + { + showStatic(); + } + return 0; +} + +//*************************************************************** +// Definition of function showStatic. * +// statNum is a static local variable. Its value is displayed * +// and then incremented just before the function returns. * +//*************************************************************** + +void showStatic() +{ + static int statNum = 5; + + cout << "statNum is " << statNum << endl; + statNum++; +} diff --git a/Chapter-6-Functions/three-functions.cpp b/Chapter-6-Functions/three-functions.cpp new file mode 100644 index 0000000..eeb53f7 --- /dev/null +++ b/Chapter-6-Functions/three-functions.cpp @@ -0,0 +1,41 @@ +//************************************************************* +// This program has three functions: main, first, second. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//************************************************************* +#include +using namespace std; + +//***************************************** +// Definition of function first * +// This function displays a message. * +//***************************************** + +void first() +{ + cout << "I am now inside the function first.\n"; +} + +//****************************************** +// Definition of function second * +// This function displays a message. * +//****************************************** + +void second() +{ + cout << "I am now inside the function second.\n"; +} + +//****************************************** +// Function main. * +//****************************************** + +int main() +{ + cout << "I am starting in function main.\n"; + first(); // Call function first + second(); // Call function second + cout << "Back in function main again. \n"; + return 0; +} diff --git a/Chapter-6-Functions/using-a-reference-variable-as-a-function-parameter.cpp b/Chapter-6-Functions/using-a-reference-variable-as-a-function-parameter.cpp new file mode 100644 index 0000000..c9e4a5f --- /dev/null +++ b/Chapter-6-Functions/using-a-reference-variable-as-a-function-parameter.cpp @@ -0,0 +1,34 @@ +//*********************************************************** +// This program uses a reference variable as a function +// parameter. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +// Function prototype. The parameter is a reference variable. +void doubleNum(int &); + +int main() +{ + int value = 4; + + cout << "In main, value is " << value << endl; + cout << "Now calling doubleNum..." << endl; + doubleNum(value); + cout << "Now back in main. value is " << value << endl; + return 0; +} + +//*********************************************************** +// Definition of doubleNum. * +// The parameter refVar is a reference variable. The value * +// in refVar is doubled. * +//*********************************************************** + +void doubleNum (int &refVar) +{ + refVar *= 2; +} diff --git a/Chapter-6-Functions/using-a-reference-variables-as-function-parameters-user-input.cpp b/Chapter-6-Functions/using-a-reference-variables-as-function-parameters-user-input.cpp new file mode 100644 index 0000000..840a128 --- /dev/null +++ b/Chapter-6-Functions/using-a-reference-variables-as-function-parameters-user-input.cpp @@ -0,0 +1,61 @@ +//*********************************************************** +// This program uses a reference variables as function +// parameters. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +// Function prototypes. Both functions use reference variables +// as parameters. +void doubleNum(int &); +void getNum (int &); + +int main() +{ + int value; + + // Get a number and store it in value. + getNum(value); + + // Double the number stored in value. + doubleNum(value); + + // Display the resulting number. + cout << "That value doubled is " << value << endl; + return 0; +} + +//*************************************************************** +// Definition of getNum. * +// The parameters userNum is a reference variable. The user is * +// asked to enter a number, which is stored in userNum. * +//*************************************************************** + +void getNum(int &userNum) +{ + cout << "Enter a number: "; + // Input validation + while (!(cin >> userNum)) + { + // Explain error + cout << "Please enter a number: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1230, '\n'); + } +} + +//*************************************************************** +// Definition of doubleNum. * +// The parameter refVar is a reference variable. The user is * +// asked to enter a number, which is stored in userNum. * +//*************************************************************** + +void doubleNum (int &refVar) +{ + refVar *= 2; +} diff --git a/Chapter-6-Functions/using-function-prototypes.cpp b/Chapter-6-Functions/using-function-prototypes.cpp new file mode 100644 index 0000000..7bd4048 --- /dev/null +++ b/Chapter-6-Functions/using-function-prototypes.cpp @@ -0,0 +1,40 @@ +//*********************************************************** +// This program has three functions: main, first, and second. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 19th, 2016 +//*********************************************************** +#include +using namespace std; + +// Function Prototypes +void first(); +void second(); + +int main() +{ + cout << "I am starting in function main.\n"; + first(); // Call function first + second(); // Call function second + cout << "Back in function main again.\n"; + return 0; +} +//***************************************** +// Definition of function first * +// This function displays a message. * +//***************************************** + +void first() +{ + cout << "I am now inside the function first.\n"; +} + +//****************************************** +// Definition of function second. * +// This function displays a message. * +//****************************************** + +void second() +{ + cout << "I am now inside the function second.\n"; +} diff --git a/Chapter-6-Functions/using-global-variables-with-functions.cpp b/Chapter-6-Functions/using-global-variables-with-functions.cpp new file mode 100644 index 0000000..b44181a --- /dev/null +++ b/Chapter-6-Functions/using-global-variables-with-functions.cpp @@ -0,0 +1,34 @@ +//*********************************************************** +// This program shows that a global variable is visible +// to all the functions that appear in a program after +// the variable's declaration. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 21st, 2016 +//*********************************************************** +#include +using namespace std; + +void anotherFunction(); // Functions prototype +int num = 2; // Global variable + +int main() +{ + cout << "In main, num is " << num << endl; + anotherFunction(); + cout << "Back in main, num is " << num << endl; + return 0; +} + +//******************************************************* +// Definition of anotherFunction * +// It has a local variable, num, whose initial value * +// is displayed. * +//******************************************************* + +void anotherFunction() +{ + cout << "In anotherFunction, num is " << num << endl; + num = 50; + cout << "But, it is now changed to " << num << endl; +} diff --git a/Chapter-6-Functions/using-overloaded-functions.cpp b/Chapter-6-Functions/using-overloaded-functions.cpp new file mode 100644 index 0000000..cf0815d --- /dev/null +++ b/Chapter-6-Functions/using-overloaded-functions.cpp @@ -0,0 +1,63 @@ +//*********************************************************** +// This program uses overloaded functions. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +#include +using namespace std; + +// Function prototypes +int square(int); +double square(double); + +int main() +{ + int userInt; + double userFloat; + + // Get an int and a double. + cout << fixed << showpoint << setprecision(2); + cout << "Enter an integer: "; + while (!(cin >> userInt)) + { + cout << "Sorry, a number must be entered: "; + cin.clear(); + cin.ignore(1234, '\n'); + } + cout << "Now, enter a floating-point value: "; + while (!(cin >> userFloat)) + { + cout << "Sorry, a floating-point must be entered: "; + cin.clear(); + cin.ignore(1234, '\n'); + } + + // Display their squares. + cout << "Here are their squares: "; + cout << square(userInt) << " and " << square(userFloat) << endl; + return 0; +} + +//*************************************************************** +// Definition of overloaded function square. * +// This function uses an int parameter, number. It returns the * +// square of number as an int. * +//*************************************************************** + +int square(int number) +{ + return number * number; +} + +//*************************************************************** +// Definition of overloaded function square. * +// This function uses a double parameter, number. It returns * +// the square of number as a double. * +//*************************************************************** + +double square(double number) +{ + return number * number; +} diff --git a/Chapter-6-Functions/using-static-local-variables-with-functions.cpp b/Chapter-6-Functions/using-static-local-variables-with-functions.cpp new file mode 100644 index 0000000..6d27b4c --- /dev/null +++ b/Chapter-6-Functions/using-static-local-variables-with-functions.cpp @@ -0,0 +1,34 @@ +//*********************************************************** +// This program uses a static local variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +void showStatic(); // Function prototype + +int main() +{ + // Call the showStatic function five times. + for (int count = 0; count <= 5; count++) + { + showStatic(); + } + return 0; +} + +//*************************************************************** +// Definition of function showStatic. * +// statNum is a static local variable. Its value is displayed * +// and then incremented just before the function returns. * +//*************************************************************** + +void showStatic() +{ + static int statNum; + + cout << "statNum is " << statNum << endl; + statNum++; +} diff --git a/Chapter-6-Functions/using-static-variable-within-for-loop-scope.cpp b/Chapter-6-Functions/using-static-variable-within-for-loop-scope.cpp new file mode 100644 index 0000000..7bb3195 --- /dev/null +++ b/Chapter-6-Functions/using-static-variable-within-for-loop-scope.cpp @@ -0,0 +1,31 @@ +//*********************************************************** +// This program uses a static local variable. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +void showVar(); // Function prototype + +int main() +{ + for (int count = 0; count < 10; count ++) + { + showVar(); + } + return 0; +} + +//*********************************** +// Definition of function showVar * +//*********************************** + +void showVar() +{ + static int var = 10; + + cout << var << endl; + var++; +} diff --git a/Chapter-6-Functions/using-the-exit-function.cpp b/Chapter-6-Functions/using-the-exit-function.cpp new file mode 100644 index 0000000..a39012c --- /dev/null +++ b/Chapter-6-Functions/using-the-exit-function.cpp @@ -0,0 +1,32 @@ +//************************************************************ +// This program shows how the exit functions causes a program +// to stop executing. +// +// By: Jesus Hilario Hernandez +// Updated last: October 22nd, 2016 +//************************************************************ +#include +#include // Needed for the exit function +using namespace std; + +void funk(); // Function prototype + +int main() +{ + funk(); + return 0; +} + +//*********************************************************** +// This function simply demonstrates that exit can be used * +// to terminate a program from a function other than main. * +//*********************************************************** + +void funk() +{ + cout << "This program terminates with the exit function.\n"; + cout << "Bye!\n"; + exit(EXIT_SUCCESS); + cout << "This message will never be displayed\n"; + cout << "because the program has already terminated.\n"; +} diff --git a/Chapter-6-Functions/value-returning-functions.cpp b/Chapter-6-Functions/value-returning-functions.cpp new file mode 100644 index 0000000..1bad4e8 --- /dev/null +++ b/Chapter-6-Functions/value-returning-functions.cpp @@ -0,0 +1,62 @@ +//************************************************************** +// This program demonstrates two value-returning functions. +// The square function is called in a mathematical statement. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 20th, 2016 +//************************************************************** +#include +#include +using namespace std; + +// Function prototypes +double getRadius(); +double square(double); + +int main() +{ + const double PI = 3.14159; // Constant for pi + double radius; // Holds circle's radius + double area; // Holds circle's area + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Get the radius of the circle. + cout << "This program calculates the area of "; + cout << "a circle. \n"; + radius = getRadius(); + + // Calculate the area of circle. + area = PI * square(radius); + + // Display the area. + cout << "The area is " << area << endl; + return 0; +} + +//***************************************************************** +// Definition of function getRadius. * +// This function asks the user to enter the radius of the circle * +// the circle and then returns that number as a double. * +//***************************************************************** + +double getRadius() +{ + double rad; // local variable within the scope of getRadius + + cout << "Enter the radius of the circle: "; + cin >> rad; + return rad; +} + +//***************************************************************** +// Definition of function square. * +// This function accepts a double argument and returns the square * +// of the argument as a double. * +//***************************************************************** + +double square(double number) +{ + return number * number; +} diff --git a/Chapter-6-Functions/variables-do-not-retain-their-values-between-function-calls.cpp b/Chapter-6-Functions/variables-do-not-retain-their-values-between-function-calls.cpp new file mode 100644 index 0000000..17927b5 --- /dev/null +++ b/Chapter-6-Functions/variables-do-not-retain-their-values-between-function-calls.cpp @@ -0,0 +1,34 @@ +//*********************************************************** +// This program demonstrates how a local variable +// can shadow the name of a global constant. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +// Function prototype +void showLocal(); + +int main() +{ + showLocal(); + showLocal(); + return 0; +} + +//*********************************************************** +// Definition of function showLocal. * +// The initial value of localNum, which is 5, is displayed. * +// The value of localNum is then changed to 99 before the * +// function returns. * +//*********************************************************** + +void showLocal() +{ + int localNum = 5; // Local variable + + cout << "localNum is " << localNum << endl; + localNum = 99; +} diff --git a/Chapter-6-Functions/variables-in-functions.cpp b/Chapter-6-Functions/variables-in-functions.cpp new file mode 100644 index 0000000..f30c31a --- /dev/null +++ b/Chapter-6-Functions/variables-in-functions.cpp @@ -0,0 +1,34 @@ +//*********************************************************** +// This program shows that variables defined in a function +// are hidden from other functions. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 21st, 2016 +//*********************************************************** +#include +using namespace std; + +void anotherFunction(); // Functions prototype + +int main() +{ + int num = 1; // Local variable + + cout << "In main, num is " << num << endl; + anotherFunction(); + cout << "Back in main, num is " << num << endl; + return 0; +} + +//******************************************************* +// Definition of anotherFunction * +// It has a local variable, num, whose initial value * +// is displayed. * +//******************************************************* + +void anotherFunction() +{ + int num = 20; // Local variable + + cout << "In anotherFunction, num is " << num << endl; +} diff --git a/Chapter-6-Functions/what-would-happen-if-user-enters-12-and-14.cpp b/Chapter-6-Functions/what-would-happen-if-user-enters-12-and-14.cpp new file mode 100644 index 0000000..5a91bac --- /dev/null +++ b/Chapter-6-Functions/what-would-happen-if-user-enters-12-and-14.cpp @@ -0,0 +1,45 @@ +//*********************************************************** +// What is the output of the program if the user enters +// 12 and 14? +// +// By: Jesus Hilario Hernandez +// Last Updated: October 22nd, 2016 +//*********************************************************** +#include +using namespace std; + +void func1(int &, int &); +void func2(int &, int &, int &); +void func3(int, int, int); + +int main() +{ + int x = 0, y = 0, z = 0; + + cout << x << " " << y << " " << z << endl; + func1(x, y); + cout << x << " " << y << " " << z << endl; + func2(x, y, z); + cout << x << " " << y << " " << z << endl; + func3(x, y, z); + cout << x << " " << y << " " << z << endl; + return 0; +} + +void func1(int &a, int &b) +{ + cout << "Enter two numbers: "; + cin >> a >> b; +} + +void func2(int &a, int &b, int &c) +{ + b++; + c--; + a = b + c; +} + +void func3(int a, int b, int c) +{ + a = b - c; +} diff --git a/Chapter-7-Arrays/7.10 Arrays with Three or More Dimensions/Checkpoint4.cpp b/Chapter-7-Arrays/7.10 Arrays with Three or More Dimensions/Checkpoint4.cpp new file mode 100644 index 0000000..1d71ab7 --- /dev/null +++ b/Chapter-7-Arrays/7.10 Arrays with Three or More Dimensions/Checkpoint4.cpp @@ -0,0 +1,52 @@ +//******************************************************** +// This program utilizes a function to write the contents +// of 4 separate arrays. Who have the same column length. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 11th, 2016 +//******************************************************** +#include +#include +using namespace std; + +// Constants +const int COLS = 7; +const int ROWS_1 = 5; +const int ROWS_2 = 8; +const int ROWS_3 = 12; +const int ROWS_4 = 50; + +// Function prototype +void showArray(int[][COLS], int); + +int main() +{ + // Arrays + int hours[ROWS_1][COLS]; + int stamps[ROWS_2][COLS]; + int autos[ROWS_3][COLS]; + int cats[ROWS_4][COLS]; + + cout << "The contents in the hours table are: " << endl; + showArray(hours, ROWS_1); + cout << "The contents in the stamps table are: " << endl; + showArray(stamps, ROWS_2); + cout << "The contents in the autos table are: " << endl; + showArray(autos, ROWS_3); + cout << "The contents in the cats table are: " << endl; + showArray(cats, ROWS_4); + return 0; +} + +void showArray(int arrays[][COLS], int rows) +{ + for (int x = 0; x < rows; x++) + { + for (int y = 0; y < COLS; y++) + { + arrays[x][y] = x; + cout << setw(4) << arrays[x][y] << " "; + } + cout << endl; + } +} diff --git a/Chapter-7-Arrays/7.11 Focus on Problem Solving and Program Design: A Case Study/7-23.cpp b/Chapter-7-Arrays/7.11 Focus on Problem Solving and Program Design: A Case Study/7-23.cpp new file mode 100644 index 0000000..ced8b23 --- /dev/null +++ b/Chapter-7-Arrays/7.11 Focus on Problem Solving and Program Design: A Case Study/7-23.cpp @@ -0,0 +1,67 @@ +//************************************************************* +// This program is a driver that tests a function comparing the +// contents of two int arrays. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 11, 2016 +//************************************************************* +#include +using namespace std; + +// Function prototype +bool testPIN(const int [], const int [], int); + +int main() +{ + const int NUM_DIGITS = 7; // Number of digits in a PIN + int pin1[NUM_DIGITS] = {2, 4, 1, 8, 7, 9, 0}; // Base set of values. + int pin2[NUM_DIGITS] = {2, 4, 6, 8, 7, 9, 0}; // Only 1 element is + // different from pin1. + int pin3[NUM_DIGITS] = {1, 2, 3, 4, 5, 6, 7}; // All elements are + // different from pin1. + if (testPIN(pin1, pin2, NUM_DIGITS)) + { + cout << "ERROR: pin1 and pin2 report to be the same.\n"; + } + else + { + cout << "SUCCESS: pin1 and pin2 are different.\n"; + } + + if (testPIN(pin1, pin3, NUM_DIGITS)) + { + cout << "ERROR: pin1 and pin3 report to be the same.\n"; + } + else + { + cout << "SUCCESS: pin1 and pin3 are different.\n"; + } + + if (testPIN(pin1, pin1, NUM_DIGITS)) + { + cout << "SUCCESS: pin1 and pin1 report to be the same.\n"; + } + else + { + cout << "ERROR: pin1 and pin1 report to be different.\n"; + } + return 0; +} + +//******************************************************************* +// The following function accepts two int arrays. The arrays are * +// compared. If they contain the same values, true is returned. * +// If they contain different values, false is returned. * +//******************************************************************* + +bool testPIN(const int custPIN[], const int databasePIN[], int size) +{ + for (int index = 0; index < size; index++) + { + if (custPIN[index] != databasePIN[index]) + { + return false; // We've found two different values. + } + } + return true; // If we make it this far, the values are the same +} diff --git a/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-24.cpp b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-24.cpp new file mode 100644 index 0000000..1b6b70f --- /dev/null +++ b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-24.cpp @@ -0,0 +1,43 @@ +//************************************************************** +// This program stores, in two vectors, the hours worked by 5 +// employees, and their hourly pay rates. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 11th, 2016 +//************************************************************** +#include +#include // Needed to define vectors +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 5; // Numbers of employees + vector hours(NUM_EMPLOYEES); // A vector of integers + vector payRate(NUM_EMPLOYEES); // A vector of doubles + int index; // Loop counter + + // Input the data. + cout << "Enter the hours worked by " << NUM_EMPLOYEES; + cout << " employees and their hourly rates.\n"; + for (index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Hours worked by employees #" << (index + 1); + cout << ": "; + cin >> hours[index]; + cout << "Hourly pay rate for employee #"; + cout << (index + 1) << ": "; + cin >> payRate[index]; + } + + // Display each empolyee's gross pay. + cout << "\nHere is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-25.cpp b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-25.cpp new file mode 100644 index 0000000..ccdd115 --- /dev/null +++ b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-25.cpp @@ -0,0 +1,23 @@ +//***************************************************************** +// This program demonsrates the range-based for loop with a vector. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 12, 2016; +//***************************************************************** +#include +#include +using namespace std; + +int main() +{ + // Define and initialize a vector. + vector numbers {10, 20, 30, 40, 50 }; + + // Display the vector elements. + for (int val : numbers) + { + cout << val << endl; + } + + return 0; +} diff --git a/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-26.cpp b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-26.cpp new file mode 100644 index 0000000..6511ea3 --- /dev/null +++ b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-26.cpp @@ -0,0 +1,30 @@ +//****************************************************************** +// This program demonstrates the range-based for loop with a vector. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 13th, 2016 +//****************************************************************** +#include +#include +using namespace std; + +int main() +{ + // Define and initialize a vector. + vector numbers(5); + + // Get values for the vector elements. + for (int &val : numbers) + { + cout << "Enter an integer value: "; + cin >> val; + } + + // Display the vector elements. + cout << "Here are the values you entered: \n"; + for (int val : numbers) + { + cout << val << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-27.cpp b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-27.cpp new file mode 100644 index 0000000..1e439e1 --- /dev/null +++ b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-27.cpp @@ -0,0 +1,51 @@ +//********************************************************** +// This program stores, in two arrays, the hours worked by 5 +// employees, and their hourly pay rates. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 13th, 2016 +//********************************************************** +#include +#include +#include // Needed to define vectors +using namespace std; + +int main() +{ + vector hours; // hours is an empty vector + vector payRate; // payRate is an empty vector + int numEmployees; // The number of employees + int index; // Loops counter + + // Get the number of employees. + cout << "How many employees do you have? "; + cin >> numEmployees; + + // Input the payroll data. + cout << "Enter the hours worked by " << numEmployees; + cout << " employees and their hourly rates.\n"; + for (index = 0; index < numEmployees; index++) + { + int tempHours; // To hold the number of hours entered + double tempRate; // To hold the pay rate entered + cout << "Hours worked by employee #" << (index + 1); + cout << ": "; + cin >> tempHours; + hours.push_back(tempHours); // Add an element to hours + cout << "Hourly pay rate for employee #"; + cout << (index + 1) << ": "; + cin >> tempRate; + payRate.push_back(tempRate); // Add an element to payRate + } + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (index = 0; index < numEmployees; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-28.cpp b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-28.cpp new file mode 100644 index 0000000..d565fc0 --- /dev/null +++ b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-28.cpp @@ -0,0 +1,48 @@ +//**************************************************************** +// This program demonstrates the vector size +// member function. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 13th, 2016 ps. going to NYC tomorrow!!!! stoked! +//**************************************************************** +#include +#include +using namespace std; + +// Function prototype +void showValues(vector); //*********************************************** + // NOTE: because the vector report its size, the* + // showValues function does not need to accept a* + // second argument indicating the number of * + // elements in the vector. * + //*********************************************** + +int main() +{ + vector values; + + // Put a series of numbers in the vector. + for (int count = 0; count < 7; count++) + { + values.push_back(count * 2); + } + + // Display the numbers. + showValues(values); + return 0; +} + +//*********************************************** +// Definition of function showValues. * +// This function accepts an int vector as its * +// argument. The value of each of the vector's * +// elements is displayed. * +//*********************************************** + +void showValues(vector vect) +{ + for (int count = 0; count < vect.size(); count++) + { + cout << vect[count] << endl; + } +} diff --git a/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-29.cpp b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-29.cpp new file mode 100644 index 0000000..4af871e --- /dev/null +++ b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-29.cpp @@ -0,0 +1,36 @@ +//************************************************************** +// This program demonstrates the vector pop_back member function. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 20th, 2016 +//************************************************************** +#include +#include +using namespace std; + +int main() +{ + vector values; + + // Store values in the vector. + values.push_back(3); + values.push_back(7); + values.push_back(79); + cout << "The size of values is " << values.size() << endl; + + // Remove a value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now " << values.size() << endl; + + // Now remove another value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now "<< values.size() << endl; + + // Remove the last value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now " << values.size() << endl; + return 0; +} diff --git a/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-30.cpp b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-30.cpp new file mode 100644 index 0000000..9e06415 --- /dev/null +++ b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-30.cpp @@ -0,0 +1,22 @@ +//*********************************************************** +// This program demonstrates the vector clear member function. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 20th, 2016 +//************************************************************ +#include +#include +using namespace std; + +int main() +{ + vector values(100); + + cout << "The values vector has " + << values.size() << " elements.\n"; + cout << "I will call the clear member function...\n"; + values.clear(); + cout << "Now, the values vector has " + << values.size() << " elements.\n"; + return 0; +} diff --git a/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-31.cpp b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-31.cpp new file mode 100644 index 0000000..777af02 --- /dev/null +++ b/Chapter-7-Arrays/7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector/7-31.cpp @@ -0,0 +1,67 @@ +//************************************************************** +// This program demonstrates the vector's empty member function. +// +// By: Jesus Hilario Hernandez +// Last Update: November 20, 2016 +//************************************************************** +#include +#include +using namespace std; + +// Function prototype +double avgVector(vector); + +int main() +{ + vector values; // A vector to hold values + int numValues; // The number of values + double average; // To hold the average + + // Get the number of values to average. + cout << "How many values do you wish to average? "; + cin >> numValues; + + // Get the values and store them in the vector. + for (int count = 0; count < numValues; count++) + { + int tempValue; + cout << "Enter a value: "; + cin >> tempValue; + values.push_back(tempValue); + } + + // Get the average of the values and display it. + average = avgVector(values); + cout << "Average: " << average << endl; + + return 0; +} + +//*********************************************************** +// Definition of function avgVector. * +// This function accepts an int vector as its argument. If * +// the vector contains values, the function returns the * +// average of those values. Otherwise, an error message is * +// displayed and the function returns 0.0. * +//*********************************************************** + +double avgVector(vector vect) +{ + int total = 0; // accumulator + double avg; // average + + if (vect.empty()) // Determine if the vector is empty + { + cout << "No values to average.\n"; + avg = 0.0; + } + else + { + for (int count = 0; count < vect.size(); count++) + { + total += vect[count]; + } + avg = total / vect.size(); + } + return avg; +} diff --git a/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-10.cpp b/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-10.cpp new file mode 100644 index 0000000..3cb98e0 --- /dev/null +++ b/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-10.cpp @@ -0,0 +1,21 @@ +//********************************************************** +// This program deomonstrates the range-based for loop. +// +// By: Jesus Hilario Hernandez +// Last updated: October 26, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + // Define an array of integers. + int numbers[] = {10, 20, 30, 40, 50}; + + // Display the values in the array. + for (int val : numbers) + { + cout << val << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-11.cpp b/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-11.cpp new file mode 100644 index 0000000..7d3dc9d --- /dev/null +++ b/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-11.cpp @@ -0,0 +1,26 @@ +//********************************************************** +// This program deomonstrates the range-based for loop and +// uses a string array. +// +// By: Jesus Hilario Hernandez +// Last updated: October 26, 2016 +//********************************************************** +#include +#include +using namespace std; + +int main() +{ + string planets [] = { "Mercury", "Venus", "Earth", "Mars", + "Jupiter", "Saturn", "Uranus", + "Neptune", "Pluto (a dwarf planet)"}; + + cout << "Here are the planets:\n"; + + // Display the values in the array. + for (string /*auto is optional too*/ val : planets) + { + cout << val << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-12.cpp b/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-12.cpp new file mode 100644 index 0000000..de7f809 --- /dev/null +++ b/Chapter-7-Arrays/7.5-the-range-based-for-loop/7-12.cpp @@ -0,0 +1,44 @@ +//********************************************************** +// This program uses a range-based for loop to modify the +// contents of an array. +// +// By: Jesus Hilario Hernandez +// Last updated: October 26, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + const int SIZE = 5; + int numbers[SIZE]; + int numbers2[SIZE]; + + // Get values for the array. + for (int &val : numbers) + { + cout << "Enter an integer value: "; + cin >> val; + } + + // Display the values in the array. + cout << "Here are the values you entered:\n"; + for (int val : numbers) + { + cout << val << endl; + } + + // Get integers for numbers2 + for (int &val : numbers2) + { + cout << "Enter integer values: "; + cin >> val; + } + + // Display values in array numbers2 + for (int val : numbers2) + { + cout << val << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/7-13.cpp b/Chapter-7-Arrays/7.6-processing-array-contents/7-13.cpp new file mode 100644 index 0000000..6d13306 --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/7-13.cpp @@ -0,0 +1,84 @@ +//*********************************************************** +// This program stores, in an array, the hours worked by +// employee who all make the same hourly wage. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 26, 2016 +//*********************************************************** + +#include +#include +using namespace std; + +// Function prototype +int inputVal(int); // Error checking for int +double inputVal(double); // Error checking for double + +int main() +{ + const int NUM_EMPLOYEES = 5; // Number of employees + int hours [NUM_EMPLOYEES]; // Array to hold hours + double payrate; // Hourly pay rate + double grossPay; // To hold the gross pay + + // Input the hours worked. + cout << "Enter the hours worked by "; + cout << NUM_EMPLOYEES << " employees who all\n"; + cout << "earn the same hourly rate.\n"; + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Employee #" << (index + 1) << ": "; + hours[index] = inputVal(hours[index]); + } + + // Input the hourly rate for all employees + cout << "Enter the hourly pay rate for all the employees: "; + payrate = inputVal(payrate); + + // Display each employee's gross pay. + cout << "Here is the gross pay rate each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + grossPay = hours[index] * payrate; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using integers. * +//********************************************************* +// Input validation function for int +int inputVal(int num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using doubles. * +//********************************************************* +double inputVal(double num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/7-13a.cpp b/Chapter-7-Arrays/7.6-processing-array-contents/7-13a.cpp new file mode 100644 index 0000000..6a415fb --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/7-13a.cpp @@ -0,0 +1,69 @@ +//*********************************************************** +// This program show how to print contents of an array, +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 26, 2016 +//*********************************************************** + +#include +#include +using namespace std; + +// Function prototype +int inputVal(int); // Error checking for int +double inputVal(double); // Error checking for double + +int main() +{ + // Print contents of an array + const int SIZE = 5; + int numbers [SIZE] = {10, 20, 30, 40, 50}; + // With regular for loop + for (int count = 0; count < SIZE; count++) + { + cout << numbers[count] << endl; + } + // With range-based for loop + for (int val : numbers) + { + cout << val << endl; + } + + return 0; +} +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using integers. * +//********************************************************* +// Input validation function for int +int inputVal(int num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using doubles. * +//********************************************************* +double inputVal(double num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/7-13b.cpp b/Chapter-7-Arrays/7.6-processing-array-contents/7-13b.cpp new file mode 100644 index 0000000..ecae7b9 --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/7-13b.cpp @@ -0,0 +1,83 @@ +//*********************************************************** +// This program sums the values in a numeric array. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 26, 2016 +//*********************************************************** + +#include +#include +using namespace std; + +// Function prototype +int inputVal(int); // Error checking for int +double inputVal(double); // Error checking for double + +int main() +{ + + // Summing the values in a numeric array + const int NUM_UNITS = 24; + int units[NUM_UNITS]; + // Using regular for loop + int total = 0; + for (int count = 0; count < NUM_UNITS; count++) + { + cout << "Enter number " << (count + 1) << ":"; + units[count] = inputVal(units[count]); + total += units[count]; + } + cout << "The total of every number in the units array is: " + << total << endl; + + // Using a range-based for loop + + total = 0; + int count = 1; + for (int val : units) + { + cout << "Enter number " << count << ":"; + val = inputVal(val); + total += val; + count++; + } + cout << "The total of every number in the units array is: " + << total << endl; + return 0; +} +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using integers. * +//********************************************************* +// Input validation function for int +int inputVal(int num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using doubles. * +//********************************************************* +double inputVal(double num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/7-13c.cpp b/Chapter-7-Arrays/7.6-processing-array-contents/7-13c.cpp new file mode 100644 index 0000000..c7a2d50 --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/7-13c.cpp @@ -0,0 +1,86 @@ +//*********************************************************** +// This program get and prints the average of the values in +// a numeric array. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 27, 2016 +//*********************************************************** +#include +#include +using namespace std; + +// Function prototype +int inputVal(int); // Error checking for int +double inputVal(double); // Error checking for double + +int main() +{ + const int NUM_SCORES = 10; + double scores[NUM_SCORES]; + double total = 0; // Initialize accumulator + double average; // Will hold the average + // Using regular for loop + for (int count = 0; count < NUM_SCORES; count++) + { + cout << "Enter test score number " + << (count + 1) << ": "; + scores[count] = inputVal(scores[count]); + total += scores[count]; + } + average = total / NUM_SCORES; + + cout << fixed << showpoint << setprecision(1); + cout << "\nYour average test score is :" << average << endl << endl; + + total = 0; // Reset accumulator + int rangeCount = 1; // Secondary counter + // Using a range-based for loop + for (int val : scores) + { + cout << "Enter test score number " + << rangeCount << ": "; + val = inputVal(val); + total += val; + rangeCount++; + } + average = total / NUM_SCORES; + + cout << "\nYour average test score is :" << average << endl << endl; + return 0; +} +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using integers. * +//********************************************************* +// Input validation function for int +int inputVal(int num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using doubles. * +//********************************************************* +double inputVal(double num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/7-13d.cpp b/Chapter-7-Arrays/7.6-processing-array-contents/7-13d.cpp new file mode 100644 index 0000000..9e13732 --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/7-13d.cpp @@ -0,0 +1,49 @@ +//*********************************************************** +// This program finds the highest and lowest values in a +// numeric array. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: May 5th, 2017 +//*********************************************************** +#include +#include +using namespace std; + +int main() +{ + const int SIZE = 50; + int numbers[SIZE] = { 54, 23, 23, 12, 65, 74, 73, 76, 34, 12, + 24, 65, 74, 87, 87, 98, 97, 96, 95, 94, + 93, 13, 14, 15, 16, 17, 18, 90, 33, 35, + 36, 37 ,38, 39, 78, 76, 75, 74, 73, 72, + 71, 78, 27, 28, 29, 20, 21, 22, 23, 40 }; + int count; + int highest; + + highest = numbers[0]; + // count is 1 because heighest variable is assined to numbers + // with a subscript 0. + for (count = 1; count < SIZE; count++) + { + if (numbers[count] > highest) + { + highest = numbers[count]; + } + } + cout << highest + << " is the highest number in numbers array. " << endl; + + int lowest; + + lowest = numbers[0]; + for (count = 1; count < SIZE; count++) + { + if (numbers[count] < lowest) + { + lowest = numbers[count]; + } + } + cout << lowest + << " is the lowest number in numbers array. " << endl; + return 0; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/7-13e.cpp b/Chapter-7-Arrays/7.6-processing-array-contents/7-13e.cpp new file mode 100644 index 0000000..193bf70 --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/7-13e.cpp @@ -0,0 +1,64 @@ +//*********************************************************** +// This program deal with partially filled array. The user +// enters in the numbers to be stored in an array that has +// the capacity of 100. If the user has less than 100 numbers +// they should press -1 to quit the program. The total amount +// of numbers they've entered will be printed to screen. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 27, 2016 +//*********************************************************** +#include +#include +using namespace std; + +// Function prototype +int inputVal(int); // Error checking for int + +int main() +{ + const int SIZE = 100; + int numbers[SIZE]; + int count = 0; + + // Adding number to array numbers + int num; + cout << "Enter a number or -1 to quit: "; + num = inputVal(num); + while (num != -1 && count < SIZE) + { + count++; + numbers[count - 1] = num; + cout << "Enter a number or -1 to quit: "; + num = inputVal(num); + } + + // Display the valid items in th array + for (int index = 0; index < count; index++) + { + cout << numbers[index] << endl; + } + + cout << "There are " << SIZE << " available spaces in number array.\n" + << count << " are have been used. " << endl; + return 0; +} + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using integers. * +//********************************************************* +// Input validation function for int +int inputVal(int number) +{ + while (!(cin >> number)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return number; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/7-14.cpp b/Chapter-7-Arrays/7.6-processing-array-contents/7-14.cpp new file mode 100644 index 0000000..1433713 --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/7-14.cpp @@ -0,0 +1,40 @@ +//*********************************************************** +// This program reads data from a file into an array. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 27, 2016 +//*********************************************************** +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 100; // Array size + int numbers[ARRAY_SIZE]; // Array with 100 elements + int count = 0; // Loop counter variable + ifstream inputFile; // Input file stream object + + //Open file. + inputFile.open ("numbers.txt"); + + // Read the numbers from the file into the array. + // After this loop executes, the count variable will hold + // the number of values that were stored in the array. + while (count < ARRAY_SIZE && inputFile >> numbers[count]) + { + count++; + } + + // Close file + inputFile.close(); + + // Display the numbers read. + cout << "The numbers are: " << endl; + for (int index = 0; index < count; index++) + { + cout << numbers[index] << " " << endl; + } + cout << endl; + return 0; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/7-14a.cpp b/Chapter-7-Arrays/7.6-processing-array-contents/7-14a.cpp new file mode 100644 index 0000000..61c014a --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/7-14a.cpp @@ -0,0 +1,40 @@ +//*********************************************************** +// This program compares the contents of two arrays. In +// order to do this you must compare the elements in +// each array...and not compare the array names. As this +// will result false; When comparing by the each +// array name, you are actually comparing memory addresses. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 27, 2016 +//*********************************************************** +#include +using namespace std; + +int main() +{ + const int SIZE = 5; + int firstArray[SIZE] = {5, 10, 15, 20, 25}; + int secondArray[SIZE] = {5, 10, 15, 20, 25}; + bool arraysEqual = 1; // Flag variable + int count = 0; // Loop counter variable + + // Determine whether the elements contain the same data. + while (arraysEqual && count < SIZE) + { + if (firstArray[count] != secondArray[count]) + { + arraysEqual = 0; + } + count++; + } + + if (arraysEqual) + { + cout << "The arrays are equal.\n"; + } + else{ + cout << "The arrays are not equal.\n"; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.6-processing-array-contents/numbers.txt b/Chapter-7-Arrays/7.6-processing-array-contents/numbers.txt new file mode 100644 index 0000000..ba34038 --- /dev/null +++ b/Chapter-7-Arrays/7.6-processing-array-contents/numbers.txt @@ -0,0 +1,39 @@ +6565 +1965 +3765 +2665 +4545 +3334 +5232 +4112 +6239 +5340 +7465 +6436 +8773 +8584 +9602 +1047 +8912 +7813 +1456 +4515 +6133 +3517 +3687 +3776 +3245 +1234 +6523 +7312 +8297 +8688 +5465 +4634 +3523 +2478 +1323 +3872 +3623 +4712 +4732 diff --git a/Chapter-7-Arrays/7.7-FSE-using-parallel-arrays/7-15.cpp b/Chapter-7-Arrays/7.7-FSE-using-parallel-arrays/7-15.cpp new file mode 100644 index 0000000..43bac9f --- /dev/null +++ b/Chapter-7-Arrays/7.7-FSE-using-parallel-arrays/7-15.cpp @@ -0,0 +1,96 @@ +//*********************************************************** +// This program uses two parallel arrays: one for hours +// worked and one for pay rate. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: May 5th, 2017 +//*********************************************************** +#include +#include +using namespace std; + +// Function prototype +int inputVal(int); // Error checking for int +double inputVal(double); // Error checking for double + +int main() +{ + const int NUM_EMPLOYEES = 5; // Number of employees + int hours[NUM_EMPLOYEES]; // Holds hour wokred + double payRate[NUM_EMPLOYEES]; // Holds pay rates + + // Input the hours worked and the hourly pay rate. + cout << "Enter the hours worked by " << NUM_EMPLOYEES + << " employees and their\n" + << "hourly pay rates.\n"; + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Hours worked by employee #" << (index + 1) << ": "; + hours[index] = inputVal(hours[index]); + cout << "Hourly pay rate for employee #" << (index + 1) << ": "; + payRate[index] = inputVal(payRate[index]); + cout << endl; + } + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + + // Display numbers of hours array + cout << "\nThe numbers in array hours are: " << endl; + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + cout << hours[index] << endl; + } + + // Display the numbers in payRate array + cout << "\nThe numbers in array payRate are: " << endl; + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + cout << payRate[index] << endl; + } + return 0; +} + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using integers. * +//********************************************************* +// Input validation function for int +int inputVal(int num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << " Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using doubles. * +//********************************************************* +double inputVal(double num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << " Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-16.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-16.cpp new file mode 100644 index 0000000..96f82e8 --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-16.cpp @@ -0,0 +1,35 @@ +//*********************************************************** +// This program demonstrates that an array element is passed +// to a function like any other variable. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 27, 2016 +//*********************************************************** +#include +using namespace std; + +// Function prototype +void showValue(int); +int main() +{ + const int SIZE = 8; + int numbers[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; + + for (int index = 0; index < SIZE; index++) + { + showValue(numbers[index]); + } + cout << '\n' << endl; + return 0; +} + +//*********************************************** +// Definition of function showValue. * +// This function accepts an integer argument. * +// The value of the argument is displayed. * +//*********************************************** + +void showValue(int num) +{ + cout << num << " "; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-17.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-17.cpp new file mode 100644 index 0000000..a51cdb0 --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-17.cpp @@ -0,0 +1,36 @@ +//*************************************************************** +// This program demonstrates an array being passed to a function. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 28, 2016 +//*************************************************************** +#include +using namespace std; + +// Function prototype +void showValue(int [], int); + +int main() +{ + const int ARRAY_SIZE = 8; + int numbers[ARRAY_SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; + + showValue(numbers, ARRAY_SIZE); + return 0; +} + +//*************************************************** +// Definition of function showValue. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array are displayed. * +//*************************************************** + +void showValue(int nums[], int size) +{ + for (int index = 0; index < size; index++) + { + cout << nums[index] << " "; + } + cout << endl; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-18.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-18.cpp new file mode 100644 index 0000000..dd6aa64 --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-18.cpp @@ -0,0 +1,42 @@ +//*************************************************************** +// This program demonstrates the showValue function being +// used to display the contents of two arrays. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 28, 2016 +//*************************************************************** +#include +using namespace std; + +void showValue(int [], int); // Function prototype + +int main() +{ + const int SIZE1 = 8; // Size of set1 array + const int SIZE2 = 5; // Size of set2 array + int set1[SIZE1] = {5, 10, 15, 20, 25, 30, 35, 40}; + int set2[SIZE2] = {2, 4, 6, 8, 10}; + + // Pass set1 to showValues. + showValue(set1, SIZE1); + + // Pass set2 to showValues. + showValue(set2, SIZE2); + return 0; +} + +//*************************************************** +// Definition of function showValues. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array are displayed. * +//*************************************************** + +void showValue(int nums[], int size) +{ + for (int index = 0; index < size; index++) + { + cout << nums[index] << " "; + } + cout << endl; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-19.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-19.cpp new file mode 100644 index 0000000..1bdc6af --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-19.cpp @@ -0,0 +1,68 @@ +//*************************************************************** +// This program uses a function to double the value of each +// element of an array +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: May 5th, 2017 +//*************************************************************** +#include +using namespace std; + +// Functions prototypes +void doubleArray(int [], int); +void showValues(int [], int); + +int main() +{ + const int ARRAY_SIZE = 7; + int set[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7}; + + // Display the initial values. + cout << "The array's values are.\n"; + showValues(set, ARRAY_SIZE); + + // Double the values in the array. + doubleArray(set, ARRAY_SIZE); + + // Display the resulting values. + cout << "After calling doubleArray the values are:\n"; + showValues(set, ARRAY_SIZE); + + doubleArray(set, ARRAY_SIZE); + + cout << "The array's values have been double 2 times.\n"; + showValues(set, ARRAY_SIZE); + + return 0; +} + +//*************************************************** +// Definition of function doubleArray * +// This function doubles the value of each element * +// in the array passed into nums. The value passed * +// into size is the number of elements in the array.* +//*************************************************** + +void doubleArray(int nums[], int size) +{ + for (int index = 0; index < size; index++) + { + nums[index] *= 2; + } +} + +//*************************************************** +// Definition of function showValues. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array displayed. * +//*************************************************** + +void showValues(int nums[], int size) +{ + for (int index = 0; index < size; index++) + { + cout << nums[index] << " "; + } + cout << endl; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-19a.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-19a.cpp new file mode 100644 index 0000000..8acedf0 --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-19a.cpp @@ -0,0 +1,85 @@ +//********************************************************************* +// This program uses a function to double the value of each +// element of an array within a function. However, the contents in +// the array cannot be changed because of the const int keyword +// parameter within the function header. Further, this program WILL NOT!!! +// run. A compiler error will occur because the of use of the const keyword +// ...the const keyword makes the array readable only and cannot be changed. +// +// When compiled, this error will occur. +// +// ( +// read-only variable is not assignable +// nums[index] *= 2; +// ~~~~~~~~~~~ ^ +// ) +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: May 5th, 2017 +//********************************************************************* +#include +using namespace std; + +// Functions prototypes +void doubleArray(int[], int); +void showValues(int[], int); + +int main() +{ + const int ARRAY_SIZE = 7; + int set[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7}; + + // Display the initial values. + cout << "The array's values are:\n"; + showValues(set, ARRAY_SIZE); + + // Double the values in the array within function only. + cout << "Changed array contents within doubleArray function:"; + doubleArray(set, ARRAY_SIZE); + + // Display the resulting values. + cout << "After calling doubleArray, the values\n" + << "stay the same as initialized in int main():\n"; + showValues(set, ARRAY_SIZE); + + // Display the resulting values. + cout << "Calling doubleArray again:\n"; + doubleArray(set, ARRAY_SIZE); + + cout << "The array's values in int main remain the same:\n"; + showValues(set, ARRAY_SIZE); + + return 0; +} + +//*************************************************** +// Definition of function doubleArray * +// This function doubles the value of each element * +// in the array passed into nums. The value passed * +// into size is the number of elements in the array.* +//*************************************************** + +void doubleArray(const int nums[], int size) +{ + for (int index = 0; index < size; index++) + { + nums[index] *= 2; + cout << nums[index] << " "; + } +} + +//*************************************************** +// Definition of function showValues. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array displayed. * +//*************************************************** + +void showValues(int nums[], int size) +{ + for (int index = 0; index < size; index++) + { + cout << nums[index] << " "; + } + cout << endl; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-20.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-20.cpp new file mode 100644 index 0000000..0d57acd --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/7-20.cpp @@ -0,0 +1,126 @@ +//************************************************************************** +// This program gets a series of test scores and +// calculates the average of the scores with the lowest +// score dropped. +//*********************** Pseudocode algorithim: *************************** +// Read the student's four test scores. +// Calculate the total of the scores. +// Find the lowest score. +// Subtract the lowest score from the total. This gives the adjusted total. +// Divide the adjusted total by 3. This is the average. +// Display the average. +//************************************************************************** +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: November 8, 2016 +//************************************************************************** +#include +#include +using namespace std; + +// Function prototypes +void getTestScores(double[], int); +double getTotal(const double[], int); +double getLowest(const double[], int); + +int main() +{ + const int SIZE = 4; // Array size + double testScores[SIZE],// Array of test scores + total, // Total of the scores + lowestScore, // Lowest test score + average; // Average test score + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Get the test scores from the user. + getTestScores(testScores, SIZE); + + // Get the total of the test scores. + total = getTotal(testScores, SIZE); + + // Get the lowest test score. + lowestScore = getLowest(testScores, SIZE); + + // Subtract the lowest score from the total. + total -= lowestScore; + + // Calculate the average. Divide by 3 because + // The lowest test score was dropped. + average = total / (SIZE - 1); + + // Display the average. + cout << "The average with the lowest score " + << "dropped is " << average << ".\n"; + + return 0; +} + +//*********************************************************** +// The getTestScores function accepts an array and its size * +// as arguments. It prompts the user to enter test scores, * +// which are stored in the array. * +//*********************************************************** + +void getTestScores(double scores[], int size) +{ + // Loop counter + int index; + + // Get each test score. + for (index = 0; index <= size - 1; index++) + { + cout << "Enter test score number " + << (index + 1) << ": "; + cin >> scores[index]; + } +} + +//*************************************************** +// The getTotal function accepts a double array * +// and its size as arguments. The sum of the array's* +// elements is returned as a double. * +//*************************************************** + +double getTotal(const double numbers[], int size) +{ + double total = 0; // Accumulator + + // Add each elements to total. + for(int count = 0; count < size; count++) + { + total += numbers[count]; + } + + // Return the total. + return total; +} + +//*************************************************** +// The getLowest function accepts a double array and* +// its size as arguments. The lowest value in the * +// array is returned as a double. * +//*************************************************** + +double getLowest(const double numbers[], int size) +{ + double lowest; // To hold the lowest value + + // Get the first array's first element. + lowest = numbers[0]; + + // Step through the rest of the array. When a + // value less than lowest is found, assign it + // to lowest. + for(int count = 1; count < size; count++) + { + if(numbers[count] < lowest) + { + lowest = numbers[count]; + } + } + + // Return the lowest value. + return lowest; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/Checkpoint3.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/Checkpoint3.cpp new file mode 100644 index 0000000..c56b1e6 --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/Checkpoint3.cpp @@ -0,0 +1,111 @@ +#include +using namespace std; + +// Function Prototypes +void fillArray(char[], int); +void showArray(const char[], int); +int avgArray(int[], int); + +int main() +{ + // 7.14 + double array1[4] = {1.2, 3.2, 4.2, 5.2}; + double array2[4] = {7.8, 6.7, 8.2, 5.2}; + + for (int count = 0; count < 4; count++) + { + array1[count] = array2[count]; + cout << "array1 subscript " << count << " is: " + << array1[count] << endl; + cout << "array2 subscript " << count << " is: " + << array2[count] << endl; + } + + cout << "\nThis is what array1 looks like: "; + for(double count : array1) + { + cout << count << " "; + } + + cout << "\nThis is what array2 looks like: "; + for(double count : array2) + { + cout << count << " "; + } + cout << endl << endl; + + + // 7.17 + const int SIZE = 7; + char prodCode[SIZE] = {'0','0','0','0','0','0','0',}; + fillArray(prodCode, SIZE); + showArray(prodCode, SIZE); + + + // 7.18 + const int SIZE1 = 10; + int userNums[SIZE1]; + + cout << "Enter 10 numbers: " << endl; + for(int count = 0; count < SIZE1; count++) + { + cout << "#" << (count + 1) << " "; + cin >> userNums[count]; + } + + cout << "The average of those numbers is "; + cout << avgArray(userNums, SIZE1) << endl; + + return 0; +} + +// ********************************************** +// avgArray adds user entered number then * +// calculates the average. * +//*********************************************** + +int avgArray(int arr[], int size) +{ + + int average; + int sum = 0; + int numOfNumbers = 0; + for(int total = 0, count = 0; count < size; total++, count++) + { + numOfNumbers++; + sum += arr[count]; + } + average = sum / numOfNumbers; + return average; +} + +//*********************************************** +// Definition of function fillArray. * +// (Hint: 65 is the ASCII code for 'A') * +//*********************************************** + +void fillArray(char arr[], int size) +{ + char code = 65; + for (int k = 0; k < size; code++, k++) + { + arr[k] = code; + } +} + +//*************************************** +// Definition of function showArray. * +//*************************************** +void showArray(const char codes[], int size) +{ + for (int k = 0; k < size; k++) + { + cout << codes[k]; + for (int i = 0; i < size; i++) + { + cout << codes[i]; + } + cout << endl; + } + cout << endl; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/checkpoint_7-17.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/checkpoint_7-17.cpp new file mode 100644 index 0000000..1bb2d59 --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/checkpoint_7-17.cpp @@ -0,0 +1,47 @@ +//*********************************************************** +// This program utilizes passing arrays as arguments +// to print ASCII characters. +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: May 5th, 2017 +//*********************************************************** +#include +using namespace std; + +// Function Prototypes +void fillArray(char [], int); +void showArray(const char [], int); + +int main() +{ + const int SIZE = 8; + char prodCode[SIZE]; + fillArray(prodCode, SIZE); + showArray(prodCode, SIZE); + return 0; +} + +//*********************************************************** +// The fillArray function fills the passed array with ASCII +// characters. (Hint: 65 is the ASCII code for 'A') +//*********************************************************** +void fillArray(char arr[], int size) +{ + char code = 65; + for (int k = 0; k < size; code++, k++) + { + arr[k] = code; + } +} +//*********************************************************** +// The showArray function prints the passed array of ASCII +// characters. +//*********************************************************** +void showArray(const char codes[], int size) +{ + for (int k = 0; k < size; k++) + { + cout << codes[k]; + } + cout << endl; +} diff --git a/Chapter-7-Arrays/7.8-arrays-as-function-arguments/checkpoint_7-18.cpp b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/checkpoint_7-18.cpp new file mode 100644 index 0000000..8d7e09c --- /dev/null +++ b/Chapter-7-Arrays/7.8-arrays-as-function-arguments/checkpoint_7-18.cpp @@ -0,0 +1,63 @@ +//************************************************************************* +// The following program will ask the user to enter 10 integers, which +// are stored in an array. The function avgArray is to calculate and return +// the average of the numbers entered +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: May 5th, 2017 +//************************************************************************* +#include +using namespace std; + +// Function Prototypes +double avgArray(double [], int); +double inputVal(double); + +int main() +{ + const int SIZE = 10; + double userNums[SIZE]; + + cout << "Enter 10 numbers: " << endl; + for (int count = 0; count < SIZE; count++) + { + cout << '#' << (count + 1) << ' '; + userNums[count] = inputVal(userNums[count]); + } + cout << "The average of those numbers is "; + cout << avgArray(userNums, SIZE) << endl; + return 0; +} + +//******************************************************* +// This function averages all the numbers in an array. * +//******************************************************* +double avgArray(double arr[], int size) +{ + double total = 0; // Initialie accumulator + double average; // Will hold the average + for (int count = 0; count < size; count++) + { + total += arr[count]; + } + average = total / size; + return average; +} + +//*********************************************************** +// The inputVal function checks for valid user input when * +// checking doubles. * +//*********************************************************** +double inputVal(double num) +{ + while(!(cin >> num)) + { + // Explain Error + cout << " Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-21.cpp b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-21.cpp new file mode 100644 index 0000000..7282738 --- /dev/null +++ b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-21.cpp @@ -0,0 +1,70 @@ +//******************************************************** +// This program demonstrates a two-dimensional array. +// +// By: Jesus Hilario Hernandez +// Last Updated: May 5th, 2017 +//******************************************************** +#include +#include +using namespace std; + +// Function Prototypes +double inputVal(double); + +int main() +{ + const int NUM_DIVS = 3; // Number of divisions + const int NUM_QTRS = 4; // Number of quarters + double sales[NUM_DIVS][NUM_QTRS]; // Array with 3 rows and 4 columns. + double totalSales = 0; // To hold the total sales. + int div, qtr; // Loop counters. + + cout << "This program will calculate the total sales of \n"; + cout << "all the company's divisions.\n"; + cout << "Enter the following sales information:\n\n"; + + // Nested loops to fill the array with quarterly sales + // figures for each division. + for(div = 0; div < NUM_DIVS; div++) + { + for (qtr = 0; qtr < NUM_QTRS; qtr++) + { + cout << "Division " << (div + 1); + cout << ", Quarter " << (qtr + 1) << ": $"; + sales[div][qtr] = inputVal(sales[div][qtr]); + } + cout << endl; // Print blank line. + } + + // Nested loops used to add all the elements. + for (div = 0; div < NUM_DIVS; div++) + { + for (qtr = 0; qtr < NUM_QTRS; qtr++) + { + totalSales += sales[div][qtr]; + } + } + + cout << fixed << showpoint << setprecision(2); + cout << "The total sales for the company are: $"; + cout << totalSales << endl; + return 0; +} + +//*********************************************************** +// The inputVal function checks for valid user input when * +// checking for entered doubles. * +//*********************************************************** +double inputVal(double num) +{ + while(!(cin >> num)) + { + // Explain Error + cout << " Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22.cpp b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22.cpp new file mode 100644 index 0000000..42671b7 --- /dev/null +++ b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22.cpp @@ -0,0 +1,60 @@ +//******************************************************** +// This program demonstrates a two-dimensional array. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 11, 2016 +//******************************************************** +#include +#include +using namespace std; + +// Global constants +const int COLS = 4; // Numbers of columns in each array +const int TBL1_ROWS = 3; // Number of rows in table1 +const int TBL2_ROWS = 4; // Number of rows in table2 +const int TBL3_ROWS = 5; // Number of rows in table3 + +void showArray(const int [][COLS], int); // Function prototype + +int main() +{ + int table1[TBL1_ROWS][COLS] = {{1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}}; + int table2[TBL2_ROWS][COLS] = {{10, 20, 30, 40}, + {50, 60, 70, 80}, + {90, 100, 110, 120}, + {130, 140, 150, 160}}; + int table3[TBL3_ROWS][COLS] = {{9, 19, 29, 39}, + {49, 59, 69, 79}, + {89, 99, 109, 119}, + {129, 139, 149, 159}, + {169, 179, 189, 199}}; + + cout << "The contents of table1 are:\n"; + showArray(table1, TBL1_ROWS); + cout << "The contents of table2 are:\n"; + showArray(table2, TBL2_ROWS); + cout << "The contents of table3 are:\n"; + showArray(table3, TBL3_ROWS); + return 0; +} + +//******************************************************************* +// Function Definition for showArray * +// The first argument is a two-dimensional int array with COLS * +// columns. The second argumnet, rows, specifies the number of * +// rows in the array. The function displays the array's contents * +//******************************************************************* + +void showArray(const int numbers[][COLS], int rows) +{ + for (int x = 0; x < rows; x++) + { + for (int y = 0; y < COLS; y++) + { + cout << setw(4) << numbers[x][y] << " "; + } + cout << endl; + } +} diff --git a/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22a.cpp b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22a.cpp new file mode 100644 index 0000000..dcde326 --- /dev/null +++ b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22a.cpp @@ -0,0 +1,39 @@ +//*********************************************************** +// This program sums all the elements of a two-dimensional +// array. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 11, 2016 +//*********************************************************** +#include +using namespace std; + +int main() +{ + const int NUM_ROWS = 5; // Number of rows + const int NUM_COLS = 5; // Number of columns + int total = 0; // Accumulator + int counter = 0; // counter + double average; + int numbers[NUM_ROWS][NUM_COLS] = {{2, 7, 9, 6, 4}, + {6, 1, 8, 9, 4}, + {4, 3, 7, 2, 9}, + {9, 9, 0, 3, 1}, + {6, 2, 7, 4, 2}}; + + // Sum the array elements. + for(int row = 0; row < NUM_ROWS; row++) + { + for(int col = 0; col < NUM_COLS; col++) + { + total += numbers[row][col]; + counter++; + } + } + cout << "There are " << counter << " total numbers in numbers array. " << endl; + // Dislay the sum + cout << "The total is " << total << endl; + average = total / counter; + cout << "The average number within number array is " << average << endl; + return 0; +} diff --git a/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22b.cpp b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22b.cpp new file mode 100644 index 0000000..1daeb2d --- /dev/null +++ b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22b.cpp @@ -0,0 +1,41 @@ +//*********************************************************** +// This program sums all the elements of a two-dimensional +// array. +// +// By: Jesus Hilario Hernandez +// Last Updated: November 11, 2016 +//*********************************************************** +#include +using namespace std; + +int main() +{ + const int NUM_STUDENTS = 3; // Number of students + const int NUM_SCORES = 5; // Number of test scores + double total; // Accumulator is set in the loops + double average; // To hold each score's class average + double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94}, + {86, 91, 78, 79, 84}, + {82, 73, 77, 82, 89}}; + + // Get the class average for each score. + for (int col = 0; col < NUM_SCORES; col++) + { + // Reset the accumulator. + total = 0; + + // Sum a column. + for (int row = 0; row < NUM_STUDENTS; row++) + { + total += scores[row][col]; + } + + // Get the average. + average = total / NUM_STUDENTS; + + // Display the class average. + cout << "Class average for test " << (col + 1) + << " is " << average << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22c.cpp b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22c.cpp new file mode 100644 index 0000000..7b80a3a --- /dev/null +++ b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22c.cpp @@ -0,0 +1,36 @@ +//*********************************************************** +// This program sums all the rows of a two-dimensional +// array. +// +// By: Jesus Hilario Hernandez +// Last Updated: April 29, 2017 +//*********************************************************** +#include +using namespace std; + +int main() +{ + const int NUM_STUDENTS = 3; // Number of students + const int NUM_SCORES = 5; // Numver of scores + double total, average; + double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94}, + {86, 91, 78, 79, 84}, + {82, 73, 77, 82, 89}}; + // Get each student's average score. + for (int row = 0; row < NUM_STUDENTS; row++) + { + // Set the accumulator + total = 0; + // Sum a row. + for (int col = 0; col < NUM_SCORES; col++) + { + total += scores[row][col]; + } + // Get the average. + average = total / NUM_SCORES; + // Display the average. + cout << "Score average for student " + << (row + 1) << " is " << average << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22d.cpp b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22d.cpp new file mode 100644 index 0000000..6d91bf6 --- /dev/null +++ b/Chapter-7-Arrays/7.9 Two-Dimensional Arrays/7-22d.cpp @@ -0,0 +1,38 @@ +//*********************************************************** +// This program sums all the columns of a two-dimensional +// array. +// +// By: Jesus Hilario Hernandez +// Last Updated: April 29, 2017 +//*********************************************************** +#include +using namespace std; + +int main() +{ + const int NUM_STUDENTS = 3; // Number of students + const int NUM_SCORES = 5; // Numver of scores + double total, average; + double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94}, + {86, 91, 78, 79, 84}, + {82, 73, 77, 82, 89}}; + + // Get the class average for each score. + for (int col = 0; col < NUM_SCORES; col++) + { + // Reset the accumulator. + total = 0; + // Sum a column. + for (int row = 0; row < NUM_STUDENTS; row++) + { + total += scores[row][col]; + } + // Get the average. + average = total / NUM_STUDENTS; + + // Display the class average. + cout << "Class average for test " << (col + 1) + << " is " << average << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/7-1.cpp b/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/7-1.cpp new file mode 100644 index 0000000..4260f68 --- /dev/null +++ b/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/7-1.cpp @@ -0,0 +1,59 @@ +//*********************************************************** +// This program asks for the number of hours worked +// by six employees. It stores the values in an array. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 25, 2016 +//*********************************************************** +#include +using namespace std; + +// Function prototype +int inputVal(int); // Used for input validation. + +int main() +{ + const int NUM_EMPLOYEES = 6; + int hours[NUM_EMPLOYEES]; + + // Get hours worked by each employee. + cout << "Enter the hours worked by " + << NUM_EMPLOYEES << " employees: " << endl; + hours[0] = inputVal(hours[0]); + hours[1] = inputVal(hours[1]); + hours[2] = inputVal(hours[2]); + hours[3] = inputVal(hours[3]); + hours[4] = inputVal(hours[4]); + hours[5] = inputVal(hours[5]); + + + // Display the values in the array. + cout << " " << hours[0]; + cout << " " << hours[1]; + cout << " " << hours[2]; + cout << " " << hours[3]; + cout << " " << hours[4]; + cout << " " << hours[5] << endl; + return 0; +} + +//*********************************************** +// Definition of function inputVal function. * +// * +// This function is used to validate whether * +// the user has entered a number. If no * +// number is entered at the keyboard, the * +// while loop will prompt the error and ask * +// for valid input. * +//*********************************************** + +int inputVal(int num) +{ + while (!(cin >> num)) + { + cout << "Please enter a number: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/7-2.cpp b/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/7-2.cpp new file mode 100644 index 0000000..f508821 --- /dev/null +++ b/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/7-2.cpp @@ -0,0 +1,58 @@ +//*********************************************************** +// This program asks for the number of hours worked by six +// employees. It stores the values in an array. +// +// By: Jesus Hilario Hernandez +// Last Updated: October 25, 2016 +//*********************************************************** +#include +using namespace std; + +// Function prototype +int inputVal(int); // Used for input validation. + +int main() +{ + const int NUM_EMPLOYEES = 6; // Number of employees + int hours[NUM_EMPLOYEES]; // Each employee's hours + int count; // Loop counter + + // Input the hours worked. + for (count = 0; count < NUM_EMPLOYEES; count++) + { + cout << "Enter the hours worked by employee " + << (count + 1) << ": "; + hours[count] = inputVal(hours[count]); + } + + // Display the contents of the array + cout << endl; + for (count = 0; count < NUM_EMPLOYEES; count++) + { + cout <<"Hours worked by employee " + << (count + 1) << ": " + << hours[count] << endl; + } + return 0; +} + +//*********************************************** +// Definition of function inputVal function. * +// * +// This function is used to validate whether * +// the user has entered a number. If no * +// number is entered at the keyboard, the * +// while loop will prompt the error and ask * +// for valid input. * +//*********************************************** + +int inputVal(int num) +{ + while (!(cin >> num)) + { + cout << "Please enter a number: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/checkpoint-7-7.cpp b/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/checkpoint-7-7.cpp new file mode 100644 index 0000000..0405004 --- /dev/null +++ b/Chapter-7-Arrays/Inputting-and-Outputting-Array-Contents/checkpoint-7-7.cpp @@ -0,0 +1,28 @@ +//******************************************************** +// This program writes the contents of an array to a file. +// +// By: Jesus Hilario Hernandez +// Last updated: October 25, 2016 +//******************************************************** +#include +#include +using namespace std; + +int main() +{ + const int NUM_FISH = 20; + int fish[NUM_FISH], count; + for (count = 0; count < NUM_FISH; count++) + { + cout << "How many fish were caught by fisherman " + << (count + 1) << ": " << endl; + cin >> fish[count]; + } + for (count = 0; count < NUM_FISH; count++) + { + cout << "Fisherman " << (count + 1) + << " caught " << fish[count] << " fish." << endl; + } + + return 0; +} diff --git a/Chapter-7-Arrays/Reading-Data-from-a-File-into-an-Array/7-3.cpp b/Chapter-7-Arrays/Reading-Data-from-a-File-into-an-Array/7-3.cpp new file mode 100644 index 0000000..02cbc89 --- /dev/null +++ b/Chapter-7-Arrays/Reading-Data-from-a-File-into-an-Array/7-3.cpp @@ -0,0 +1,38 @@ +//*************************************************** +// This program reads data from a file into an array. +// +// By: Jesus Hilario Hernandez +// Last updated: October 25, 2016 +//*************************************************** +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 10; // Array size + int numbers[ARRAY_SIZE]; // Array with 10 elements + int count = 0; // Loop counter variable + ifstream inputFile; // Input file stream object + + // Open the file. + inputFile.open("TenNumbers.txt"); + + // Read the numbers from the file into the array. + while (count < ARRAY_SIZE && inputFile >> numbers[count]) + { + count++; + } + + // Close the file. + inputFile.close(); + + // Display the numbers read. + cout << "The numbers are: "; + for (count = 0; count < ARRAY_SIZE; count++) + { + cout << numbers[count] << " "; + } + cout << endl; + return 0; +} diff --git a/Chapter-7-Arrays/Reading-Data-from-a-File-into-an-Array/TenNumbers.txt b/Chapter-7-Arrays/Reading-Data-from-a-File-into-an-Array/TenNumbers.txt new file mode 100644 index 0000000..26e40ad --- /dev/null +++ b/Chapter-7-Arrays/Reading-Data-from-a-File-into-an-Array/TenNumbers.txt @@ -0,0 +1,10 @@ +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 diff --git a/Chapter-7-Arrays/Writing-the-Contents-of-an-Array-to-a-File/7-4.cpp b/Chapter-7-Arrays/Writing-the-Contents-of-an-Array-to-a-File/7-4.cpp new file mode 100644 index 0000000..13675be --- /dev/null +++ b/Chapter-7-Arrays/Writing-the-Contents-of-an-Array-to-a-File/7-4.cpp @@ -0,0 +1,38 @@ +//******************************************************** +// This program writes the contents of an array to a file. +// +// By: Jesus Hilario Hernandez +// Last updated: October 25, 2016 +//******************************************************** +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 10; // Array size + int numbers[ARRAY_SIZE]; // Array with 10 elements + int count; // Loop counter variable + ofstream outputFile; // Output file stream object + + // Store values in the array. + for (count = 0; count < ARRAY_SIZE; count ++) + { + numbers[count] = count; + } + + // Open output file + outputFile.open("SavedNumbers.txt"); + + // Write the array contents to file. + for (count = 0; count < ARRAY_SIZE; count++) + { + outputFile << numbers[count] << endl; + } + // Close file + outputFile.close(); + + // That's it! + cout << "The numbers were saved to the file.\n" ; + return 0; +} diff --git a/Chapter-7-Arrays/Writing-the-Contents-of-an-Array-to-a-File/SavedNumbers.txt b/Chapter-7-Arrays/Writing-the-Contents-of-an-Array-to-a-File/SavedNumbers.txt new file mode 100644 index 0000000..8b1acc1 --- /dev/null +++ b/Chapter-7-Arrays/Writing-the-Contents-of-an-Array-to-a-File/SavedNumbers.txt @@ -0,0 +1,10 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 diff --git a/Chapter-7-Arrays/array-initialization/7-6.cpp b/Chapter-7-Arrays/array-initialization/7-6.cpp new file mode 100644 index 0000000..3780d70 --- /dev/null +++ b/Chapter-7-Arrays/array-initialization/7-6.cpp @@ -0,0 +1,24 @@ +//******************************************************** +// This program displays the number of days in each month. +// +// By: Jesus Hilario Hernandez +// Last updated: October 25, 2016 +//******************************************************** +#include +#include +using namespace std; + +int main() +{ + const int MONTHS = 12; + int days[MONTHS] = { 31, 28, 31, 30, + 31, 30, 31, 31, + 30, 31, 30, 31}; + + for (int count = 0; count < MONTHS; count++) + { + cout << "Month " << (count + 1) << " has "; + cout << days[count] << " days.\n"; + } + return 0; +} diff --git a/Chapter-7-Arrays/array-initialization/7-7.cpp b/Chapter-7-Arrays/array-initialization/7-7.cpp new file mode 100644 index 0000000..fa94338 --- /dev/null +++ b/Chapter-7-Arrays/array-initialization/7-7.cpp @@ -0,0 +1,25 @@ +//******************************************************** +// This program initializes a string array. +// +// By: Jesus Hilario Hernandez +// Last updated: October 25, 2016 +//******************************************************** +#include +#include +using namespace std; + +int main() +{ + const int SIZE = 9; + string planets[SIZE] = { "Mercury", "Venus", "Earth", "Mars", + "Jupiter", "Saturn", "Uranus", + "Neptune", "Pluto (a dwarf planet)"}; + + cout << "Here are the planets:\n"; + + for (int count = 0; count < SIZE; count++) + { + cout << planets[count] << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/array-initialization/7-8.cpp b/Chapter-7-Arrays/array-initialization/7-8.cpp new file mode 100644 index 0000000..12f1b34 --- /dev/null +++ b/Chapter-7-Arrays/array-initialization/7-8.cpp @@ -0,0 +1,26 @@ +//********************************************************** +// This program uses an array of ten characters to store the +// first ten letters of the alphabet. The ASCII codes of the +// characters are displayed. +// +// By: Jesus Hilario Hernandez +// Last updated: October 25, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + const int NUM_LETTERS = 10; + char letters[NUM_LETTERS] = {'A', 'B', 'C', 'D', 'E', + 'F', 'G', 'H', 'I', 'J'}; + + cout << "Character" << "\t" << "ASCII Code\n"; + cout << "---------" << "\t" << "----------\n"; + for (int count = 0; count < NUM_LETTERS; count++) + { + cout << letters[count] << "\t\t\t"; + cout << static_cast(letters[count]) << endl; + } + return 0; +} diff --git a/Chapter-7-Arrays/array-initialization/7-9.cpp b/Chapter-7-Arrays/array-initialization/7-9.cpp new file mode 100644 index 0000000..877dbb4 --- /dev/null +++ b/Chapter-7-Arrays/array-initialization/7-9.cpp @@ -0,0 +1,22 @@ +//********************************************************** +// This program has a partially initialized array. +// +// By: Jesus Hilario Hernandez +// Last updated: October 25, 2016 +//********************************************************** +#include +using namespace std; + +int main() +{ + const int SIZE = 7; + int numbers[SIZE] = {1, 2, 4, 8}; // Initialized first 4 elements + + cout << "Here are the contents of the array:\n"; + for (int index = 0; index < SIZE; index++) + { + cout << numbers[index] << " "; + } + cout << endl; + return 0; +} diff --git a/Data-Storage/ListOfNumbers.txt b/Data-Storage/ListOfNumbers.txt new file mode 100644 index 0000000..1ed04e6 --- /dev/null +++ b/Data-Storage/ListOfNumbers.txt @@ -0,0 +1,7 @@ +100 +200 +300 +400 +500 +600 +700 diff --git a/Data-Storage/Sales.txt b/Data-Storage/Sales.txt new file mode 100644 index 0000000..91d3451 --- /dev/null +++ b/Data-Storage/Sales.txt @@ -0,0 +1,5 @@ +1200 +2200 +3200 +4200 +5200 diff --git a/Data-Storage/demofile.txt b/Data-Storage/demofile.txt new file mode 100644 index 0000000..b68324d --- /dev/null +++ b/Data-Storage/demofile.txt @@ -0,0 +1,5 @@ +Bach +Beethoven +Chopin +Mozart +Brahms diff --git a/Data-Storage/friends.txt b/Data-Storage/friends.txt new file mode 100644 index 0000000..e9be28f --- /dev/null +++ b/Data-Storage/friends.txt @@ -0,0 +1,3 @@ +jan gonzales +christina hernandez +francesca mariella diff --git a/Data-Storage/ifstream-reading-data-from-a-file.cpp b/Data-Storage/ifstream-reading-data-from-a-file.cpp new file mode 100644 index 0000000..0c41b9a --- /dev/null +++ b/Data-Storage/ifstream-reading-data-from-a-file.cpp @@ -0,0 +1,31 @@ +//******************************************** +// This Program reads data from a file. +// +// By: Jesus Hilario HERNANDEZ +// Last updated: October 11th, 2016 +//******************************************** +#include +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + string firstname, lastname; + + inputFile.open("friends.txt"); + cout << "Reading data from the file." << endl; + + inputFile >> firstname >> lastname; // Read name 1 from the file + cout << firstname << " " << lastname << endl; // Display name 1 + + inputFile >> firstname >> lastname; // Read name 2 from the file + cout << firstname << " " << lastname << endl; // Display name 2 + + inputFile >> firstname >> lastname; // Read name 3 from the file + cout << firstname << " " << lastname << endl; // Display name 3 + + inputFile.close(); // Close the file + return 0; +} diff --git a/Data-Storage/ifstream-reading-data-using-while-loop.cpp b/Data-Storage/ifstream-reading-data-using-while-loop.cpp new file mode 100644 index 0000000..e815a53 --- /dev/null +++ b/Data-Storage/ifstream-reading-data-using-while-loop.cpp @@ -0,0 +1,30 @@ +//******************************************************************** +// This program reads data from a file +// Also used for detecting the end of a file +// +// By: JESUS HILARIO HERNANDEZ +// Last Updated: October 12th, 2016 +//******************************************************************** +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int number; + + // Open the file + inputFile.open("ListOfNumbers.txt"); + + // Read numbers + // Display them + while (inputFile >> number) + { + cout << number << endl; + } + + // CLose file + inputFile.close(); + return 0; +} diff --git a/Data-Storage/ifstream-reading-numbers-from-a-file.cpp b/Data-Storage/ifstream-reading-numbers-from-a-file.cpp new file mode 100644 index 0000000..d88284d --- /dev/null +++ b/Data-Storage/ifstream-reading-numbers-from-a-file.cpp @@ -0,0 +1,39 @@ +//******************************************** +// This Program reads number from a file. +// +// By: Jesus Hilario HERNANDEZ +// Last updated: October 11th, 2016 +//******************************************** +#include +#include +using namespace std; + +int main() +{ + ifstream inFile; + int value1, value2, value3, sum; + + // Open the file. + inFile.open("numbers.txt"); + + // Read the three numbers from the file. + inFile >> value1; + inFile >> value2; + inFile >> value3; + + // Close file. + inFile.close(); + + // Calculate the sum of the numbers. + sum = value1 + value2 + value3; + + // Display the three numbers. + cout << "Here are the numbers: " << endl + << value1 << " " << value2 << " " + << value3 << endl; + + // Display the sum of the numbers. + cout << "Their sum is: " << sum << endl; + + return 0; +} diff --git a/Data-Storage/ifstream-test-for-file-open-errors.cpp b/Data-Storage/ifstream-test-for-file-open-errors.cpp new file mode 100644 index 0000000..c5d5d3f --- /dev/null +++ b/Data-Storage/ifstream-test-for-file-open-errors.cpp @@ -0,0 +1,61 @@ +//********************************************* +// This program tests for file open errors. +// +// By: JESUS HILARIO HERNANDEZ +// Last modified: October 12, 2016 +//********************************************* +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int number; + + // Open the file. + inputFile.open("BadListOfNumbers.txt"); + + // If the file sucessfully opened... + if (inputFile) + { + // Read the numbers from the file and + // display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close the file. + inputFile.close(); + } + // Trailing Else statment + else + { + // Display and error message. + cout << "Error opening the file.\n"; + } + +//********************************************* +// Another example +//********************************************* + + inputFile.open("ListOfNumbers.txt"); + if (inputFile.fail()) + { + cout << "Error opening file.\n"; + } + else + { + // Read the numbers from the file and + // display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close the file. + inputFile.close(); + } + return 0; +} diff --git a/Data-Storage/numbers.txt b/Data-Storage/numbers.txt new file mode 100644 index 0000000..38fe639 --- /dev/null +++ b/Data-Storage/numbers.txt @@ -0,0 +1,3 @@ +345 +23 +745 diff --git a/Data-Storage/ofstream-use-for-loop-to-write-data-to-a-file.cpp b/Data-Storage/ofstream-use-for-loop-to-write-data-to-a-file.cpp new file mode 100644 index 0000000..6dd18f4 --- /dev/null +++ b/Data-Storage/ofstream-use-for-loop-to-write-data-to-a-file.cpp @@ -0,0 +1,32 @@ +//************************************************** +// This program uses a for loop to write the numbers +// in increments of 2 within the range of 0 through +// 1000. +// +// By: JESUS HILARIO HERNANDEZ +// Last modified: October 14, 2016 +//************************************************** +#include +#include +using namespace std; + +int main() +{ + // Stream object + ofstream outputFile; + + // Open or create file to write to + outputFile.open("writenumbersto.txt"); + + for (int i = 0; i <= 1000; i += 2) + { + outputFile << i << endl; + } + // Display data write complete + cout << "Your written file has been written and " + << "complete." << endl; + + // Close file + outputFile.close(); + return 0; +} diff --git a/Data-Storage/ofstream-writing-data-to-a-file-using-for-loop.cpp b/Data-Storage/ofstream-writing-data-to-a-file-using-for-loop.cpp new file mode 100644 index 0000000..8b9b546 --- /dev/null +++ b/Data-Storage/ofstream-writing-data-to-a-file-using-for-loop.cpp @@ -0,0 +1,60 @@ +//******************************************************************** +//This program writes data to a file +// +//By: JESUS HILARIO HERNANDEZ +//Last Updated: October 12th, 2016 +//******************************************************************** +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; // File stream object + int numberOfDays; // Number of days of sales + double sales; // Sales amount for a day + + // Get the number of days. + cout << "For how many days do you have sales? "; + + // Input Validation + while (!(cin >> numberOfDays)) + { + // Explain the error + cout << "ERROR: you must enter a number: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + + // Open a file named Sales.txt. + outputFile.open("Sales.txt"); + + // Get sales...write to file + for (int count = 1; count <= numberOfDays; count++) + { + // Get the sales for a day. + cout << "Enter the sales for day " + << count << ": "; + // Input validation + while(!(cin >> sales)) + { + // Explain error + cout << "ERROR: you must enter a number: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + + // Write the sales to the file. + outputFile << sales << endl; + } + + // Close the file. + outputFile.close(); + cout << "Data written to Sales.txt\n"; + + return 0; +} diff --git a/Data-Storage/ofstream-writing-data-to-a-file.cpp b/Data-Storage/ofstream-writing-data-to-a-file.cpp new file mode 100644 index 0000000..e53a380 --- /dev/null +++ b/Data-Storage/ofstream-writing-data-to-a-file.cpp @@ -0,0 +1,29 @@ +//********************************************* +//This program writes data to a file. +// +// By: JESUS HILARIO HERNANDEZ +// Last modified: October 8, 2016 +//********************************************* +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + outputFile.open("demofile.txt"); + + cout << "Now writing data to the file.\n"; + + // Write for names to the file. + outputFile << "Bach\n"; + outputFile << "Beethoven\n"; + outputFile << "Chopin\n"; + outputFile << "Mozart\n"; + outputFile << "Brahms\n"; + + // Close the file + outputFile.close(); + cout << "Done.\n"; + return 0; +} diff --git a/Data-Storage/ofstream-writing-user-input-to-a-file-2.cpp b/Data-Storage/ofstream-writing-user-input-to-a-file-2.cpp new file mode 100644 index 0000000..7559876 --- /dev/null +++ b/Data-Storage/ofstream-writing-user-input-to-a-file-2.cpp @@ -0,0 +1,39 @@ +//******************************************** +// This Program writes user input to a file. +// +// By: Jesus Hilario HERNANDEZ +// Last updated: October 11th, 2016 +//******************************************** +#include +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + string name1, name2, name3; + + // Open an output file. + outputFile.open("friends.txt"); + + // Get the names of three friedns. + cout << "Enter the names of three friends." << endl; + cout << "Friend #1: "; + getline(cin, name1); + cout << "Friend #2: "; + getline(cin, name2); + cout << "Friend #3: "; + getline(cin, name3); + + // Write the names to the file. + outputFile << name1 << endl; + outputFile << name2 << endl; + outputFile << name3 << endl; + cout << "The names were saved to a file." << endl; + + // Close the file + outputFile.close(); + + return 0; +} diff --git a/Data-Storage/ofstream-writing-user-input-to-a-file.cpp b/Data-Storage/ofstream-writing-user-input-to-a-file.cpp new file mode 100644 index 0000000..741cd7c --- /dev/null +++ b/Data-Storage/ofstream-writing-user-input-to-a-file.cpp @@ -0,0 +1,63 @@ +//******************************************** +// This Program writes user input to a file +// +// By: Jesus Hilario HERNANDEZ +// Last updated: October 11th, 2016 +//******************************************** +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + int number1, number2, number3; + + // Open an output file. + outputFile.open("numbers.txt"); + + // Get three numbers from the user. + cout << "Enter a number: "; + while (!(cin >> number1)) + { + // Explain error + cout << "ERROR: a number must be pressed. " << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + + cout << "Enter another number: "; + while (!(cin >> number2)) + { + // Explain Error + cout << "ERROR: a number must be entered. " << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + + cout << "Enter a last number: "; + while (!(cin >> number3)) + { + // Explain the error + cout << "ERROR: you must enter a number. " << endl; + // Clear input stream + cin.clear(); + // Discard previous input. + cin.ignore(1200, '\n'); + } + + // Write the numbers to the file. + outputFile << number1 << endl; + outputFile << number2 << endl; + outputFile << number3 << endl; + cout << "The numbers were saved to a file.\n"; + + // Close the file + outputFile.close(); + cout << "Done.\n" << endl; + return 0; +} diff --git a/Data-Storage/writenumbersto.txt b/Data-Storage/writenumbersto.txt new file mode 100644 index 0000000..07e6a81 --- /dev/null +++ b/Data-Storage/writenumbersto.txt @@ -0,0 +1,501 @@ +0 +2 +4 +6 +8 +10 +12 +14 +16 +18 +20 +22 +24 +26 +28 +30 +32 +34 +36 +38 +40 +42 +44 +46 +48 +50 +52 +54 +56 +58 +60 +62 +64 +66 +68 +70 +72 +74 +76 +78 +80 +82 +84 +86 +88 +90 +92 +94 +96 +98 +100 +102 +104 +106 +108 +110 +112 +114 +116 +118 +120 +122 +124 +126 +128 +130 +132 +134 +136 +138 +140 +142 +144 +146 +148 +150 +152 +154 +156 +158 +160 +162 +164 +166 +168 +170 +172 +174 +176 +178 +180 +182 +184 +186 +188 +190 +192 +194 +196 +198 +200 +202 +204 +206 +208 +210 +212 +214 +216 +218 +220 +222 +224 +226 +228 +230 +232 +234 +236 +238 +240 +242 +244 +246 +248 +250 +252 +254 +256 +258 +260 +262 +264 +266 +268 +270 +272 +274 +276 +278 +280 +282 +284 +286 +288 +290 +292 +294 +296 +298 +300 +302 +304 +306 +308 +310 +312 +314 +316 +318 +320 +322 +324 +326 +328 +330 +332 +334 +336 +338 +340 +342 +344 +346 +348 +350 +352 +354 +356 +358 +360 +362 +364 +366 +368 +370 +372 +374 +376 +378 +380 +382 +384 +386 +388 +390 +392 +394 +396 +398 +400 +402 +404 +406 +408 +410 +412 +414 +416 +418 +420 +422 +424 +426 +428 +430 +432 +434 +436 +438 +440 +442 +444 +446 +448 +450 +452 +454 +456 +458 +460 +462 +464 +466 +468 +470 +472 +474 +476 +478 +480 +482 +484 +486 +488 +490 +492 +494 +496 +498 +500 +502 +504 +506 +508 +510 +512 +514 +516 +518 +520 +522 +524 +526 +528 +530 +532 +534 +536 +538 +540 +542 +544 +546 +548 +550 +552 +554 +556 +558 +560 +562 +564 +566 +568 +570 +572 +574 +576 +578 +580 +582 +584 +586 +588 +590 +592 +594 +596 +598 +600 +602 +604 +606 +608 +610 +612 +614 +616 +618 +620 +622 +624 +626 +628 +630 +632 +634 +636 +638 +640 +642 +644 +646 +648 +650 +652 +654 +656 +658 +660 +662 +664 +666 +668 +670 +672 +674 +676 +678 +680 +682 +684 +686 +688 +690 +692 +694 +696 +698 +700 +702 +704 +706 +708 +710 +712 +714 +716 +718 +720 +722 +724 +726 +728 +730 +732 +734 +736 +738 +740 +742 +744 +746 +748 +750 +752 +754 +756 +758 +760 +762 +764 +766 +768 +770 +772 +774 +776 +778 +780 +782 +784 +786 +788 +790 +792 +794 +796 +798 +800 +802 +804 +806 +808 +810 +812 +814 +816 +818 +820 +822 +824 +826 +828 +830 +832 +834 +836 +838 +840 +842 +844 +846 +848 +850 +852 +854 +856 +858 +860 +862 +864 +866 +868 +870 +872 +874 +876 +878 +880 +882 +884 +886 +888 +890 +892 +894 +896 +898 +900 +902 +904 +906 +908 +910 +912 +914 +916 +918 +920 +922 +924 +926 +928 +930 +932 +934 +936 +938 +940 +942 +944 +946 +948 +950 +952 +954 +956 +958 +960 +962 +964 +966 +968 +970 +972 +974 +976 +978 +980 +982 +984 +986 +988 +990 +992 +994 +996 +998 +1000 diff --git a/Homework/HW6/JhernandezHW6.docx b/Homework/HW6/JhernandezHW6.docx new file mode 100644 index 0000000..b5c8337 Binary files /dev/null and b/Homework/HW6/JhernandezHW6.docx differ diff --git a/Homework/HW6/JhernandezHW6.pages b/Homework/HW6/JhernandezHW6.pages new file mode 100644 index 0000000..faeb378 Binary files /dev/null and b/Homework/HW6/JhernandezHW6.pages differ diff --git a/Homework/HW6/convertmoney-exercise-1.cpp b/Homework/HW6/convertmoney-exercise-1.cpp new file mode 100644 index 0000000..f8368cc --- /dev/null +++ b/Homework/HW6/convertmoney-exercise-1.cpp @@ -0,0 +1,155 @@ +#include +#include +using namespace std; + + +// This program will input American money and convert it to foreign currency + +// JESUS HILARIO HERNANDEZ + +// Prototypes of the functions +void convertMulti(float dollars, float& euros, float& pesos); +void convertMulti(float dollars, float& euros, float& pesos, float& yen); +float convertToYen(float dollars); +float convertToEuros(float dollars); +float convertToPesos(float dollars); + +int main () +{ + float dollars; + float euros; + float pesos; + float yen; + + cout << fixed << showpoint << setprecision(2); + + cout << "Please input the amount of American Dollars you want converted " + << endl; + cout << "to euros and pesos" << endl; + cin >> dollars; + + // Fill in the code to call convertMulti with parameters dollars, euros and pesos + // Fill in the code to output the value of those dollars converted to both euros and pesos + + cout << "Please input the amount of American Dollars you want converted\n"; + cout << "to euros, pesos and yen" << endl; + cin >> dollars; + + // Fill in the code to call convertMulti with parameters dollars, euros, pesos and yen + // Fill in the code to output the value of those dollars converted to euros, pesos and yen + + cout << "Please input the amount of American Dollars you want converted\n"; + cout << "to yen" <> dollars; + + // Fill in the code to call convertToYen + // Fill in the code to output the value of those dollars converted to yen + + cout << "Please input the amount of American Dollars you want converted\n"; + cout << " to euros" << endl; + cin >> dollars; + + // Fill in the code to call convertToEuros + // Fill in the code to output the value of those dollars converted to euros + + cout << "Please input the amount of American Dollars you want converted\n"; + cout << " to pesos " << endl; + cin >> dollars; + + // Fill in the code to call convertToPesos + // Fill in the code to output the value of those dollars converted to pesos + + return 0; +} + + +// All of the functions are stubs that just serve to test the functions +// Replace with code that will cause the functions to execute properly + +// ************************************************************************ +// convertMult +// +// task: This function takes a dollar value and converts it to euros +// and pesos +// data in: dollars +// data out: euros and pesos +// +// *********************************************************************** + +void convertMulti(float dollars, float& euros, float& pesos) +{ + cout << "The function convertMulti with dollars, euros and pesos " + << endl <<" was called with " << dollars <<" dollars" << endl << endl; + + +} + + +// ************************************************************************ +// convertMult +// +// task: This function takes a dollar value and converts it to euros +// pesos and yen +// data in: dollars +// data out: euros pesos yen +// +// *********************************************************************** + +void convertMulti(float dollars, float& euros, float& pesos, float& yen) +{ + cout << "The function convertMulti with dollars, euros, pesos and yen" + << endl << " was called with " << dollars << " dollars" << endl << endl; + + + +} + +// **************************************************************************** +// convertToYen +// +// task: This function takes a dollar value and converts it to yen +// data in: dollars +// data returned: yen +// +// *************************************************************************** + +float convertToYen(float dollars) +{ + cout << "The function convertToYen was called with " << dollars <<" dollars" + << endl << endl; + + return 0; +} + +// **************************************************************************** +// convertToEuros +// +// task: This function takes a dollar value and converts it to euros +// data in: dollars +// data returned: euros +// +// *************************************************************************** + +float convertToEuros(float dollars) +{ + cout << "The function convertToEuros was called with " << dollars + << " dollars" << endl << endl; + + return 0; +} + +// ***************************************************************************** +// convertToPesos +// +// task: This function takes a dollar value and converts it to pesos +// data in: dollars +// data returned: pesos +// +// **************************************************************************** +float convertToPesos(float dollars) +{ + cout << "The function convertToPesos was called with " << dollars + << " dollars" << endl; + + return 0; +} diff --git a/Homework/HW6/money-exercise-2.cpp b/Homework/HW6/money-exercise-2.cpp new file mode 100644 index 0000000..3e34a61 --- /dev/null +++ b/Homework/HW6/money-exercise-2.cpp @@ -0,0 +1,73 @@ +#include +#include +using namespace std; + +//JESUS HILARIO HERNANDEZ + +void normalizeMoney(float& dollars, int cents = 150); +// This function takes cents as an integer and converts it to dollars +// and cents. The default value for cents is 150 which is converted +// to 1.50 and stored in dollars + +int main() +{ + int cents; + float dollars; + + cout << setprecision(2) << fixed << showpoint; + + cents = 95; + cout << "\n We will now add 95 cents to our dollar total\n"; + + // Fill in the code to call normalizeMoney to add 95 cents + normalizeMoney(dollars, cents); + + cout << "Converting cents to dollars resulted in " << dollars << " dollars\n"; + cout << "\n We will now add 193 cents to our dollar total\n"; + + // Fill in the code to call normalizeMoney to add 193 cents + cents = 193; + normalizeMoney(dollars, cents); + + cout << "Converting cents to dollars resulted in " << dollars << " dollars\n"; + cout << "\n We will now add the default value to our dollar total\n"; + + // Fill in the code to call normalizeMoney to add the default value of cents + normalizeMoney(dollars); + + cout << "Converting cents to dollars resulted in " << dollars << " dollars\n"; + + return 0; +} + +// ******************************************************************************* +// normalizeMoney +// +// task: This function is given a value in cents. It will convert cents +// to dollars and cents which is stored in a local variable called +// total which is sent back to the calling function through the +// parameter dollars. It will keep a running total of all the money +// processed in a local static variable called sum. +// +// data in: cents which is an integer +// data out: dollars (which alters the corresponding actual parameter) +// +// ********************************************************************************* + +void normalizeMoney(float& dollars, int cents) +{ + + float total=0; + + // Fill in the definition of sum as a static local variable + static float sum = 0.0; + + // Fill in the code to convert cents to dollars + dollars = cents * .01; + total = total + dollars; + sum = sum + dollars; + + cout << "We have added another $" << dollars <<" to our total" << endl; + cout << "Our total so far is $" << sum << endl; + cout << "The value of our local variable total is $" << total << endl; +} diff --git a/Homework/HW6/newproverb-1-exercise-1.cpp b/Homework/HW6/newproverb-1-exercise-1.cpp new file mode 100644 index 0000000..c17acde --- /dev/null +++ b/Homework/HW6/newproverb-1-exercise-1.cpp @@ -0,0 +1,60 @@ +// This program will allow the user to input from the keyboard +// whether the last word to the following proverb should be party or country: +// "Now is the time for all good men to come to the aid of their _______" +// Inputting a 1 will use the word party. Any other number will use the word country. + +// JESUS HILARIO HERNANDEZ + +#include +#include +using namespace std; + +// Fill in the prototype of the function writeProverb. +void writeProverb(int); + +int main () +{ + + int wordCode; + + cout << "Given the phrase:" << endl; + cout << "Now is the time for all good men to come to the aid of their ___" << endl; + cout << "Input a 1 if you want the sentence to be finished with party" << endl; + cout << "Input any other number for the word country" << endl; + cout << "Please input your choice now" << endl; + cin >> wordCode; + cout << endl; + writeProverb(wordCode); + + return 0; +} + +// ****************************************************************************** +// writeProverb +// +// task: This function prints a proverb. The function takes a number +// from the call. If that number is a 1 it prints "Now is the time +// for all good men to come men to come to the aid of their party." +// Otherwise, it prints "Now is the time for all good men +// to come to the aid of their country" +// data in: code for ending word of proverb (integer) +// data out: none +// +// ***************************************************************************** + +void writeProverb (int number) + + +{ + // Fill in the body of the function to accomplish what is described above + if (number == 1) + { + cout << "Now is the time for all good men " + << "to come to the aid of their party" << endl; + } + else + { + cout << "Now is the time for all good men " + << "to come to the aid of their country" << endl; + } +} diff --git a/Homework/HW6/newproverb-1-exercise-2.cpp b/Homework/HW6/newproverb-1-exercise-2.cpp new file mode 100644 index 0000000..d318f4e --- /dev/null +++ b/Homework/HW6/newproverb-1-exercise-2.cpp @@ -0,0 +1,69 @@ +// This program will allow the user to input from the keyboard +// whether the last word to the following proverb should be party or country: +// "Now is the time for all good men to come to the aid of their _______" +// Inputting a 1 will use the word party. the number 2 will use the word country. + +// JESUS HILARIO HERNANDEZ + +#include +#include +using namespace std; + +// Fill in the prototype of the function writeProverb. +void writeProverb(int); + +int main () +{ + + int wordCode; + + cout << "Given the phrase:" << endl; + cout << "Now is the time for all good men to come to the aid of their ___" << endl; + cout << "Input a 1 if you want the sentence to be finished with party" << endl; + cout << "Input any other number for the word country" << endl; + cout << "Please input your choice now" << endl; + cin >> wordCode; + while (wordCode != 1 && wordCode != 2) + { + cout << "I'm sorry but that is an ncorrect choice; " + << "Please input a 1 or a 2 " << endl; + cin.clear(); + cin.ignore(123, '\n'); + cin >> wordCode; + } + cout << endl; + writeProverb(wordCode); + + cout << endl << endl; + return 0; +} + +// ****************************************************************************** +// writeProverb +// +// task: This function prints a proverb. The function takes a number +// from the call. If that number is a 1 it prints "Now is the time +// for all good men to come men to come to the aid of their party." +// The number 2 prints "Now is the time for all good men +// to come to the aid of their country" +// data in: code for ending word of proverb (integer) +// data out: none +// +// ***************************************************************************** + +void writeProverb (int number) + + +{ + // Fill in the body of the function to accomplish what is described above + if (number == 1) + { + cout << "Now is the time for all good men " + << "to come to the aid of their party" << endl; + } + else if (number == 2) + { + cout << "Now is the time for all good men " + << "to come to the aid of their country" << endl; + } +} diff --git a/Homework/HW6/newproverb-1-exercise-3.cpp b/Homework/HW6/newproverb-1-exercise-3.cpp new file mode 100644 index 0000000..ea34de5 --- /dev/null +++ b/Homework/HW6/newproverb-1-exercise-3.cpp @@ -0,0 +1,53 @@ +// This program will allow the user to input from the keyboard +// whether the last word to the following proverb should be party or country: +// "Now is the time for all good men to come to the aid of their _______" +// The user will input a word to finish the sentence. + +// JESUS HILARIO HERNANDEZ + +#include +#include +using namespace std; + +// Fill in the prototype of the function writeProverb. +string writeProverb(string); + +int main () +{ + + string word; + + cout << "Given the phrase:" << endl; + cout << "Now is the time for all good men to come to the aid of their ___" << endl; + cout << "Input a 1 if you want the sentence to be finished with party" << endl; + cout << "Input any other number for the word country" << endl; + cout << "Please input your choice now" << endl; + cin >> word; + + cout << endl; + writeProverb(word); + + cout << endl << endl; + return 0; +} + +// ****************************************************************************** +// writeProverb +// +// task: This function prints a proverb. The function takes a string +// from the user. The word the user provides is used to +// end the proverb. "Now is the time for all good men to come +// men to come to the aid of their _(user input)_" will be +// printed to screen +// data in: code for ending word of proverb (string) +// data out: none +// +// ***************************************************************************** + +string writeProverb (string endword) +{ + // Fill in the body of the function to accomplish what is described above + cout << "Now is the time for all good men " + << "to come to the aid of their " << endword << endl; + return endword; +} diff --git a/Homework/HW6/paycheck-exercise-1.cpp b/Homework/HW6/paycheck-exercise-1.cpp new file mode 100644 index 0000000..131e079 --- /dev/null +++ b/Homework/HW6/paycheck-exercise-1.cpp @@ -0,0 +1,77 @@ +// This program takes two numbers (pay rate & hours) +// and multiplies them to get grosspay +// it then calculates net pay by subtracting 15% + +// JESUS HILARIO HERNANDEZ + +#include +#include +using namespace std; + +//Function prototypes +void printDescription(); +void computePaycheck(float, int, float&, float&); + +int main() +{ + float payRate; + float grossPay; + float netPay; + int hours; + + cout << setprecision(2) << fixed; + + cout << "Welcome to the Pay Roll Program" << endl; + + printDescription(); //Call to Description function + + cout << "Please input the pay per hour" << endl; + cin >> payRate; + + cout << endl << "Please input the number of hours worked" << endl; + cin >> hours; + cout << endl << endl; + + computePaycheck(payRate,hours,grossPay,netPay); + + // Fill in the code to output grosspay + cout << "The gross pay is $" << static_cast(grossPay) << endl; + cout << "The net pay is $" << static_cast(netPay) << endl; + cout << "We hoped you enjoyed this program" << endl; + + return 0; +} + +// ******************************************************************** +// printDescription +// +// task: This function prints a program description +// data in: none +// data out: none +// +// ******************************************************************** + +void printDescription() //The function heading +{ + cout << "************************************************" << endl << endl; + cout << "This program takes two numbers (pay rate & hours)" << endl; + cout << "and multiplies them to get gross pay " << endl; + cout << "it then calculates net pay by subtracting 15%" << endl; + cout << "************************************************" << endl << endl; +} + +// ********************************************************************* +// computePaycheck +// +// task: This function takes rate and time and multiples them to +// get gross pay and then finds net pay by subtracting 15%. +// data in: pay rate and time in hours worked +// data out: the gross and net pay +// +// ******************************************************************** + +void computePaycheck(float rate, int time, float& gross, float& net) +{ + // Fill in the code to find grosspay and net pay + gross = rate * time; net = (gross) - (gross * .15); +} diff --git a/Homework/HW6/paycheck-exercise-4.cpp b/Homework/HW6/paycheck-exercise-4.cpp new file mode 100644 index 0000000..702c67d --- /dev/null +++ b/Homework/HW6/paycheck-exercise-4.cpp @@ -0,0 +1,78 @@ +// This program takes two numbers (pay rate & hours) +// and multiplies them to get grosspay +// it then calculates net pay by subtracting 15% + +// JESUS HILARIO HERNANDEZ + +#include +#include +using namespace std; + +//Function prototypes +void printDescription(); +void computePaycheck(float, int, float&, float&); + +int main() +{ + float payRate; + float grossPay; + float netPay; + int hours; + + cout << setprecision(2) << fixed; + cout << "Welcome to the Pay Roll Program" << endl; + + printDescription(); //Call to Description function + + cout << "Please input the pay per hour" << endl; + cin >> payRate; + + cout << endl << "Please input the number of hours worked" << endl; + cin >> hours; + cout << endl << endl; + + computePaycheck(payRate,hours,grossPay,netPay); + + + + return 0; +} + +// ******************************************************************** +// printDescription +// +// task: This function prints a program description +// data in: none +// data out: none +// +// ******************************************************************** + +void printDescription() //The function heading +{ + cout << "************************************************" << endl << endl; + cout << "This program takes two numbers (pay rate & hours)" << endl; + cout << "and multiplies them to get gross pay " << endl; + cout << "it then calculates net pay by subtracting 15%" << endl; + cout << "************************************************" << endl << endl; +} + +// ********************************************************************* +// computePaycheck +// +// task: This function takes rate and time and multiples them to +// get gross pay and then finds net pay by subtracting 15%. +// data in: pay rate and time in hours worked +// data out: the gross and net pay +// +// ******************************************************************** + +void computePaycheck(float rate, int time, float& gross, float& net) +{ + // Fill in the code to find grosspay and net pay + gross = rate * time; net = (gross) - (gross * .15); + + // Fill in the code to output grosspay + cout << "The gross pay is $" << static_cast(grossPay) << endl; + cout << "The net pay is $" << static_cast(netPay) << endl; + cout << "We hoped you enjoyed this program" << endl; +} diff --git a/Homework/HW6/paycheck-exercise-5.cpp b/Homework/HW6/paycheck-exercise-5.cpp new file mode 100644 index 0000000..4a0b896 --- /dev/null +++ b/Homework/HW6/paycheck-exercise-5.cpp @@ -0,0 +1,80 @@ +// This program takes two numbers (pay rate & hours) +// and multiplies them to get grosspay +// it then calculates net pay by subtracting 15% + +// JESUS HILARIO HERNANDEZ +#include +#include +using namespace std; + +//Function prototypes +void printDescription(); +float computeGross(float, int, float); +float computeNet(float, int, float); + +int main() +{ + float payRate; + float grossPay; + float netPay; + int hours; + + cout << setprecision(2) << fixed; + cout << "Welcome to the Pay Roll Program" << endl; + + printDescription(); //Call to Description function + + cout << "Please input the pay per hour" << endl; + cin >> payRate; + + + cout << endl << "Please input the number of hours worked" << endl; + cin >> hours; + cout << endl << endl; + + // Fill in the code to output grosspay + cout << "The gross pay is $" << static_cast(computeGross(payRate,hours,grossPay)) << endl; + cout << "The net pay is $" << static_cast (computeNet(payRate,hours,netPay)) << endl; + cout << "We hoped you enjoyed this program" << endl << endl; + + return 0; +} + +// ******************************************************************** +// printDescription +// +// task: This function prints a program description +// data in: none +// data out: none +// +// ******************************************************************** + +void printDescription() //The function heading +{ + cout << "************************************************" << endl << endl; + cout << "This program takes two numbers (pay rate & hours)" << endl; + cout << "and multiplies them to get gross pay " << endl; + cout << "it then calculates net pay by subtracting 15%" << endl; + cout << "************************************************" << endl << endl; +} + +// ********************************************************************* +// computePaycheck +// +// task: This function takes rate and time and multiples them to +// get gross pay and then finds net pay by subtracting 15%. +// data in: pay rate and time in hours worked +// data out: the gross and net pay +// +// ******************************************************************** + +float computeGross(float rate, int time, float gross) +{ + // Fill in the code to find grosspay and net pay + return gross = rate * time; +} + +float computeNet(float rate, int time, float net) +{ + return net = (rate * time) - ((rate * time) * .15); +} diff --git a/Homework/HW6/proverb-1-exercise-1.cpp b/Homework/HW6/proverb-1-exercise-1.cpp new file mode 100644 index 0000000..f6a0c1b --- /dev/null +++ b/Homework/HW6/proverb-1-exercise-1.cpp @@ -0,0 +1,39 @@ +// This program prints the proverb +// "Now is the time for all good men to come to the aid of their party" +// in a function (procedure) called Proverb that is called by the main function + +//JESUS HILARIO HERNANDEZ + +#include +using namespace std; + +void writeProverb(); //This is the prototype for the writeProverb function + +int main() +{ + + // Fill in the code to call the writeProverb function + writeProverb(); + + return 0; + +} + +// ********************************************************************* +// writeProverb +// +// task: This function prints a proverb +// data in: none +// data out: none +// +// ******************************************************************** + +// Fill in the function heading and the body of the function that will print +// to the screen the proverb listed in the comments at the beginning of the +// program + +void writeProverb() +{ + cout << "\"Now is the time for all good men to " + << "come to the aid of their party\"" << endl; +} diff --git a/Homework/HW6/scope-1-exercise-2.cpp b/Homework/HW6/scope-1-exercise-2.cpp new file mode 100644 index 0000000..a9f58b2 --- /dev/null +++ b/Homework/HW6/scope-1-exercise-2.cpp @@ -0,0 +1,92 @@ +#include +#include +using namespace std; + +// This program will demonstrate the scope rules. + +// JESUS HILARIO HERNANDEZ + +const double PI = 3.14; +const double RATE = 0.25; + +void findArea(float, float&); +void findCircumference(float, float&); + +int main() + +{ + cout << fixed << showpoint << setprecision(2); + float radius = 12; + + cout << "Main function outer block" << endl; + cout << "PI, RATE, findArea(), findCircumference(), and radius are active here" << endl << endl; + { + float area; + cout << "Main function first inner block" << endl; + cout << "PI, RATE, findArea(), findCircumference(), radius " + << "and area are active here" << endl << endl; + + // Fill in the code to call findArea here + + cout << "The radius = " << radius << endl; + cout << "The area = " << area << endl << endl; + } + + { + float radius = 10; + float circumference; + + cout << "Main function second inner block" << endl; + cout << "PI, RATE, findArea(), findCircumference(), radius, and " + << "circumference are active here" << endl << endl; + + // Fill in the code to call findCircumference here + cout << "The radius = " << radius << endl; + cout << "The circumference = " << circumference << endl << endl; + + } + + cout << "Main function after all the calls" << endl; + cout << "PI, RATE, findArea(), findCircumference(), " + << "and radius are active here" << endl << endl; + return 0; +} + +// ********************************************************************* +// findArea +// +// task: This function finds the area of a circle given its radius +// data in: radius of a circle +// data out: answer (which alters the corresponding actual parameter) +// +// ******************************************************************** + +void findArea(float rad, float& answer) +{ + + cout << "AREA FUNCTION" << endl << endl; + cout << "PI, RATE, rad, and answer are active here"<< endl << endl; + + // FILL in the code, given that parameter rad contains the radius, that + // will find the areato be stored in answer + +} + +// ****************************************************************************** +// findCircumference +// +// task: This function finds the circumference of a circle given its radius +// data in: radius of a circle +// data out: distance (which alters the corresponding actual parameter) +// +// ***************************************************************************** + +void findCircumference(float length, float& distance) +{ + cout << "CIRCUMFERENCE FUNCTION" << endl << endl; + cout << "PI, RATE, findArea(), length, and distance are active here" << endl << endl; + + // FILL in the code, given that parameter length contains the radius, + // that will find the circumference to be stored in distance + +} diff --git a/Homework/HW6/scope-1-exercise-3.cpp b/Homework/HW6/scope-1-exercise-3.cpp new file mode 100644 index 0000000..ae24c00 --- /dev/null +++ b/Homework/HW6/scope-1-exercise-3.cpp @@ -0,0 +1,95 @@ +#include +#include +#include +using namespace std; +// This program will demonstrate the scope rules. + +// JESUS HILARIO HERNANDEZ + +const double PI = 3.14; +const double RATE = 0.25; + +void findArea(float, float&); +void findCircumference(float, float&); + +int main() + +{ + cout << fixed << showpoint << setprecision(2); + float radius = 12; + + cout << "Main function outer block" << endl; + cout << "PI, RATE, findArea(), findCircumference(), " + << "and radius are active here" << endl << endl; + { + float area; + cout << "Main function first inner block" << endl; + cout << "PI, RATE, findArea(), findCircumference(), radius " + << "and area are active here" << endl << endl; + + // Fill in the code to call findArea here + findArea(radius, area); + + cout << "The radius = " << radius << endl; + cout << "The area = " << area << endl << endl; + } + + { + float radius = 10; + float circumference; + + cout << "Main function second inner block" << endl; + cout << "PI, RATE, findArea(), findCircumference(), radius, and " + << "circumference are active here" << endl << endl; + + // Fill in the code to call findCircumference here + findCircumference(radius, circumference); + + cout << "The radius = " << radius << endl; + cout << "The circumference = " << circumference << endl << endl; + } + + cout << "Main function after all the calls" << endl; + cout << "PI, RATE, findArea(), findCircumference(), " + << "and radius are active here" << endl << endl; + + return 0; +} + +// ********************************************************************* +// findArea +// +// task: This function finds the area of a circle given its radius +// data in: radius of a circle +// data out: answer (which alters the corresponding actual parameter) +// +// ******************************************************************** + +void findArea(float rad, float& answer) +{ + cout << "AREA FUNCTION" << endl << endl; + cout << "PI, RATE, rad, and answer are active here"<< endl << endl; + + // FILL in the code, given that parameter rad contains the radius, that + // will find the areato be stored in answer + answer = PI * (pow(rad, 2)); +} + +// ****************************************************************************** +// findCircumference +// +// task: This function finds the circumference of a circle given its radius +// data in: radius of a circle +// data out: distance (which alters the corresponding actual parameter) +// +// ***************************************************************************** + +void findCircumference(float length, float& distance) +{ + cout << "CIRCUMFERENCE FUNCTION" << endl << endl; + cout << "PI, RATE, findArea(), length, and distance are active here" << endl << endl; + + // FILL in the code, given that parameter length contains the radius, + // that will find the circumference to be stored in distance + distance = (2 * PI) * length; +} diff --git a/InputValidation/YorNCheck.cpp b/InputValidation/YorNCheck.cpp new file mode 100644 index 0000000..180f532 --- /dev/null +++ b/InputValidation/YorNCheck.cpp @@ -0,0 +1,46 @@ +//****************************************** +// This program check for valid user input. +// In this case the characters Y or N +// +// By: Jesus Hilario Hernandez +// Last Updated: December 5, 2016 +//****************************************** +#include +using namespace std; + +int main() +{ + // Variables + char letter; + + // Ask user to enter Y or N + cout << "Would you like to continue (Y/N)? "; + // Receive user input + cin >> letter; + // Error check algorithim + while (!((letter == 'y') || (letter == 'Y') || (letter == 'n') || (letter == 'N'))) + { + // Explain error + cout << "ERROR: a Y or an N must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + // Receive input again + cin >> letter; + } + + // Display letter entered + if (letter == 'y' || letter == 'Y') + { + cout << "You've entered " << letter << ". Let's continue!" << endl; + } + else if (letter == 'n' || letter == 'N') + { + cout << "Since you've entered " << letter + << "Let's not continute. :(" << endl; + } + + + return 0; +} diff --git a/InputValidation/doubleCheck.cpp b/InputValidation/doubleCheck.cpp new file mode 100644 index 0000000..47bf5af --- /dev/null +++ b/InputValidation/doubleCheck.cpp @@ -0,0 +1,35 @@ +//***************************************** +// This program check for valid user input. +// In this case a double must be entered. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 5, 2016 +//***************************************** +#include +using namespace std; + +int main() +{ + // Variables + double num; + + // Ask user to enter a number + cout << "Enter you favorite number: "; + + // Error check and receive user input + while (!(cin >> num)) + { + // Explain error + cout << "ERROR: a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + + // Display user's number + cout << "Your favorite number is: " << num << endl; + // Salutation + cout << "Good bye! Thanks" << endl; + return 0; +} diff --git a/InputValidation/input-val-functions-double-and-ints.cpp b/InputValidation/input-val-functions-double-and-ints.cpp new file mode 100644 index 0000000..7b63541 --- /dev/null +++ b/InputValidation/input-val-functions-double-and-ints.cpp @@ -0,0 +1,40 @@ +// Function prototype +int inputVal(int); // Error checking for int +double inputVal(double); // Error checking for double + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using integers. * +//********************************************************* +// Input validation function for int +int inputVal(int num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} + +//********************************************************* +// Definition of function inputVal. * +// Checks for valid input when using doubles. * +//********************************************************* +double inputVal(double num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "Sorry, a number must be entered..." << endl; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} diff --git a/InputValidation/input-val-int.cpp b/InputValidation/input-val-int.cpp new file mode 100644 index 0000000..edfeca7 --- /dev/null +++ b/InputValidation/input-val-int.cpp @@ -0,0 +1,28 @@ +//************************************************ +// This program uses a while loop to error check +// for valid user input. In this case and int. +// +// By: Jesus Hilario Hernandez +// December 3, 2016 +//************************************************ +#include +using namespace std; + +int main() +{ + int num; + // Ask user to enter and number + cout << "Enter a number: "; + while (!(cin >> num)) + { + // Explain error + cout << "ERROR: a number must be entered"; + // Clear previous input + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + // Let user know the number that they've entered + cout << "The number you\'ve entered is: " << num << endl; + return 0; +} \ No newline at end of file diff --git a/InputValidation/input-validation-using-while-loops.cpp b/InputValidation/input-validation-using-while-loops.cpp new file mode 100644 index 0000000..5aafe74 --- /dev/null +++ b/InputValidation/input-validation-using-while-loops.cpp @@ -0,0 +1,73 @@ +//******************************************************************** +//This program displays a list of numbers and their squares. +// +//By: JESUS HILARIO HERNANDEZ +//Last Updated: December 6th, 2016 +//******************************************************************** +#include +using namespace std; + +int main() +{ + + /* Input validation when using numbers. */ + int number; + + cout << "Enter a number in the range 1-10: "; + while (!(cin >> number) || (number < 1 || number > 10)) + { + // Explain error + cout << "ERROR: A number must be pressed.\n" + << "Enter a value in the range 1-10: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + + cout << "You entered the number " << number << endl; + + + /* Input validation when using characters */ + char choice; + + cout << "Enter Y or N: "; + cin >> choice; + + while (!(choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N')) + { + cout << "ERROR: Either Y or N must be pressed.\n" + << "Enter Y or N: "; + // clear input stream + cin.clear(); + // discard previous input + cin.ignore(1200, '\n'); + // enter choice again + cin >> choice; + } + cout << "You have chosen " << choice << endl; + + + /* Input validation when using strings */ + + string stringChoice; + + cout << "Enter \"yes\" or \"no\": "; + cin >> stringChoice; + + while (!(stringChoice == "yes") && !(stringChoice == "no")) + { + cout << "ERROR: You must type either \"yes\" or \"no\".\n" + << "Enter \"yes\" or \"no\": "; + // clear input stream + cin.clear(); + // discard previous input + cin.ignore(1200, '\n'); + // Re-enter choice again + cin >> stringChoice; + } + + cout << "You have enter: " << stringChoice << endl; + + return 0; +} diff --git a/InputValidation/intCheck.cpp b/InputValidation/intCheck.cpp new file mode 100644 index 0000000..e28a4a0 --- /dev/null +++ b/InputValidation/intCheck.cpp @@ -0,0 +1,34 @@ +//******************************************** +// This program check for valid user input. +// In this cas the user must enter an integer. +// +// By: Jesus HIlario Hernandez +// Last Updated: December 5, 2016 +//******************************************** +#include +using namespace std; + +int main() +{ + // Variables + int num; + + // Ask user to enter a number + cout << "Enter your favorite number: "; + + // Error Checkin algorithim + while (!(cin >> num)) + { + // Explain error + cout << "ERROR: a number must be entered: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + // Display the number the user has entered + cout << "Your favorite number is: " << num << endl; + // Salutation + cout << "Thanks. Bye." << endl; + return 0; +} diff --git a/InputValidation/intRangeCheck.cpp b/InputValidation/intRangeCheck.cpp new file mode 100644 index 0000000..9715fd0 --- /dev/null +++ b/InputValidation/intRangeCheck.cpp @@ -0,0 +1,35 @@ +//******************************************************* +// This program check for valid user input. +// In this case in integer and the number from 1 thru 10. +// +// By: Jesus Hilario Hernandez +// Last Updated: December 5, 2016 +//****************************************************** +#include +using namespace std; + +int main() +{ + // Variables + int num; + + // Ask user to enter a number from 1 and 10; + cout << "Choose a number from 1 to 10: "; + + // Receive user input and Error check + while (!(cin >> num) || (num < 1 || num > 10)) + { + // Explain Error + cout << "ERROR: You must enter a number between 1 and 10: "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(132, '\n'); + } + + // Display number entered + cout << "You've entered " << num << ". That's it!" << endl; + // Salutation + cout << "Thanks. Bye.!" << endl; + return 0; +} diff --git a/InputValidation/number.cpp b/InputValidation/number.cpp new file mode 100644 index 0000000..7184b4b --- /dev/null +++ b/InputValidation/number.cpp @@ -0,0 +1,31 @@ +//**************************************************** +// This program uses an algorithm for error checking +// and input validation when using numbers. +// +// By: Jesus Hilario Hernandez +// Last updated: December 2, 2016 +//**************************************************** +#include +using namespace std; + +int main() +{ + // Variables + int number; + + // Ask user to enter a number + cout << "Enter an number: "; + + while (!(cin >> number)) + { + // Explain error + cout << "I'm sorry you've not entered a number. Try again:"; + // Clear input stream + cin.clear(); + // discard previous input from user + cin.ignore(123, '\n'); + } + + cout << "You've entered " << number << endl; + return 0; +} diff --git a/InputValidation/number2.cpp b/InputValidation/number2.cpp new file mode 100644 index 0000000..60a755b --- /dev/null +++ b/InputValidation/number2.cpp @@ -0,0 +1,11 @@ +// Receive into selectBook variable + // Error check for input validation + while (!(cin >> selectBook) || (selectBook < 1 || selectBook > 10)) // Error Check for valid input + { + // Describe error + cout << "ERROR: you must choose a number from 1 to 10."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } diff --git a/Loops/deciding-which-loop-to-use.txt b/Loops/deciding-which-loop-to-use.txt new file mode 100644 index 0000000..1467bd8 --- /dev/null +++ b/Loops/deciding-which-loop-to-use.txt @@ -0,0 +1,16 @@ + +THE WHILE LOOP: The while loop is a conditional loop, which means it repeats as long as a particular condition exists. +It is alos a pretest loop, so it is ideal in situations where you do not want the loop to iterate if the condition is +false from the beginning. For example, validating input that has been read and reading lists of dat terminated by a +sentinel value are good applications of the while loop. + +THE DO-WHILE LOOP: The do-while loop is also a conditional loop. Unlike the while loop, however, do-while is a posttest loop. +It is ideal in situations where you always want the loop to iterate at least once. The do-while loop is a good choice for +repeating a menu. + +THE FOR LOOP: The for loop is a pretest loop that has built-in expressions for (initalizing, testing, and updating). These +expressions make it very convenient to use a counter variable to control the number of iterations that the loop performs. +The initialization expression can initialize the counter variable to a starting value, the test expression can test the +counter variable to determine whether it holds the maximum value, and the update expression can increment the counter +variable. The for loop is ideal in situations where the exact number of iterations is known. + diff --git a/Loops/do-while-enter-a-letter.cpp b/Loops/do-while-enter-a-letter.cpp new file mode 100644 index 0000000..6f2d1da --- /dev/null +++ b/Loops/do-while-enter-a-letter.cpp @@ -0,0 +1,22 @@ +// JESUS HILARIO HERNANDEZ +// Last Modified: October 4th, 2016 + +#include +using namespace std; + +int main() +{ + char letter = 'a'; + + do + { + cout << "Please enter a letter" << endl; + cin >> letter; + cout << "The letter you entered is " << letter << endl; + + //Notify user that pressing x will exit the loop. + cout << "\nPRESS x IF YOU WISH TO EXIT.\n\n"; + }while (letter != 'x'); + + return 0; +} diff --git a/Loops/do-while-loop-membership-menu.cpp b/Loops/do-while-loop-membership-menu.cpp new file mode 100644 index 0000000..698c0e4 --- /dev/null +++ b/Loops/do-while-loop-membership-menu.cpp @@ -0,0 +1,75 @@ +// This program displays a menu and asks the user to make a +// selection. A do-while loops repeats the program untill the +// user selects item 4 from the menu. +// +// Jesus Hilario Hernandez +// Date modified: October 2, 2016 +#include +#include +using namespace std; + +int main() +{ + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Constants for member rates + const double ADULT = 40.0, + CHILD = 20.0, + SENIOR = 30.0; + + // Variables + int choice; // Menu choices + int months; // Number of months + double charges; // Monthly charges + + //Set up numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + //Display the menu. + cout << "\n\t\tHealth Club Membership Menu\n\n"; + cout << "1. Standard Adult Membership\n"; + cout << "2. Child Membership\n"; + cout << "3. Senior Citizen Membership\n"; + cout << "4. Quit the Program\n\n"; + cin >> choice; + + //Validate the menu selection. + while (choice < ADULT_CHOICE || choice > QUIT_CHOICE) + { + cout << "Please enter a valid menu choice: "; + cin >> choice; + } + + //Process the user's choice. + if (choice != QUIT_CHOICE) + { + //Get the number of months. + cout << "For how many months? "; + cin >> months; + + //Respond to the user's menu selection. + switch (choice) + { + case ADULT_CHOICE: + charges = months * ADULT; + break; + case CHILD_CHOICE: + charges = months * CHILD; + break; + case SENIOR_CHOICE: + charges = months * SENIOR; + } + + //Display the monthly charges. + cout << "The total charges are $" + << charges << endl; + } + } while (choice != QUIT_CHOICE); + return 0; +} diff --git a/Loops/do-while-switch-user-menu.cpp b/Loops/do-while-switch-user-menu.cpp new file mode 100644 index 0000000..e1411a9 --- /dev/null +++ b/Loops/do-while-switch-user-menu.cpp @@ -0,0 +1,100 @@ +// This program displays a hot beverage menu and prompts the user to +// make a selection. A switch statement determines which item the user +// has chosen. A do-while loop repeats until the user selects item E +// from the menu. + +// JESUS HILARIO HERNANDEZ + +#include +#include +using namespace std; + + + +int main() +{ + // Fill in the code to define an integer variable called number, + // a floating point variable called cost, + // and a character variable called beverage + int number; + float cost; + char beverage; + + bool validBeverage; + + cout << fixed << showpoint << setprecision(2); + + + do + { + cout << endl << endl; + cout << "Hot Beverage Menu" << endl << endl; + cout << "A: Coffee $1.00" << endl; + cout << "B: Tea $ .75" << endl; + cout << "C: Hot Chocolate $1.25" << endl; + cout << "D: Cappuccino $2.50" << endl <> beverage; + + switch(beverage) + { + case 'a': + case 'A': + case 'b': + case 'B': + case 'c': + case 'C': + case 'd': + case 'D': validBeverage = true; + break; + default: validBeverage = false; + } + + if (validBeverage) + { + cout << "How many cups would you like?" << endl; + // Fill in the code to read in number + cin >> number; + } + // Fill in the code to begin a switch statement + // that is controlled by beverage + switch (beverage) + { + case 'a': + case 'A': cost = number * 1.0; + cout << "The total cost is $ " << cost << endl; + break; + // Fill in the code to give the case for tea ( $0.75 a cup) + case 'b': + case 'B': cost = number * 0.75; + cout << "The total cost is $ " << cost << endl; + break; + // Fill in the code to give the case for hot chocolate ($1.25 a cup) + case 'c': + case 'C': cost = number * 1.25; + cout << "The total cost is $ " << cost << endl; + break; + // Fill in the code to give the case for cappuccino ($2.50 a cup) + case 'd': + case 'D': cost = number * 2.50; + cout << "The total cost is $ " << cost << endl; + break; + + case 'e': + case 'E': cout << " Please come again" << endl; + break; + default:cout << "Invalid selection."<< endl; + cout << " Try again please" << endl; + } + + + // Fill in the code to finish the do-while statement with the + // condition that beverage does not equal E or e. + } while(beverage != 'e' || beverage != 'E'); + + // Fill in the appropriate return statement + return 0; +} diff --git a/Loops/for-loop-accumulator-running-total-daily-sales.cpp b/Loops/for-loop-accumulator-running-total-daily-sales.cpp new file mode 100644 index 0000000..0ff41e9 --- /dev/null +++ b/Loops/for-loop-accumulator-running-total-daily-sales.cpp @@ -0,0 +1,36 @@ +//******************************************************************** +// This program takes daily sales figures over a period of time +// and calculates their total. +// +// JESUS HILARIO HERNANDEZ +// Last updated: October 7, 2016 +// +//******************************************************************** + +#include +#include +using namespace std; + +int main() +{ + int days; // Number of days + double total = 0.0; // Accumulator, initialized with 0 + + // Get the number of days. + cout << "For how many days do you have sales figures? "; + cin >> days; + + // Get the sales for each day and acculate a total. + for (int count = 1; count <= days; count++) + { + double sales; + cout << "Enter the sales for day " << count << ": "; + cin >> sales; + total += sales; // Accumulate the running total. + } + + // Display the toal sales. + cout << fixed << showpoint << setprecision(2); + cout << "The total sales are $" << total << endl; + return 0; +} diff --git a/Loops/for-loop-average-test-scores.cpp b/Loops/for-loop-average-test-scores.cpp new file mode 100644 index 0000000..a143686 --- /dev/null +++ b/Loops/for-loop-average-test-scores.cpp @@ -0,0 +1,93 @@ +//************************************************************* +// +// This program averages test scores. It asks the user for the +// number of students and the number of test scores per student. +// +// By: Jesus Hilario Hernandez +// Used from: Gaddis, "Starting Out With C++: From Control +// Structures Through Objects." +// +// Last modified: October 8, 2016. +// +//************************************************************* +#include +#include +using namespace std; + +int main () +{ + int numStudents, // Number of students + numTests; // Number of tests per student + double total, // Accumulator for total scores + average; // Average test score + + // Numeric output formatting + cout << fixed << showpoint << setprecision(1); + + // Get number of students + cout << "This program aveerages test scores.\n"; + cout << "For how many students do you have test scores? "; + + // Input Validation + while(!(cin >> numStudents) || numStudents < 0) + { + // Explain the error + cout << "\nERROR: You must have entered a positive number." << endl; + cout << "For how many students do you have test scores? "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + + // Get number of test scores per student. + cout << "\nHow many test scores does each student have? "; + + // Input validation + while(!(cin >> numTests) || numTests < 0) + { + // Explain the error + cout << "\nERROR: You must have entered a positive number." << endl; + cout << "How many test scores does each student have? "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + + + // Determine each student's average score. + for (int student = 1; student <= numStudents; student++) + { + total = 0; // Initialize the accumulator + for (int test = 1; test <= numTests; test++) + { + double score; + cout << "\nEnter score " << test << " for "; + cout << "student " << student << ": "; + // Input validation + while(!(cin >> score) || score < 0) + { + // Explain the error + cout << "\nERROR: You must have entered a positive number." << endl; + cout << "Enter score " << test << " for "; + cout << "student " << student << ": "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + // Keeping a running total + total += score; + } + // Calculate average test score + average = total / numTests; + cout << "\nThe average score for student " << student ; + cout << " is " << average << ".\n\n"; + } + + + + + return 0; +} diff --git a/Loops/for-loop-digital-clock.cpp b/Loops/for-loop-digital-clock.cpp new file mode 100644 index 0000000..82e9df9 --- /dev/null +++ b/Loops/for-loop-digital-clock.cpp @@ -0,0 +1,52 @@ +//******************************************************************** +// This program simulates a digital clock. It displays +// the hours:minutes:seconds. +// +// JESUS HILARIO HERNANDEZ +// Last updated: October 8, 2016 +// +//******************************************************************** + +#include +#include +using namespace std; + +int main() +{ + int count_hour = 0, count_minutes = 0, count_seconds = 0; + cout << fixed << right; // Formatting output + + /* + * The fill() member function of cout changes the fill character, which + * is a space by default. In the program segment above, the fill function + * causes a zero to be printed in front of all single digit numbers. + */ + + cout.fill('0'); + // Hour loop + for (int hours = 0; hours < 24; hours ++) + { + count_hour++;// Hour counter + // Minute loop + for (int minutes = 0; minutes < 60; minutes++) + { + count_minutes++;// Minute counter + // Second loop + for (int seconds = 0; seconds < 60; seconds++) + { + count_seconds++; // Second counter + cout << setw(2) << hours << ":"; + cout << setw(2) << minutes << ":"; + cout << setw(2) << seconds << endl; + } + } + } + // Total number of iterations for hours loop + cout << "The hours for loop iterates " << count_hour << " times." << endl; + // Total number of iterations for minutes loopa + cout << "The minutes for loop iterates " << count_minutes << " times."<< endl; + // Total number of iterations for minutes loop + cout << "The seconds for loop iterates " << count_seconds << " times." << endl; + + return 0; +} diff --git a/Loops/for-loop-pyramids.cpp b/Loops/for-loop-pyramids.cpp new file mode 100644 index 0000000..844c3be --- /dev/null +++ b/Loops/for-loop-pyramids.cpp @@ -0,0 +1,42 @@ +//************************************************** +// This program displays a right side up pyramid, +// as well as an upside down pyramid. +// +// By: JESUS HILARIO HERNANDEZ +// Last modified: October 14, 2016 +//************************************************** +#include +#include +#include +using namespace std; + +int main() +{ + + // Display Pattern A + cout << "Pattern A looks like this:" << endl; + + // Right side up pyramid for loop + for (int row = 1; row <= 13; ++row) + { + for (int col = 1; col <= row; ++col) + { + cout << "+"; + } + cout << endl; + } + + // Display Pattern B + cout << "\nHere is pattern B: " << endl; + + // Upside down pyramid for loop + for (int row = 13; row >= 1; --row) + { + for (int col = 1; col <= row; ++ col) + { + cout << "+"; + } + cout << endl; + } + return 0; +} diff --git a/Loops/for-loops-counters-running-totals.cpp b/Loops/for-loops-counters-running-totals.cpp new file mode 100644 index 0000000..b154ae7 --- /dev/null +++ b/Loops/for-loops-counters-running-totals.cpp @@ -0,0 +1,83 @@ +//******************************************************************** +// This program counter, running totals, averages, and sums +// 130 kph (in 10kph increments) to mph. +// +// JESUS HILARIO HERNANDEZ +// Last updated: October 5, 2016 +// +//******************************************************************** + +#include +#include +using namespace std; + +int main() +{ + int counter = 0, number = 1; + for (int x = 1; x <= 50; x++) + { + counter++; + cout << number++ <<". I love to program" << endl; + } + cout << "There are " << counter << " \"I love to program\" statements.\n" << endl; + + + for (int count = 0; count < 6; count++) + { + cout << (count + count) << endl; + } + cout << endl; + + float count3 = 0, sum3 = 0, average3; + for (int value = -5; value <= 5; value++) + { + count3++; + sum3 = sum3 + value; + cout << value << endl; + } + cout << "There are " << count3 << " numbers between -5 and 5." << endl; + cout << "The sum of the numbers between -5 and 5 is " << sum3 << "." << endl; + + average3 = sum3 / count3; + cout << "The average of the all numbers between -5 and 5 is " << average3 << "." << endl; + cout << endl; + + int namecount = 1; + for (int name = 1; name <= 10; name++) + { + cout << namecount << ". JESUS HILARIO HERNANDEZ." << endl; + namecount++; + } + cout << endl; + + float oddcounter = 0, sum = 0, average; + for (int odd = 1; odd <= 49; odd += 2) + { + oddcounter++; + sum = sum + odd; + cout << "all odds: " << odd << endl; + } + cout << "There are " << oddcounter << " odd numbers from 1 - 49. " << endl; + cout << "The sum of all odd numbers from 1 - 49 is " << sum << "." << endl; + + average = sum / oddcounter; + cout << "The average of all odd numbers from 1 - 49 is " << average << "." << endl; + cout << endl; + + float fivesSum = 0, fivesCount = 0, fivesAverage; + for (int fives = 0; fives <= 100; fives += 5) + { + fivesCount++; + fivesSum = fivesSum + fives; + cout << "by fives: " << fives << endl; + } + cout << "The total number of 5's including 0 betwee 0 and 100 is " << fivesCount << endl; + cout << "The sum total of every multiple of 5 between 0 and 100, " + << "including zero is " << fivesSum << "." << endl; + + fivesAverage = fivesSum / fivesCount; + cout << "The average of the sum total of every multiple of 5 " + << "between 0 - 100, including zero is " << fivesAverage << "." << endl; + cout << endl; + return 0; +} diff --git a/Loops/list-of-squared-numbers-using-while-and-for-loops.cpp b/Loops/list-of-squared-numbers-using-while-and-for-loops.cpp new file mode 100644 index 0000000..244acd6 --- /dev/null +++ b/Loops/list-of-squared-numbers-using-while-and-for-loops.cpp @@ -0,0 +1,42 @@ +//******************************************************************** +// This program displays a list of numbers and +// their squares. +// +// JESUS HILARIO HERNANDEZ +// Last updated: October 5, 2016 +// +//******************************************************************** + +#include +using namespace std; + +int main() +{ + /* Using a while loop */ + + const int MIN_NUMBER = 1, // Strating number to square + MAX_NUMBER = 10; // Maximum number to square + + int num = MIN_NUMBER; // Counter + + cout << "Number Number Squared\n"; + cout << "-------------------------\n"; + while (num <= MAX_NUMBER) + { + cout << num << "\t\t" << (num * num) << endl; + num++; //Increment the counter. + } + + /* Using a for loop */ + + cout << "\nNumber Number Squared\n"; + cout << "-------------------------\n"; + for (num = MIN_NUMBER; num <= MAX_NUMBER; num++) + { + + cout << num << "\t\t" << (num * num) << endl; + } + + + return 0; +} diff --git a/Loops/multiple-statements-in-for-loops.cpp b/Loops/multiple-statements-in-for-loops.cpp new file mode 100644 index 0000000..6b8dc34 --- /dev/null +++ b/Loops/multiple-statements-in-for-loops.cpp @@ -0,0 +1,42 @@ +//******************************************************************** +// This program demonstrates how to use multiple +// statememts in the initialization and update expressions +// +// JESUS HILARIO HERNANDEZ +// Last updated: October 5, 2016 +// +//******************************************************************** + +#include +using namespace std; + +int main() +{ + int x, y; + // loop's initialization expression is : + // x = 1, y = 1 + for (x = 1, y = 1; x <= 5; x++) + { + cout << x << " plus " << y + << " equals " << (x + y) + << endl; + } + + cout << endl; + + /** + * same as above + * however, along with two initialization expressions + * we'll add two update expression statements + */ + + for (x = 1, y = 1; x <= 5; x++, y++) + { + cout << x << " plus " << y + << " equals " << (x + y) + << endl; + } + + + return 0; +} diff --git a/Loops/nested-loops.cpp b/Loops/nested-loops.cpp new file mode 100644 index 0000000..b4bdf9e --- /dev/null +++ b/Loops/nested-loops.cpp @@ -0,0 +1,78 @@ +// This program finds the average time spent programming by a student +// each day over a three day period. + +// JESUS HILARIO HERNANDEZ + +#include +using namespace std; + +int main() +{ + int numStudents; + float numHours, + total, //biology total + total2, //programming total + average, //biology average + average2, //programming average + numHours2; + int student, + day = 0; // these are the counters for the loops + int n; //defined by user. + + cout << "This program will find the average number of hours a day" + << " that a student studying biology and programming.\n\n"; + cout << "How many students are there ?" << endl; + cin >> numStudents; + + //ask how many days + cout << "How many days are they there? " << endl; + //receive number of days + cin >> n; + + //check for positive number. + if (n > 0) + for( student = 1; student <= numStudents; student++) + { + total = 0; //initial total biology + total2 = 0;//initial total programming + for(day = 1; day <= n; day++) //changed to n number of days + { + cout << "how many hours spent studying biology by student " + << student <<" on day " << day << "." << endl; + cin >> numHours; + + cout << "how many hours spent studying programming by student " + << student <<" on day " << day << "." << endl; + cin >> numHours2; + + total = total + numHours; //total for biology + total2 = total2 + numHours2; //total for programming + average = total / n; //average for biology + average2 = total2 / n; //average for programming + + cout << "The average number of hours per day spent studying biology by " + << "student " << student << " is " << average + << endl; //diaplay average biology + + cout << "The average number of hours per day spent studying programming by " + << "student " << student << " is " << average2 + << endl; //display average programming + + if(average > average2) + { //if-else if used to print, on average, which subject spent most time on + cout << "Student " << student << " spent more hours studying biology " + << "than programming."<< endl; + } + else if (average < average2) + { + cout << "Student " << student << " spent more hours studying programming " + << "than biology. " << endl; + } + } + } + //if integer is a negative number. + else + cout << "Invalid input - integer must be positive." << endl; + + return 0; +} diff --git a/Loops/sentinel-in-while-loop.cpp b/Loops/sentinel-in-while-loop.cpp new file mode 100644 index 0000000..82b5377 --- /dev/null +++ b/Loops/sentinel-in-while-loop.cpp @@ -0,0 +1,46 @@ +// This program illustrates the use of a sentinel in a while loop. +// The user is asked for monthly rainfall totals until a sentinel +// value of -1 is entered. Then the total rainfall is displayed + +// JESUS HILARIO HERNANDEZ + +#include +using namespace std; + +int main() +{ + // Fill in the code to define and initialize to 1 the variable month + float total = 0, rain; + int month = 1; + + cout << "Enter the total rainfall for month " << month << endl; + cout << "Enter -1 when you are finished" << endl; + // Fill in the code to read in the value for rain + cin >> rain; + + // Fill in the code to start a while loop that iterates + // while rain does not equal -1 + while(rain != -1) + { + // Fill in the code to update total by adding it to rain + total += rain; + // Fill in the code to increment month by one + month++; + + cout << "Enter the total rainfall in inches for month " + << month << endl; + cout << "Enter -1 when you are finished" << endl; + // Fill in the code to read in the value for rain + cin >> rain; + } + + if (month == 1) + cout << "No data has been entered" << endl; + + else + cout << "The total rainfall for the " << month-1 + << " months is "<< total << " inches." << endl; + + + return 0; +} diff --git a/Loops/while-loop-1.cpp b/Loops/while-loop-1.cpp new file mode 100644 index 0000000..a3b6df0 --- /dev/null +++ b/Loops/while-loop-1.cpp @@ -0,0 +1,21 @@ +//This program demonstrates a simple while loop. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/30/16 + +#include +using namespace std; + +int main() +{ + int number = 0; + + while (number < 5) + { + cout << "Hello\n"; + number++; + } + cout << "That's all!\n"; + return 0; +} diff --git a/Loops/while-loop-substance-temperature.cpp b/Loops/while-loop-substance-temperature.cpp new file mode 100644 index 0000000..b07ca37 --- /dev/null +++ b/Loops/while-loop-substance-temperature.cpp @@ -0,0 +1,37 @@ +//This program assists a technician in the process +//of checking a substance's temperature. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/30/16 + +#include +using namespace std; + +int main() +{ + const double MAX_TEMP = 102.5; + double temperature; + + //Get the current temperature. + cout << "Enter the substance's Celsius temperature: "; + cin >> temperature; + + //As long as necessary, instruct the technician again + //to adjust the thermostat. + while (temperature > MAX_TEMP) + { + cout << "\nThe temperature is too high. Turn the\n"; + cout << "thermostat down and wait 5 minutes.\n"; + cout << "Then take the Celsius temperature again\n"; + cout << "and enter it here: "; + cin >> temperature; + } + + //Remind the technician to check the temperature + //again in 15 minutes. + cout << "\nThe temperature is acceptable.\n"; + cout << "Check it again in 15 minutes.\n"; + + return 0; +} diff --git a/Loops/while-loop-validating-input.cpp b/Loops/while-loop-validating-input.cpp new file mode 100644 index 0000000..4a382a2 --- /dev/null +++ b/Loops/while-loop-validating-input.cpp @@ -0,0 +1,45 @@ +//this program demonstrates how to avoid +//an infinite loop while validating user +//input with a while loop. + +// Jesus H. Hernandez +// Last modified: Sept. 30, 2016 + +#include + +using namespace std; + +int main() +{ + int age = 0; + char again = 'Y'; + + while (again == 'y' || again == 'Y') + { + //Get age + cout << "How old are you?" << endl; + while (!(cin >> age)) + { + cout << "Must be a number: " << endl; + //to clear input stream + cin.clear(); + //to drop and ignore any content that is is the cin object. + cin.ignore(1900, '\n'); + } + if (age == 18) + cout << "Congratulations, you are old enough to vote!" << endl; + else if (age < 18) + cout << "Don't forget to vote" << endl; + else if (age > 60) + cout << "Don't forget to vote" << endl; + else + cout << "Get the vote out" << endl; + + cout << "Go again? (y/n) "; + cin >> again; //change control variable + + } //end while loop + + cout << "The end." << endl; + return 0; +} diff --git a/Loops/while-loops-input-validation-soccer-teams.cpp b/Loops/while-loops-input-validation-soccer-teams.cpp new file mode 100644 index 0000000..c9ecfb7 --- /dev/null +++ b/Loops/while-loops-input-validation-soccer-teams.cpp @@ -0,0 +1,61 @@ +//This program calculates the number of soccer teams +//that a youth league may create from the number of +//available players. Input valication is demonstrated +//with while loops. + +//JESUS HILARIO HERNANDEZ +//Last modified: 9/30/16 + +#include +using namespace std; + +int main() +{ + //Constants for min and max players + const int MIN_PLAYERS = 9, MAX_PLAYERS = 15; + + //Variables + int players, //Number of available players + teamPlayers, //Number of desired players per team + numTeams, //Number of teams + leftOver; //Number of players left over + + //Get the number of players per team. + cout << "How many players do you wish per team? "; + cin >> teamPlayers; + + //Validate the input. + while (teamPlayers < MIN_PLAYERS || teamPlayers > MAX_PLAYERS) + { + //Explain the error. + cout << "You should have at least " << MIN_PLAYERS + << " but no more than " << MAX_PLAYERS << " per team.\n"; + + //Get the input again. + cout << "How many players do you wish per team? "; + cin >> teamPlayers; + } + + //Get the number of players available. + cout << "How many players available? "; + cin >> players; + + //Validae the input. + while (players <= 0) + { + //Get the input again. + cout << "Please enter 0 or greater: "; + cin >> players; + } + + //Calculate the number of teams. + numTeams = players / teamPlayers; + + //Calculate the number of leftover players. + leftOver = players % teamPlayers; + + //Display the results. + cout << "There will be " << numTeams << " teams with " + << leftOver << " players left over.\n"; + return 0; +} diff --git a/Opt-topics/continue-statement.cpp b/Opt-topics/continue-statement.cpp new file mode 100644 index 0000000..b0e3ad9 --- /dev/null +++ b/Opt-topics/continue-statement.cpp @@ -0,0 +1,47 @@ +//***************************************************** +// This program calculates the charges for DVD rentals. +// +// By: JESUS HILARIO HERNANDEZ +// Last modified: October 17th, 2016 +//***************************************************** +#include +#include +using namespace std; + +int main() +{ + int dvdCount = 1; // DVD counter + int numDVDs; // Number of DVDs rented + double total = 0.0; // Accumulator + char current; // Current release, Y or N. + + // Get the number of DVDs. + cout << "How many DVDs are being rented? "; + cin >> numDVDs; + + // Determine the charges. + do + { + if ((dvdCount % 3) == 0) + { + cout << "DVD #" << dvdCount << " is free!\n"; + continue; // Immediately start the next iteration + } + cout << "Is DVD #" << dvdCount; + cout << " a current release? (Y/N)"; + cin >> current; + if (current == 'Y' || current == 'Y') + { + total += 3.50; + } + else + { + total += 2.50; + } + } while (dvdCount++ < numDVDs); + + // Display the total.] + cout << fixed << showpoint << setprecision(2); + cout << "The total is $" << total << endl; + return 0; +} diff --git a/Projects/BookFlix/AdventureBooksRegean.csv b/Projects/BookFlix/AdventureBooksRegean.csv new file mode 100644 index 0000000..9e13765 --- /dev/null +++ b/Projects/BookFlix/AdventureBooksRegean.csv @@ -0,0 +1,6 @@ +The Lightning Thief (Series) ,Rick Riordan ,2005 +The Sorcerer's Apprentice (Series) ,John Flanagan ,2005 +The Hobbit ,J. R. R. Tolkien ,1966 +Pendragon (Series) ,D. J. MacHale ,2002 +Treasure Island ,Robert Louis Stevenson ,1883 +Harry Potter (Series) ,J. K. Rowling ,1997 diff --git a/Projects/BookFlix/Adventure_authors.txt b/Projects/BookFlix/Adventure_authors.txt new file mode 100644 index 0000000..0d09f71 --- /dev/null +++ b/Projects/BookFlix/Adventure_authors.txt @@ -0,0 +1,4 @@ +John Flanagan +Rick Riordan +Robert Louis Stevenson +J. K. Rowling \ No newline at end of file diff --git a/Projects/BookFlix/Adventure_date.txt b/Projects/BookFlix/Adventure_date.txt new file mode 100644 index 0000000..bfdaf59 --- /dev/null +++ b/Projects/BookFlix/Adventure_date.txt @@ -0,0 +1,4 @@ +2005 +2005 +1883 +1997 \ No newline at end of file diff --git a/Projects/BookFlix/Adventure_descriptions.txt b/Projects/BookFlix/Adventure_descriptions.txt new file mode 100644 index 0000000..9879afc --- /dev/null +++ b/Projects/BookFlix/Adventure_descriptions.txt @@ -0,0 +1,32 @@ + The Rangers, with their shadowy ways, have always made him nervous. And now fifteen-year-old Will + has been chosen as a Ranger's Apprentice. But what he doesn't yet realize is that the Rangers are the + protectors of the kingdom who will fight the battles before the battles reach the people. And there is + a large battle brewing. The exiled Morgarath, Lord of the Mountains of Rain and Night, is gathering his + forces for an attack on the kingdom. This time he will not be denied... $ + Percy Jackson is about to be kicked out of boarding school... again. And that's the least of his + troubles. Lately, myhtological monsters and the gods of Mount Olympus seem to be walking straight out of + the pages of Percy's Greek mythology textbook and into his life. And worse, he's angered a few of them. + Zeus's master lightning bolt has been stolen, and Percy is the prime suspect. + Now Percy and his friends have just ten days to find and return Zeus's stolen property and bring + peace to a warring Mount Olympus. But to succeed on his quest, Percy will have to do more than catch the + true thief: he must come to terms with his father who abandoned him; solve the riddle of the Oracle, which + warns him of betrayal by a friend; and unravel a treachery more powerful than the gods themselves. $ + A mysterious seaman hides at a country inn; cut-throats raid a sleepy English village; + suddenly, young Jim Hawkins becomes the owner of a map leading to a lost tropical island and + a fortune in stolen gold. Three adventures - Jim, Squire Trelawney, and Dr. Livesey - set out + to find the treasure. But they trust the one man they should most fear, Long John Silver. + Charming, brave, ruthless, murderous, Silver fills the squire's ship with pirates. And on the + desolate, fever-infested island, the quest for gold becomes a deadly war of hide and seek. + Desperate defenders against merciless killers battling over a cursed treasure won with blood, + buried with blood, sought with blood. Incredible wealth that Jim and his friends can only + claim... If they survive! $ + Harry Potter has never been the star of a Quiddich team, scoring points while riding + a broom far above the ground. He knows no spells, has never helped to hatch a dragon, and has + never worn a cloak of invisibility. All he knows is a miserable life with the Dursleys, + his horrible aunt and uncle, and their abominable son, Dudley - a great big swollen spoiled + bully. Harry's room is a tiny closet at the foot of the stairs, and he hasn't had a birthday + party in Eleven years. But all that is about to change when a mysterious letter arrives by + owl messenger: a letter with an invitation to an incredible place that Harry - and anyone who + reads about him - will find unforgettable. For it's there that not only friends, aerial sports, + and magic in everything from classes to meals, but a great destiny that's been waiting for + him... if Harry can survive the encounter. $ \ No newline at end of file diff --git a/Projects/BookFlix/Adventure_function.cpp b/Projects/BookFlix/Adventure_function.cpp new file mode 100644 index 0000000..4c7a44e --- /dev/null +++ b/Projects/BookFlix/Adventure_function.cpp @@ -0,0 +1,236 @@ +#include +#include +#include +#include +#include +#include //for rand and srand +#include // for the time +using namespace std; + +// Directives for clearing the screen +#ifdef _WIN32 +char buffer[4] = "cls"; +const char* clearVar = buffer; +#ifdef _WIN64 +char buffer[4] = "cls"; +const char* clearVar = buffer; +#endif +#else +char buffer[6] = "clear"; +const char* clearVar = buffer; +#endif + +void Adventure(); +void clearScreen(); // clear screen +char errorCheckYorN(char); // Error Check for Y or N. + +int main() +{ + int menu_choice; + + cout << "Please choose from the menu.\n"; + cin >> menu_choice; + + if (menu_choice == 1) + { + cout << "You have chosen the Adventure genre.\n" << endl; + Adventure(); + cout << "\n\nHave a nice day!"; + return 0; + } +} + +void Adventure() +{ + // Input Stream Objects + ifstream inputAuthors; // For Authors.txt + ifstream inputTitle; // For Books.txt + ifstream inputDates; // For Date.txt + ifstream inputDescription; // For Discription.txt + + // Output Stream Objects + ofstream keptBooks; // Output Stream Object + + // Constants + const int SIZE = 4, + SELECT_BOOK_1 = 0, + SELECT_BOOK_2 = 1, + SELECT_BOOK_3 = 2, + SELECT_BOOK_4 = 3, + SELECT_BOOK_5 = 4; + + // Variables + string author[SIZE]; //author names + string title[SIZE]; // book titles + string date[SIZE]; // book dates + string description[SIZE]; // book descriptions + + int selectBook; // book selection + char keepBook, // Holds Y or N + anotherSelection; // Holds Y or N to return to adventure menu or not + + // Open input/ouput files + inputAuthors.open("Adventure_authors.txt"); + inputTitle.open("Adventure_titles.txt"); + inputDates.open("Adventure_date.txt"); + inputDescription.open("Adventure_descriptions.txt"); + keptBooks.open("KeptAdventureBooks.txt", ios::out | ios::app); + + + // Select Book from a list + do + { + + clearScreen(); + // Display list of music books + cout << "Here are the available adventure books: \n" << endl; + // Fill arrays with external file data and display contents + for (int count = 0; count < SIZE; count++) + { + getline(inputAuthors, author[count]); + getline(inputTitle, title[count]); + getline(inputDates, date[count]); + getline(inputDescription, description[count], '$'); + cout << '\t' << (count + 1) << ". " + << title[count] << endl; + } + + // Close inputFiles + inputAuthors.close(); + inputTitle.close(); + inputDates.close(); + inputDescription.close(); + + // Ask your to select a book + cout << "Select a book: "; + + // Receive into selectBook variable + // Error check for input validation + while (!(cin >> selectBook) || (selectBook < 1 || selectBook > SIZE)) // Error Check for valid input + { + // Describe error + cout << "ERROR: you must choose a number between 1 and 4.\n"; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + + switch (selectBook) + { + case (SELECT_BOOK_1 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl; + cout << '\t' << title[SELECT_BOOK_1] << ", by "; + cout << author[SELECT_BOOK_1] << endl << endl; + cout << " " << description[SELECT_BOOK_1] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_2 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl; + cout << "'\t'" << title[SELECT_BOOK_2] << ", by "; + cout << author[SELECT_BOOK_2] << endl << endl; + cout << " " << description[SELECT_BOOK_2] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_3 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl; + cout << '\t' << title[SELECT_BOOK_3] << ", by "; + cout << author[SELECT_BOOK_3] << endl << endl; + cout << " " << description[SELECT_BOOK_3] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_4 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl; + cout << '\t' << title[SELECT_BOOK_4] << ", by "; + cout << author[SELECT_BOOK_4] << endl << endl; + cout << " " << description[SELECT_BOOK_4] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + default: + cout << "No book selected." << endl; + } + + // If no. Say ok. + if (keepBook == 'N' || keepBook == 'n') + { + cout << "Ok.\n" << endl; + } + // If yes. Say awesome! + else if (keepBook == 'y' || keepBook == 'Y') + { + cout << "That's Great!\n" << endl; + // Write to output file books kept by user + keptBooks << title[selectBook - 1] << ", " + << author[selectBook -1] << ", " + << date [selectBook -1] << endl; + } + + // Clear screen + clearScreen(); + + // Ask if would like to make another music selection + cout << "Would you like to make another " + << "Adventure genre selection? (Y/N)"; + cin >> anotherSelection; + anotherSelection = errorCheckYorN(anotherSelection); + + } while(anotherSelection == 'y' || anotherSelection == 'Y');// End Do While + + //Close output File + keptBooks.close(); +} + +void clearScreen() +{ + system(clearVar); +} + +char errorCheckYorN(char letter) +{ + while (!(letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N')) + { + // Explain error + cout << "ERROR: you must choose either Y or N." << endl + << "Y for Yes or\n" + << "N for No...\n"; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + // Receive input again + cin >> letter; + } + return letter; +} diff --git a/Projects/BookFlix/Adventure_titles.txt b/Projects/BookFlix/Adventure_titles.txt new file mode 100644 index 0000000..11affac --- /dev/null +++ b/Projects/BookFlix/Adventure_titles.txt @@ -0,0 +1,4 @@ +Ranger's Apprentice: The Ruins of Gorlan +The Lightning Thief +Treasure Island +Harry Potter and the Sorcerer's Stone \ No newline at end of file diff --git a/Projects/BookFlix/GroupProject.cpp b/Projects/BookFlix/GroupProject.cpp new file mode 100644 index 0000000..e5808b1 --- /dev/null +++ b/Projects/BookFlix/GroupProject.cpp @@ -0,0 +1,630 @@ +#include +#include +#include +#include +//#include +#include //for rand and srand +#include // for the time +using namespace std; + +// Directives for clearing the screen +#ifdef _WIN32 +char buffer[4] = "cls"; +const char* clearVar = buffer; +#ifdef _WIN64 +char buffer[4] = "cls"; +const char* clearVar = buffer; +#endif +#else +char buffer[6] = "clear"; +const char* clearVar = buffer; +#endif + +//Function Prototypes +void Romance(); // Romance Genre +void RomanceDes(); // Romance Discriptions +void Adventure(); // Adventure Genre +void Mystery(); // Mystery Genre +void Music(); // Music Genre +void clearScreen(); // Mystery Genre +char errorCheckYorN(char); // Error Check for Y or N. + +int main() +{ + // Variables + int menu_choice; // Holds Menu Choice + char repeat_menu; // To Re-display the menu_choice + + // Clear Screen + clearScreen(); + do + { + cout << "# # "<< endl + << "# # # ###### # #### #### # # ###### ##### #### "<< endl + << "# # # # # # # # # ## ## # # # # "<< endl + << "# # # ##### # # # # # ## # ##### # # # "<< endl + << "# # # # # # # # # # # # # # "<< endl + << "# # # # # # # # # # # # # # # "<< endl + << " ## ## ###### ###### #### #### # # ###### # #### "<< endl + << "###### ####### "<< endl + << "# # #### #### # # # # # # # "<< endl + << "# # # # # # # # # # # # # "<< endl + << "###### # # # # #### ##### # # ## "<< endl + << "# # # # # # # # # # # ## "<< endl + << "# # # # # # # # # # # # # "<< endl + << "###### #### #### # # # ###### # # # "<< endl; + + cout << "\nChoose a genre to begin" << endl; + cout << "\n1. Music " << endl; + cout << "\n2. Romance" << endl; + cout << "\n3. Adventure" << endl; + cout << "\n4. Mystery\n" << endl; + + // Receive into menu_choice + // Error check for input validation + while (!(cin >> menu_choice) || (menu_choice < 1 || menu_choice > 4)) // Error Check for valid input + { + // Describe error + cout << "ERROR: you must choose a number from 1 to 10."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + + switch (menu_choice) + { + + // 1. Music Genre + case 1: + Music(); + break; + + // 2. Romance Genre + case 2: + Romance(); + break; + + // 3. Adventure Genre + case 3: + Adventure(); + break; + + // 4. Mystery Genre + case 4: + Mystery(); + break; + + default: + break; + + } + + // Clear Screen + cout << "\nWould you like to return to the main menu? (Y/N)" << endl; + + cin >> repeat_menu; + + } while (repeat_menu == 'Y' || repeat_menu == 'y'); + + cout << "\nHave a nice day!" << endl; + return 0; +} + +//*************************************************** +// function errorCheckYN check for valid input. * +// In this case the user must enter a Y or and N. * +//*************************************************** +char errorCheckYorN(char letter) +{ + while (!(letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N')) + { + // Explain error + cout << "ERROR: you must choose either Y or N." << endl + << "Y for Yes or\n" + << "N for No..."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + // Receive input again + cin >> letter; + } + return letter; +} + +//*************************************************** +// function to clear screen, using variable * +// created in PPD statement * +//*************************************************** +void clearScreen() +{ + system(clearVar); +} + +//*************************************************** +// Romance Function. * +//*************************************************** +void Romance() +{ + // Variables + const int SIZE = 4; // Holds array size + int position = 0; + char repeat_romancemenu; // Holds Y or N to return to Romance menu or not + int menu_romancechoice; // Holds romance book selection + + // Arrays + string romanceBookInfo[SIZE]; // Holds Romance Book info: author, title, date + + // Input Files + ifstream file; + + do + { + + // Clear the screen + clearScreen(); + + cout << "###### "<< endl + << "# # #### # # ## # # #### ###### "<< endl + << "# # # # ## ## # # ## # # # # "<< endl + << "###### # # # ## # # # # # # # ##### "<< endl + << "# # # # # # ###### # # # # # "<< endl + << "# # # # # # # # # ## # # # "<< endl + << "# # #### # # # # # # #### ###### "; + + // Open input file. + file.open("RomanceBooksAshley.txt"); + + // Display book selection + cout << "\n\n" << endl; + cout << " Author Title Date" << endl << endl; + + // This For loop get contents from the external file + // and Displays the to screen. + for (int count = 0; count < SIZE; count++) + { + // getting from external file + getline(file, romanceBookInfo[count]); + // displays contents to screen + cout << " " << romanceBookInfo[count] << endl; + } + + // Close input file. + file.close(); + + cout << endl << " Choose a book to read the description: "; + + cin >> menu_romancechoice; + cout << endl; + + switch(menu_romancechoice) + { + case 1: + { + // Clear the screen + clearScreen(); + // Display Selction + cout << endl << " " << romanceBookInfo[0] << endl << endl; + // Display Description + cout << "\tWould you risk it all to " << endl + << " change your destiny?" << endl << endl; + + cout << "\tThe last thing Kelsey Hayes thought she'd be" << endl + << " doing this summer was trying to break a 300-year" << endl + << " old Indian curse. With a mysterious white tiger " << endl + << " named Ren. Halfway around the world. But that's" << endl + << " exactly what happened." << endl << endl; + + cout << "\tFace-to-face with dark forces, spellbinding "<< endl + << " magic, and mystical worlds where nothing is " << endl + << " what it seems, Kelsey risks everything to piece " << endl + << " together an ancient prophecy that could break the " << endl + << " curse forever. Packed the epic with magic, " << endl + << " action-adventure, and romance, Tiger's Curse " << endl + << " series will keep you breathless and yearning for " << endl + << " more." << endl; + } + break; + case 2: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[1] << endl << endl; + // Display Description + cout << "\tBack in Oregon, Kelsey tries to pick up the " << endl + << " pieces of her life and push aside her feelings " << endl + << " for Ren. Kelsey Hayes's eighteenth summer was" << endl + << " crazy. The kind of crazy nobody would ever" << endl + << " believe." << endl << endl; + + cout << "\tAside From battling immortal sea monkeys and " << endl + << " trekking the jungles of India, she fell in love " << endl + << " with Ren, a 300-year-old prince." << endl << endl; + + cout << "\tWhen danger suddenly forces Kelsey on another " << endl + << " Indian quest, with Ren's bad-boy brother, " << endl + << " Kishan, the unlikely duo begins to question their " << endl + << " true destiny. Ren's life hangs in the balance--" << endl + << " so does the truth within Kelsey's heart." << endl; + + } + break; + case 3: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[2] << endl << endl; + // Display Description + cout << "\tGalen, a Syrena prince, searches land for a " << endl + << " girl he's heard can communicate with fish. " << endl + << " It's while Emma is on vacation at the beach" << endl + << " that she meets Galen. Although their connection " << endl + << " is immediate and powerful, Galen's not fully convinced " << endl + << " that Emma's the one he's been looking for. That is," << endl + << " until a deadly encounter with a shark proves" << endl + << " that Emma and her Gift may be the only thing that " << endl + << " can save his kingdom. He needs her help�no matter" << endl + << " what the risk." << endl; + + } + break; + case 4: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[3] << endl << endl; + // Display Description + cout << "\tEmma has just learned that her mother is a " << endl + << " long-lost Poseidon princess, and now struggles " << endl + << " with an identity crisis: As a Half-Breed, " << endl + << " she's a freak in the human world and an abomination" << endl + << " in the Syrena realm. Syrena law states all " << endl + << " Half-Breeds should be put to death." << endl << endl; + + cout << "\tAs if that's not bad enough, her mother's " << endl + << " reappearance in the Syrena world turns the " << endl + << " two kingdoms�Poseidon and Triton�against one " << endl + << " another. Which leaves Emma with a decision to make:" << endl + << " Should she comply with Galen's request to keep" << endl + << " herself safe and just hope for the best? Or " << endl + << " should she risk it all and reveal herself�and" << endl + << " her Gift�to save a people she's never known?" << endl; + + } + break; + default: + { + cout << " Invalid answer. Please try again." << endl; + } + break; + + } + cout << endl << " Would you like to return to the Romance menu? (Y/N)" << endl; + + cin >> repeat_romancemenu; + } + while (repeat_romancemenu == 'Y' || repeat_romancemenu == 'y'); +} + +//*************************************************** +// RomanceDes Function. * +//*************************************************** + +void RomanceDes() +{ + +} + + +//*************************************************** +// Adventure Function. * +//*************************************************** + +void Adventure() +{ + cout << "\nHere's a list of 3 Adventure books you'd might like to read.\n" << endl; + //Sleep (1000); + + fstream inFile; + const int SIZE = 10; //array size + const int min_value = 0; //min random value + const int max_value = 5; //max random value + + string book[SIZE]; //declare arrays + string author[SIZE]; + string date[SIZE]; + + int count = 0; + int num = 1; + int RNG; //for random generator + + inFile.open ("AdventureBooksRegean.csv"); //open the file + + if (inFile.fail()) //if file did not open + { + cout << "Error! Could not open file." << endl; + } + if (inFile) + { + + while (getline (inFile, book[count], ',')) + { + getline (inFile, author[count], ','); + getline (inFile, date[count], '\n'); + count++; + } + + cout << "Title" << "\t\t" << setw(25) << "Author" << "\t" << setw(14) << "Date\n" << endl; + + for (int numloop = 0; numloop < 3; numloop++) + { + //get the system time + unsigned seed = time(0); + //seed the random num generator + srand(seed); + + RNG = (rand() % (max_value - min_value + 1)) + min_value; + cout << num << ". " << book[RNG] << setw(25) << right << author[RNG] << setw(10) << right << date[RNG] << endl << endl; + num++; + + + //Sleep (1000); + } + } + + + inFile.close(); //close the file + +} + +//*************************************************** +// Mystery Function. * +//*************************************************** + +void Mystery() +{ + cout << "\nHere's a list of 3 Mystery books you'd might like to read.\n" << endl; + //Sleep (1000); + + fstream inFile; + const int SIZE = 10; //array size + const int min_value = 0; //min random value + const int max_value = 5; //max random value + + string book[SIZE]; //declare arrays + string author[SIZE]; + string date[SIZE]; + + int count = 0; + int num = 1; + int RNG; //for random generator + + inFile.open ("MysteryBooksRegean.csv"); //open the file + + if (inFile.fail()) //if file did not open + { + cout << "Error! Could not open file." << endl; + } + if (inFile) + { + + while (getline (inFile, book[count], ',')) + { + getline (inFile, author[count], ','); + getline (inFile, date[count], '\n'); + count++; + } + + cout << "Title" << "\t\t" << setw(25) << "Author" << "\t" << setw(14) << "Date\n" << endl; + + for (int numloop = 0; numloop < 3; numloop++) + { + //get the system time + unsigned seed = time(0); + //seed the random num generator + srand(seed); + + RNG = (rand() % (max_value - min_value + 1)) + min_value; + cout << num << ". " << book[RNG] << setw(25) << right << author[RNG] << setw(10) << right << date[RNG] << endl << endl; + num++; + + + //Sleep (1000); + } + } + + + inFile.close(); //close the file +} + +//*********************************************************** +// The Music function displays a list of music books for * +// the user to choose from. The user will be asked if they * +// would like to keep the book they've selected. If yes, * +// The book information will be written to an external file.* +// Then, the user will be asked if they would like to make * +// another music selection. If yes, the program will display* +// the menu again. If no, the program will then exit this * +// function. * +//*********************************************************** +void Music() +{ + // Input Stream Objects + ifstream inputAuthors, // For Authors.txt + inputBooks, // For Books.txt + inputDates, // For Date.txt + inputDiscription; // For Discription.txt + + // Output Stream Objects + ofstream keptBooks; // Output Stream Object + + // Constants + const int SIZE = 10, + SELECT_BOOK_1 = 0, + SELECT_BOOK_2 = 1, + SELECT_BOOK_3 = 2, + SELECT_BOOK_4 = 3, + SELECT_BOOK_5 = 4, + SELECT_BOOK_6 = 5, + SELECT_BOOK_7 = 6, + SELECT_BOOK_8 = 7, + SELECT_BOOK_9 = 8, + SELECT_BOOK_10 = 9; + + // Variables + string author[SIZE], // Holds author names + book[SIZE], // Holds book names + date[SIZE], // Holds book dates + discription[SIZE]; // Holds book discriptions + + int selectBook; // Holds book selection + char keepBook, // Holds Y or N + anotherSelection; // Holds Y or N to return to music menu or not + + // Open input/ouput files + inputAuthors.open("MusicAuthorsJesus.txt"); + inputBooks.open("MusicBooksJesus.txt"); + inputDates.open("MusicDateJesus.txt"); + inputDiscription.open("Discriptions.txt"); + keptBooks.open("RememberedBooks.txt", ios::out | ios::app); + + + // Select Book from a list + do + { + + clearScreen(); + // Display list of music books + cout << "Here are the available music books: \n" << endl; + // Fill arrays with external file data and display contents + for (int count = 0; count < SIZE; count++) + { + getline(inputAuthors, author[count]); + getline(inputBooks, book[count]); + getline(inputDates, date[count]); + getline(inputDiscription, discription[count]); + cout << '\t' << (count + 1) << ". " + << book[count] << ", " << endl; + } + + // Close inputFiles + inputAuthors.close(); + inputBooks.close(); + inputDates.close(); + inputDiscription.close(); + + // Ask your to select a book + cout << "Select a book: "; + + // Receive into selectBook variable + // Error check for input validation + while (!(cin >> selectBook) || (selectBook < 1 || selectBook > 10)) // Error Check for valid input + { + // Describe error + cout << "ERROR: you must choose a number between 1 and 10."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + + switch (selectBook) + { + case (SELECT_BOOK_1 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_1] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_1] << endl << endl + << " " << discription[SELECT_BOOK_1] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_2 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_2] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_2] << endl << endl + << " " << discription[SELECT_BOOK_2] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_3 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_3] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_3] << endl << endl + << " " << discription[SELECT_BOOK_3] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_4 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_4] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_4] << endl << endl + << " " << discription[SELECT_BOOK_4] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + + default: + cout << "NO WORK." << endl; + } + + // If no. Say ok. + if (keepBook == 'N' || keepBook == 'n') + { + cout << "Ok.\n" << endl; + } + // If yes. Say awesome! + else if (keepBook == 'y' || keepBook == 'Y') + { + cout << "Awesome!\n" << endl; + // Write to output file books kept by user + keptBooks << book[selectBook - 1] << ", " + << author[selectBook -1] << ", " + << date [selectBook -1] << endl; + } + + // Clear screen + clearScreen(); + + // Ask if would like to make another music selection + cout << "Would you like to make another " + << "music genre selection? (Y/N)"; + cin >> anotherSelection; + anotherSelection = errorCheckYorN(anotherSelection); + + } while(anotherSelection == 'y' || anotherSelection == 'Y');// End Do While + + //Close output File + keptBooks.close(); +} diff --git a/Projects/BookFlix/Idea 1/Untitled b/Projects/BookFlix/Idea 1/Untitled new file mode 100644 index 0000000..e69de29 diff --git a/Projects/BookFlix/Idea 1/b75 b/Projects/BookFlix/Idea 1/b75 new file mode 100644 index 0000000..9b1bf4b --- /dev/null +++ b/Projects/BookFlix/Idea 1/b75 @@ -0,0 +1 @@ +Oh up, grand! diff --git a/Projects/BookFlix/Idea 1/fds b/Projects/BookFlix/Idea 1/fds new file mode 100644 index 0000000..8c0e791 --- /dev/null +++ b/Projects/BookFlix/Idea 1/fds @@ -0,0 +1 @@ +Ok now, ok. diff --git a/Projects/BookFlix/Idea 1/idea1.cpp b/Projects/BookFlix/Idea 1/idea1.cpp new file mode 100644 index 0000000..65d4806 --- /dev/null +++ b/Projects/BookFlix/Idea 1/idea1.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +using namespace std; + +int main() +{ + cout << "Enter you user name: "; + string username; + cin >> username; + + ofstream personsFile; + // Open personsFile + personsFile.open(username); + + // write to file + personsFile << "Ok now, ok. " << endl; + // close pevious user files + personsFile.close(); + + // New user + cout << "Enter another user name: "; + cin >> username; + personsFile.open(username); + + // write to file + personsFile << "Oh up, grand! " << endl; + // close pevious user files + personsFile.close(); + + cout << "Enter another username: "; + cin >> username; + + + ifstream personsBack; + personsBack.open(username); + vector letsSEE; + string ok; + if (personsBack) + { + personsBack.open(username); + cout << "I remember you!" << endl; + cout << "Your " << username << endl; + cout << "And here are your previous selections" << endl; + + for (int count = 0; count < letsSEE.size(); count++) + { + getline(personsBack, letsSEE[count]); + cout << letsSEE[count] << endl; + } + } + else + { + cout << "I dont remember you. :(" << endl; + } + + return 0; +} diff --git a/Projects/BookFlix/Idea 1/re b/Projects/BookFlix/Idea 1/re new file mode 100644 index 0000000..9b1bf4b --- /dev/null +++ b/Projects/BookFlix/Idea 1/re @@ -0,0 +1 @@ +Oh up, grand! diff --git a/Projects/BookFlix/Idea 1/rew b/Projects/BookFlix/Idea 1/rew new file mode 100644 index 0000000..9b1bf4b --- /dev/null +++ b/Projects/BookFlix/Idea 1/rew @@ -0,0 +1 @@ +Oh up, grand! diff --git a/Projects/BookFlix/Idea 1/rtg b/Projects/BookFlix/Idea 1/rtg new file mode 100644 index 0000000..9b1bf4b --- /dev/null +++ b/Projects/BookFlix/Idea 1/rtg @@ -0,0 +1 @@ +Oh up, grand! diff --git a/Projects/BookFlix/Idea 1/rw b/Projects/BookFlix/Idea 1/rw new file mode 100644 index 0000000..8c0e791 --- /dev/null +++ b/Projects/BookFlix/Idea 1/rw @@ -0,0 +1 @@ +Ok now, ok. diff --git a/Projects/BookFlix/Idea 1/sdf b/Projects/BookFlix/Idea 1/sdf new file mode 100644 index 0000000..9b1bf4b --- /dev/null +++ b/Projects/BookFlix/Idea 1/sdf @@ -0,0 +1 @@ +Oh up, grand! diff --git a/Projects/BookFlix/Idea 1/t40 b/Projects/BookFlix/Idea 1/t40 new file mode 100644 index 0000000..8c0e791 --- /dev/null +++ b/Projects/BookFlix/Idea 1/t40 @@ -0,0 +1 @@ +Ok now, ok. diff --git a/Projects/BookFlix/Idea 1/vf b/Projects/BookFlix/Idea 1/vf new file mode 100644 index 0000000..8c0e791 --- /dev/null +++ b/Projects/BookFlix/Idea 1/vf @@ -0,0 +1 @@ +Ok now, ok. diff --git a/Projects/BookFlix/Idea 1/y25 b/Projects/BookFlix/Idea 1/y25 new file mode 100644 index 0000000..8c0e791 --- /dev/null +++ b/Projects/BookFlix/Idea 1/y25 @@ -0,0 +1 @@ +Ok now, ok. diff --git a/Projects/BookFlix/IntMainPseudocode.txt b/Projects/BookFlix/IntMainPseudocode.txt new file mode 100644 index 0000000..ebbbdf5 --- /dev/null +++ b/Projects/BookFlix/IntMainPseudocode.txt @@ -0,0 +1,365 @@ +Do + Display Book Genre menu + 1. Music + 2. Romance + 3. Adventure + 4. Mystery + + Ask user to choose book + User input saved into menu_choice variable + Error check for valid user input + while menu_choice is not an int or between the range of 1 to 4 + Explain user Error + Clear input stream + Discard previous input + + user will then be sent to the function assigned to the genre that they pick + Switch + Case 1 Music + Pseudocode for music function + + Do + Open input and output files + Display list of available music books + + for loop + get book info from separate external files + display book info to screen + + Close input files + + Ask user to select a book + Error Check user input + While not an int or numbers between 1 and 4 + Explain Error + Clear input stream + Discard previous input + + Display Menu + Switch + Case 1 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 2 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 3 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 4 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + End Switch Statement + + If the user decides Not to keep the book + display ok. + else if the user decides to keep the book + display awesome! + write book information to an output file + + Ask if user would like to make another music selection + Receive answer into anotherSelection + Error check user input + While not a Y or an N + Explain User Error + Clear input stream + Discard previous input + + End of Do While statement + While anotherSelection is Y repeat the music menu selection + + Close output file keptBooks + End Music Function + + Case 2 Romance + Pseudocode for Romance function + + Do + Open input and output files + Display list of available Romance books + + for loop + get book info from separate external files + display book info to screen + + Close input files + + Ask user to select a book + Error Check user input + While not an int or numbers between 1 and 4 + Explain Error + Clear input stream + Discard previous input + + Display Menu + Switch + Case 1 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 2 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 3 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 4 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + End Switch Statement + + If the user decides Not to keep the book + display ok. + else if the user decides to keep the book + display awesome! + write book information to an output file + + Ask if user would like to make another Romance selection + Receive answer into anotherSelection + Error check user input + While not a Y or an N + Explain User Error + Clear input stream + Discard previous input + + End of Do While statement + While anotherSelection is Y repeat the Romance menu selection + + Close output file keptBooks + End Romance Function + + Case 3 Adventure + Pseudocode for Adventure function + + Do + Open input and output files + Display list of available Adventure books + + for loop + get book info from separate external files + display book info to screen + + Close input files + + Ask user to select a book + Error Check user input + While not an int or numbers between 1 and 4 + Explain Error + Clear input stream + Discard previous input + + Display Menu + Switch + Case 1 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 2 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 3 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 4 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + End Switch Statement + + If the user decides Not to keep the book + display ok. + else if the user decides to keep the book + display awesome! + write book information to an output file + + Ask if user would like to make another Adventure selection + Receive answer into anotherSelection + Error check user input + While not a Y or an N + Explain User Error + Clear input stream + Discard previous input + + End of Do While statement + While anotherSelection is Y repeat the Adventure menu selection + + Close output file keptBooks + End Adventure Function + + Case 4 Mystery + Pseudocode for Mystery function + + Do + Open input and output files + Display list of available Mystery books + + for loop + get book info from separate external files + display book info to screen + + Close input files + + Ask user to select a book + Error Check user input + While not an int or numbers between 1 and 4 + Explain Error + Clear input stream + Discard previous input + + Display Menu + Switch + Case 1 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 2 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 3 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 4 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + End Switch Statement + + If the user decides Not to keep the book + display ok. + else if the user decides to keep the book + display awesome! + write book information to an output file + + Ask if user would like to make another Mystery selection + Receive answer into anotherSelection + Error check user input + While not a Y or an N + Explain User Error + Clear input stream + Discard previous input + + End of Do While statement + While anotherSelection is Y repeat the Mystery menu selection + + Close output file keptBooks + End Mystery Function + + default + Display: not a valid choice + + Ask if the user would like to return to main menu + Receive user input into repeat_menu + Error check for valid user input + while repeat_menu is not Y or N + Explain the error + Clear input stream + Discard previous input + +End Do While Statement +(While anotherSelection is Y repeat the music menu selection) + +Display "Have a nice day!" +End Program diff --git a/Projects/BookFlix/KeptAdventureBooks.txt b/Projects/BookFlix/KeptAdventureBooks.txt new file mode 100644 index 0000000..e69de29 diff --git a/Projects/BookFlix/MusicAuthorsJesus.txt b/Projects/BookFlix/MusicAuthorsJesus.txt new file mode 100644 index 0000000..c6bb5b5 --- /dev/null +++ b/Projects/BookFlix/MusicAuthorsJesus.txt @@ -0,0 +1,4 @@ +Oliver Sacks +Alex Ross +Larry Fine +David Byrne diff --git a/Projects/BookFlix/MusicDateJesus.txt b/Projects/BookFlix/MusicDateJesus.txt new file mode 100644 index 0000000..090b8e9 --- /dev/null +++ b/Projects/BookFlix/MusicDateJesus.txt @@ -0,0 +1,4 @@ +September 23, 2008 +October 14, 2008 +November 1, 2000 +January 1, 2013 diff --git a/Projects/BookFlix/MusicDiscriptionsJesus.txt b/Projects/BookFlix/MusicDiscriptionsJesus.txt new file mode 100644 index 0000000..8f07acb --- /dev/null +++ b/Projects/BookFlix/MusicDiscriptionsJesus.txt @@ -0,0 +1,4 @@ +With the same trademark compassion and erudition he brought to The Man Who Mistook His Wife for a Hat, Oliver Sacks explores the place music occupies in the brain and how it affects the human condition. In Musicophilia, he shows us a variety of what he calls “musical misalignments.†Among them: a man struck by lightning who suddenly desires to become a pianist at the age of forty-two; an entire group of children with Williams syndrome, who are hypermusical from birth; people with “amusia,†to whom a symphony sounds like the clattering of pots and pans; and a man whose memory spans only seven seconds-for everything but music. Illuminating, inspiring, and utterly unforgettable, Musicophilia is Oliver Sacks' latest masterpiece. +In this sweeping and dramatic narrative, Alex Ross, music critic for The New Yorker, weaves together the histories of the twentieth century and its music, from Vienna before the First World War to Paris in the twenties; from Hitler's Germany and Stalin's Russia to downtown New York in the sixties and seventies up to the present. Taking readers into the labyrinth of modern style, Ross draws revelatory connections between the century's most influential composers and the wider culture. The Rest Is Noise is an astonishing history of the twentieth century as told through its music. +This bible of the piano marketplace is indispensable to buyers and owners of pianos, amateur and professional players alike. Hundreds of thousands of pianos are bought and sold each year, yet most people buy a piano with only the vaguest idea of what to look for as they make this major purchase. The Piano Book evaluates and compares every brand and style of piano sold in the United States. There is information on piano moving and storage, inspecting individual new and used pianos, the special market for Steinways, and sales gimmicks to watch out for. An annual supplement, sold separately, lists current prices for more than 2,500 new piano models. +How Music Works is David Byrne's buoyant celebration of a subject he has spent a lifetime thinking about. Equal parts historian and anthropologist, raconteur and social scientist, Byrne draws on his own work over the years with Talking Heads, Brian Eno, and his myriad collaborators - along with journeys to Wagnerian opera houses, African villages, and anywhere music exisits - to show that music - making is not just the act of a solitary composer in a studio, but rather a logical, populist, and beautiful result of cultural circumstance. A brainy, irresistible adventure, How Music Works is an impassioned argument about music's liberating, life - affirming power. diff --git a/Projects/BookFlix/MusicFunctionPseudocode.txt b/Projects/BookFlix/MusicFunctionPseudocode.txt new file mode 100644 index 0000000..25a0d24 --- /dev/null +++ b/Projects/BookFlix/MusicFunctionPseudocode.txt @@ -0,0 +1,81 @@ +Pseudocode for music function + +Do + Open input and output files + Display list of available music books + + for loop + get book info from separate external files + display book info to screen + + Close input files + + Ask user to select a book + Error Check user input + While not an int or numbers between 1 and 4 + Explain Error + Clear input stream + Discard previous input + + Display Menu + Switch + Case 1 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 2 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 3 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + + Case 4 + Display book information and description + Ask if the user would like to keep the book + Receive answer into keepBook + Error Check user input + While not a Y or N + Explain Error + Clear input stream + Discard previous input + End Switch Statement + + If the user decides Not to keep the book + display ok. + else if the user decides to keep the book + display awesome! + write book information to an output file + + Ask if user would like to make another music selection + Receive answer into anotherSelection + Error check user input + While not a Y or an N + Explain User Error + Clear input stream + Discard previous input + +End of Do While statement +While anotherSelection is Y repeat the music menu selection + +Close output file keptBooks +End Music Function diff --git a/Projects/BookFlix/MusicTitleJesus.txt b/Projects/BookFlix/MusicTitleJesus.txt new file mode 100644 index 0000000..849830c --- /dev/null +++ b/Projects/BookFlix/MusicTitleJesus.txt @@ -0,0 +1,4 @@ +Musicophilia +The Rest Is Noise +The Piano Book +How Music Works diff --git a/Projects/BookFlix/MysteryBooksAshley.txt b/Projects/BookFlix/MysteryBooksAshley.txt new file mode 100644 index 0000000..0c3f09c --- /dev/null +++ b/Projects/BookFlix/MysteryBooksAshley.txt @@ -0,0 +1,4 @@ +1. Jay Anson, The Amityville Horror 1977 +2. Stieg Larsson, The Girl with the Dragon Tattoo 2005 +3. Dan Brown, The Da Vinci Code 2003 +4. Yukito Ayatsuji, Another 2009 diff --git a/Projects/BookFlix/MysteryBooksRegean.csv b/Projects/BookFlix/MysteryBooksRegean.csv new file mode 100644 index 0000000..5d8299f --- /dev/null +++ b/Projects/BookFlix/MysteryBooksRegean.csv @@ -0,0 +1,7 @@ +Shutter Island,Dennis Lehane,2003 +The Godfather,Mario Puzo,1969 +The Lovely Bones,Alice Sebold,2002 +The Alienist,Caleb Carr,1994 +A Time to Kill,John Grisham,1989 +The Firm,Robin A.H. Waterfield,1991 +Presumed Innocent ,Scott Turow,1986 diff --git a/Projects/BookFlix/RememberedBooks.txt b/Projects/BookFlix/RememberedBooks.txt new file mode 100644 index 0000000..e7f923f --- /dev/null +++ b/Projects/BookFlix/RememberedBooks.txt @@ -0,0 +1 @@ +, , diff --git a/Projects/BookFlix/RomanceBooksAshley.txt b/Projects/BookFlix/RomanceBooksAshley.txt new file mode 100644 index 0000000..b0477c4 --- /dev/null +++ b/Projects/BookFlix/RomanceBooksAshley.txt @@ -0,0 +1,4 @@ +1. Colleen Houck, Tiger's Curse 2009 +2. Colleen Houck, Tiger's Quest 2009 +3. Anna Banks, Of Poseidon 2012 +4. Anna Banks, Of Triton 2013 diff --git a/Projects/BookFlix/Slide8.txt b/Projects/BookFlix/Slide8.txt new file mode 100644 index 0000000..866e96c --- /dev/null +++ b/Projects/BookFlix/Slide8.txt @@ -0,0 +1,4 @@ +Pros: +Cons: +How can it be improved: more books, more time +What would we do if we could start all over: diff --git a/Projects/BookFlix/Slide9.txt b/Projects/BookFlix/Slide9.txt new file mode 100644 index 0000000..2ce465a --- /dev/null +++ b/Projects/BookFlix/Slide9.txt @@ -0,0 +1,7 @@ +code blocks +colabedit +Amazon +goodreads +atom text editor +canvas +the book Gaddis diff --git a/Projects/BookFlix/Untitled b/Projects/BookFlix/Untitled new file mode 100644 index 0000000..e69de29 diff --git a/Projects/BookFlix/main.cpp b/Projects/BookFlix/main.cpp new file mode 100644 index 0000000..584b40d --- /dev/null +++ b/Projects/BookFlix/main.cpp @@ -0,0 +1,909 @@ +//****************************************************************** +// Project name: BookFlix +// Team name: +// Members: +// ASHLEY GUZMAN, +// REAGEN HAMMITT, +// JESUS HERNANDEZ + +// Course: COSC 1436.001 Programming Fundamentals 1 +// Group Project +// Due Date: December 4, 2016 +// Instructor: Korinne Caruso +// +// PURPOSE: This program displays a book menu selection for the user +// to choose from. The user then searches through the progam for a +// book or books that they would like to read. +// +// INPUT: The input in this program comes either from the user or from +// an input file. The user selects from a initial menu, a book genre +// menu, and must enter a Y or N for either keep a book or to continue +// to make another seletion. And then, the user must type +// a Y or an N to redisplay they menu or to end the program. +// +// OUTPUT: Output, in this program, is sent either to the screen +// or to an output file. The user is displayed an initial menu, +// a genre menu, asked to select a book, if they would like to keep +// a book, if they would like to select another book, and if they +// would like to see the inital menu. The output file receives +// data from the program, if the user decides to keep a book. The +// title, date, and author of the book is written to an output file. +// +//****************************************************************** +#include +#include +#include +#include +//#include +#include //for rand and srand +#include // for the time +using namespace std; + +// Directives for clearing the screen +#ifdef _WIN32 +char buffer[4] = "cls"; +const char* clearVar = buffer; +#ifdef _WIN64 +char buffer[4] = "cls"; +const char* clearVar = buffer; +#endif +#else +char buffer[6] = "clear"; +const char* clearVar = buffer; +#endif + +//Function Prototypes +void Music(); // Music Genre +void Romance(); // Romance Genre +void Adventure(); // Adventure Genre +void Mystery(); // Mystery Genre +void clearScreen(); // Mystery Genre +char errorCheckYorN(char); // Error Check for Y or N. +int errorCheckInts1_4(int); // Error Check range 1-4 and integers + +int main() +{ + // Variables + int menu_choice; // Holds Menu Choice + char repeat_menu; // To Re-display the menu_choice + + do + { + // Clear Screen + clearScreen(); + + cout << "\nChoose a genre to begin" << endl; + cout << "\n1. Music " << endl; + cout << "\n2. Romance" << endl; + cout << "\n3. Adventure" << endl; + cout << "\n4. Mystery\n" << endl; + + // Receive user input into menu_choice + // Error check for valid input + menu_choice = errorCheckInts1_4(menu_choice); + + switch (menu_choice) + { + + // 1. Music Genre + case 1: + Music(); + break; + + // 2. Romance Genre + case 2: + Romance(); + break; + + // 3. Adventure Genre + case 3: + Adventure(); + break; + + // 4. Mystery Genre + case 4: + Mystery(); + break; + + default: + break; + + } + + cout << "\nWould you like to return to the main menu? (Y/N)" << endl; + // Receive user input into repeat_menu + cin >> repeat_menu; + // Error check for valid input (Y/N) + repeat_menu = errorCheckYorN(repeat_menu); + + } while (repeat_menu == 'Y' || repeat_menu == 'y'); + + cout << "\nHave a nice day!" << endl; + return 0; +} + +//*************************************************** +// function errorCheckYN check for valid input. * +// In this case the user must enter a Y or and N. * +//*************************************************** + +char errorCheckYorN(char letter) +{ + while (!(letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N')) + { + // Explain error + cout << "ERROR: you must choose either Y or N." << endl + << "Y for Yes or\n" + << "N for No..."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + // Receive input again + cin >> letter; + } + return letter; +} + +//*********************************************************** +// Function errorCheckInt1-4 checks for valid input. * +// In this case the user must enter and integer or choose * +// a number between 1 and 4. * +//*********************************************************** + +int errorCheckInts1_4(int num) +{ + while (!(cin >> num) || (num < 1 || num > 4)) + { + // Explain the Error + cout << "ERROR: you must choose a number from 1 to 4."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + return num; +} + +//*************************************************** +// function to clear screen, using variable * +// created in PPD statement * +//*************************************************** + +void clearScreen() +{ + system(clearVar); +} + +//*********************************************************** +// The Music function displays a list of music books for * +// the user to choose from. The user will be asked if they * +// would like to keep the book they've selected. If yes, * +// The book information will be written to an external file.* +// Then, the user will be asked if they would like to make * +// another music selection. If yes, the program will display* +// the menu again. If no, the program will then exit this * +// function. * +//*********************************************************** + +void Music() +{ + // Input Stream Objects + ifstream inputAuthors, // For MusicAuthors.txt + inputBooks, // For MusicBooks.txt + inputDates; // For MusicDate.txt + + // Output Stream Objects + ofstream keptBooks; // Output Stream Object + + // Constants + const int SIZE = 4, + SELECT_BOOK_1 = 0, + SELECT_BOOK_2 = 1, + SELECT_BOOK_3 = 2, + SELECT_BOOK_4 = 3; + + // Variables + string author[SIZE], // Holds author names + book[SIZE], // Holds book names + date[SIZE]; // Holds book dates + + int selectBook; // Holds book selection + char keepBook, // Holds Y or N + anotherSelection; // Holds Y or N to return to music menu or not + + // Select Book from a list + do + { + // Open input/ouput files + inputAuthors.open("MusicAuthorsJesus.txt"); + inputBooks.open("MusicTitleJesus.txt"); + inputDates.open("MusicDateJesus.txt"); + keptBooks.open("RememberedBooks.txt", ios::out | ios::app); + + clearScreen(); + // Display list of music books + cout << "Here are the available music books: \n" << endl; + // Fill arrays with external file data and display contents + for (int count = 0; count < SIZE; count++) + { + getline(inputAuthors, author[count]); + getline(inputBooks, book[count]); + getline(inputDates, date[count]); + cout << '\t' << (count + 1) << ". " + << book[count] << ", " << endl; + } + + // Close inputFiles + inputAuthors.close(); + inputBooks.close(); + inputDates.close(); + + // Ask your to select a book + cout << "\nSelect a book: "; + + // Receive into selectBook variable + // Error check for input validation + selectBook = errorCheckInts1_4(selectBook); + + switch (selectBook) + { + case (SELECT_BOOK_1 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_1] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_1] << endl << endl; + + // Display Description + cout << "\tWith the same trademark compassion " << endl + << "and erudition he brought to The Man Who Mistook " << endl + << "His Wife for a Hat, Oliver Sacks explores the place music " << endl + << "occupies in the brain and how it affects the human condition. " << endl + << "In Musicophilia, he shows us a variety of what he calls “musical " << endl + << "misalignments.†Among them: a man struck by lightning who suddenly " << endl + << "desires to become a pianist at the age of forty-two; an entire group " << endl + << "of children with Williams syndrome, who are hypermusical from birth; " << endl + << "people with “amusia,†to whom a symphony sounds like the clattering of " << endl + << "pots and pans; and a man whose memory spans only seven seconds-for everything " << endl + << "but music. Illuminating, inspiring, and utterly unforgettable, Musicophilia " << endl + << "is Oliver Sacks' latest masterpiece." << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + // Receive user input into keepBook + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_2 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_2] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_2] << endl << endl; + + // Display description + cout << "\tIn this sweeping and dramatic narrative, " << endl + << "Alex Ross, music critic for The New Yorker, weaves " << endl + << "together the histories of the twentieth century and its music," << endl + << "from Vienna before the First World War to Paris in the twenties; " << endl + << "from Hitler's Germany and Stalin's Russia to downtown New York " << endl + << "in the sixties and seventies up to the present. Taking readers into the " << endl + << "labyrinth of modern style, Ross draws revelatory connections " << endl + << "between the century's most influential composers and the wider " << endl + << "culture. The Rest Is Noise is an astonishing history of the twentieth " << endl + << "century as told through its music." << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + // Receive user input into keepBook + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_3 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_3] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_3] << endl << endl; + + // Display Book 3 description + cout << "\tThis bible of the piano marketplace " << endl + << "is indispensable to buyers and owners of pianos, " << endl + << "amateur and professional players alike. Hundreds of thousands " << endl + << "of pianos are bought and sold each year, yet most people buy a" << endl + << "piano with only the vaguest idea of what to look for as they make this" << endl + << "major purchase. The Piano Book evaluates and compares every brand and " << endl + << "style of piano sold in the United States. There is information on piano " << endl + << "moving and storage, inspecting individual new and used pianos, the special" << endl + << "market for Steinways, and sales gimmicks to watch out for. An annual supplement, " << endl + << "sold separately, lists current prices for more than 2,500 new piano models." << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + // Receive user input into keepBook + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_4 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_4] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_4] << endl << endl; + + // Display Book 4 Description + cout << "How Music Works is David Byrne's buoyant " << endl + << "celebration of a subject he has spent a lifetime thinking " << endl + << "about. Equal parts historian and anthropologist, raconteur " << endl + << "and social scientist, Byrne draws on his own work over the " << endl + << "years with Talking Heads, Brian Eno, and his myriad collaborators - " << endl + << "along with journeys to Wagnerian opera houses, African villages, " << endl + << "and anywhere music exisits - to show that music - making is not " << endl + << "just the act of a solitary composer in a studio, but rather a logical, " << endl + << "populist, and beautiful result of cultural circumstance. " << endl + << "A brainy, irresistible adventure, How Music Works is an impassioned " << endl + << "argument about music's liberating, life - affirming power." << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + // Receive user input into keepBook + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + default: + cout << "NO WORK." << endl; + } + + // If no. Say ok. + if (keepBook == 'N' || keepBook == 'n') + { + cout << "Ok.\n" << endl; + } + // If yes. Say awesome! + else if (keepBook == 'y' || keepBook == 'Y') + { + cout << "Awesome!\n" << endl; + // Write to output file books kept by user + keptBooks << book[selectBook - 1] << ", " + << author[selectBook -1] << ", " + << date [selectBook -1] << endl; + } + + // Ask if would like to make another music selection + cout << "Would you like to make another " + << "music genre selection? (Y/N)"; + // Receive user input into anotherSelection + cin >> anotherSelection; + // Error check anotherSelection + anotherSelection = errorCheckYorN(anotherSelection); + + } while(anotherSelection == 'y' || anotherSelection == 'Y');// End Do While + + //Close output File + keptBooks.close(); +} + + +//*************************************************************** +// The romance function displays a menu with romance books to * +// choose from. The user is asked to choose a book. A description +// of the book is then displayed to the user. The user is asked * +// if they would like to keep the book. If yes, the book info is* +// then displayed to an output file. If they would not like to * +// keep the book, the user will be asked if they would like * +// to choose another book from the romance menu. * +//*************************************************************** + +void Romance() +{ + // Variables + const int SIZE = 4; // Holds array size + int position = 0; + char repeat_romancemenu; // Holds Y or N to return to Romance menu or not + int menu_romancechoice; // Holds romance book selection + + // Arrays + string romanceBookInfo[SIZE]; // Holds Romance Book info: author, title, date + + // Input / Output Files + ifstream file; + ofstream outputfile; + + do + { + + // Clear the screen + clearScreen(); + + // Open input file. + file.open("RomanceBooksAshley.txt"); + + // Display book selection + cout << "\n\n" << endl; + cout << " Author Title Date" << endl << endl; + + // This For loop get contents from the external file + // and Displays the to screen. + for (int count = 0; count < SIZE; count++) + { + // getting from external file + getline(file, romanceBookInfo[count]); + // displays contents to screen + cout << " " << romanceBookInfo[count] << endl; + } + + // Close input file. + file.close(); + + cout << endl << " Choose a book to read the description: "; + + // Receive into menu_romancechoice variable + // Error check for input validation + menu_romancechoice = errorCheckInts1_4(menu_romancechoice); + cout << endl; + + switch(menu_romancechoice) + { + case 1: + { + // Clear the screen + clearScreen(); + // Display Selction + cout << endl << " " << romanceBookInfo[0] << endl << endl; + // Display Description + cout << "\tWould you risk it all to " << endl + << " change your destiny?" << endl << endl; + + cout << "\tThe last thing Kelsey Hayes thought she'd be" << endl + << " doing this summer was trying to break a 300-year" << endl + << " old Indian curse. With a mysterious white tiger " << endl + << " named Ren. Halfway around the world. But that's" << endl + << " exactly what happened." << endl << endl; + + cout << "\tFace-to-face with dark forces, spellbinding "<< endl + << " magic, and mystical worlds where nothing is " << endl + << " what it seems, Kelsey risks everything to piece " << endl + << " together an ancient prophecy that could break the " << endl + << " curse forever. Packed the epic with magic, " << endl + << " action-adventure, and romance, Tiger's Curse " << endl + << " series will keep you breathless and yearning for " << endl + << " more." << endl; + } + // Ask is user would like to keep book + //cout << "\nWould you like to keep this book?"; + //cout << " (Y/N)"; + // Receive user input into keepBook + //cin >> keepBook; + // Error check keepBook + //keepBook = errorCheckYorN(keepBook); + break; + case 2: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[1] << endl << endl; + // Display Description + cout << "\tBack in Oregon, Kelsey tries to pick up the " << endl + << " pieces of her life and push aside her feelings " << endl + << " for Ren. Kelsey Hayes's eighteenth summer was" << endl + << " crazy. The kind of crazy nobody would ever" << endl + << " believe." << endl << endl; + + cout << "\tAside From battling immortal sea monkeys and " << endl + << " trekking the jungles of India, she fell in love " << endl + << " with Ren, a 300-year-old prince." << endl << endl; + + cout << "\tWhen danger suddenly forces Kelsey on another " << endl + << " Indian quest, with Ren's bad-boy brother, " << endl + << " Kishan, the unlikely duo begins to question their " << endl + << " true destiny. Ren's life hangs in the balance--" << endl + << " so does the truth within Kelsey's heart." << endl; + + } + break; + case 3: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[2] << endl << endl; + // Display Description + cout << "\tGalen, a Syrena prince, searches land for a " << endl + << " girl he's heard can communicate with fish. " << endl + << " It's while Emma is on vacation at the beach" << endl + << " that she meets Galen. Although their connection " << endl + << " is immediate and powerful, Galen's not fully convinced " << endl + << " that Emma's the one he's been looking for. That is," << endl + << " until a deadly encounter with a shark proves" << endl + << " that Emma and her Gift may be the only thing that " << endl + << " can save his kingdom. He needs her help no matter" << endl + << " what the risk." << endl; + + } + break; + case 4: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[3] << endl << endl; + // Display Description + cout << "\tEmma has just learned that her mother is a " << endl + << " long-lost Poseidon princess, and now struggles " << endl + << " with an identity crisis: As a Half-Breed, " << endl + << " she's a freak in the human world and an abomination" << endl + << " in the Syrena realm. Syrena law states all " << endl + << " Half-Breeds should be put to death." << endl << endl; + + cout << "\tAs if that's not bad enough, her mother's " << endl + << " reappearance in the Syrena world turns the " << endl + << " two kingdoms Poseidon and Triton against one " << endl + << " another. Which leaves Emma with a decision to make:" << endl + << " Should she comply with Galen's request to keep" << endl + << " herself safe and just hope for the best? Or " << endl + << " should she risk it all and reveal herself and" << endl + << " her Gift to save a people she's never known?" << endl; + + } + break; + default: + { + cout << " Invalid answer. Please try again." << endl; + } + break; + + } + cout << endl << " Would you like to return to the Romance menu? (Y/N)" << endl; + + // Receive into repeat_romancemenu variable + cin >> repeat_romancemenu; + // Error check for input validation + repeat_romancemenu = errorCheckYorN(repeat_romancemenu); + } + while (repeat_romancemenu == 'Y' || repeat_romancemenu == 'y'); +} + +/* + ************************************************************************* + * This is the Adventure function. This function call from the files the * + * title, author, and date. It will then allow the user to select a book * + * which will then display a description of the book. The user is then * + * asked if they would like to keep the book. If they chose 'yes', the * + * book information will be sent to another file. They the user will be * + * asked if they would like to select another book. If they select 'no', * + * the adventure function will end. * + ************************************************************************* + */ + +void Adventure() +{ + // Input Stream Objects + ifstream inputAuthors; // For Authors.txt + ifstream inputTitle; // For Books.txt + ifstream inputDates; // For Date.txt + ifstream inputDescription; // For Discription.txt + + // Output Stream Objects + ofstream keptBooks; // Output Stream Object + + // Constants + const int SIZE = 4, + SELECT_BOOK_1 = 0, + SELECT_BOOK_2 = 1, + SELECT_BOOK_3 = 2, + SELECT_BOOK_4 = 3; + + // Variables + string author[SIZE]; //author names + string title[SIZE]; // book titles + string date[SIZE]; // book dates + string description[SIZE]; // book descriptions + + int selectBook; // book selection + char keepBook, // Holds Y or N + anotherSelection; // Holds Y or N to return to adventure menu or not + + + + + // Select Book from a list + do + { + // Open input/ouput files + inputAuthors.open("Adventure_authors.txt"); + inputTitle.open("Adventure_titles.txt"); + inputDates.open("Adventure_date.txt"); + inputDescription.open("Adventure_descriptions.txt"); + keptBooks.open("KeptAdventureBooks.txt", ios::out | ios::app); + + clearScreen(); + // Display list of music books + cout << "Here are the available adventure books: \n" << endl; + // Fill arrays with external file data and display contents + for (int count = 0; count < SIZE; count++) + { + getline(inputAuthors, author[count]); + getline(inputTitle, title[count]); + getline(inputDates, date[count]); + getline(inputDescription, description[count], '$'); + cout << '\t' << (count + 1) << ". " + << title[count] << endl; + } + + // Close inputFiles + inputAuthors.close(); + inputTitle.close(); + inputDates.close(); + inputDescription.close(); + + // Ask your to select a book + cout << "\nSelect a book: "; + + // Receive into selectBook variable + // Error check for input validation + selectBook = errorCheckInts1_4(selectBook); + + switch (selectBook) + { + case (SELECT_BOOK_1 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl; + cout << "\t" << title[SELECT_BOOK_1] << ", by "; + cout << author[SELECT_BOOK_1] << endl << endl; + cout << " " << description[SELECT_BOOK_1] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + // Receive user input into keepBook + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_2 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl; + cout << "\t" << title[SELECT_BOOK_2] << ", by "; + cout << author[SELECT_BOOK_2] << endl << endl; + cout << " " << description[SELECT_BOOK_2] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + // Receive user input into keepBook + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_3 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl; + cout << "\t" << title[SELECT_BOOK_3] << ", by "; + cout << author[SELECT_BOOK_3] << endl << endl; + cout << " " << description[SELECT_BOOK_3] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + // Receive user input into keepBook + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + case (SELECT_BOOK_4 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl; + cout << "\t" << title[SELECT_BOOK_4] << ", by "; + cout << author[SELECT_BOOK_4] << endl << endl; + cout << " " << description[SELECT_BOOK_4] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + // Receive user input into keepBook + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + break; + + default: + cout << "No book selected." << endl; + } + + // If no. Say ok. + if (keepBook == 'N' || keepBook == 'n') + { + cout << "Ok.\n" << endl; + } + // If yes. Say awesome! + else if (keepBook == 'y' || keepBook == 'Y') + { + cout << "That's Great!\n" << endl; + // Write to output file books kept by user + keptBooks << title[selectBook - 1] << ", " + << author[selectBook - 1] << ", " + << date [selectBook - 1] << endl; + } + + // Clear screen + clearScreen(); + + // Ask if would like to make another music selection + cout << "Would you like to make another " + << "Adventure genre selection? (Y/N)"; + // Receive user input into anotherSelection + cin >> anotherSelection; + // Error chek anotherSelection for (Y/N) + anotherSelection = errorCheckYorN(anotherSelection); + + } while(anotherSelection == 'y' || anotherSelection == 'Y');// End Do While + + //Close output File + keptBooks.close(); +} + +//*************************************************************** +// The mystery function displays a menu with mystery books to * +// choose from. The user is asked to choose a book. A description +// of the book is then displayed to the user. The user is asked * +// if they would like to keep the book. If yes, the book info is* +// then displayed to an output file. If they would not like to * +// keep the book, the user will be asked if they would like * +// to choose another book from the mystery menu. * +//*************************************************************** + +void Mystery() +{ + // Variables + const int SIZE = 4; // Holds array size + int position = 0; + char repeat_mysterymenu; // Holds Y or N to return to Romance menu or not + int menu_mysterychoice; // Holds romance book selection + + // Arrays + string mysteryBookInfo[SIZE]; // Holds Romance Book into: author, title, date + + // Input Files + ifstream file; + + do + { + // Clear the screen + clearScreen(); + + // Open input file. + file.open("MysteryBooksAshley.txt"); + + // Display book selection + cout << "\n\n" << endl; + cout << " Author Title Date" << endl << endl; + + // This For Loop gets contents from the external file + // and Displays them to the screen. + for (int count = 0; count < SIZE; count++) + { + // getting from external file + getline(file, mysteryBookInfo[count]); + // displays contents to screen + cout << " " << mysteryBookInfo[count] << endl; + } + + // Close input file. + file.close(); + + cout << endl << " Choose a book to read the discription: "; + + // Receive user input into menu_mysterychoice + // and error check with errorCheckInts1_4 function + menu_mysterychoice = errorCheckInts1_4(menu_mysterychoice); + + cout << endl; + + switch(menu_mysterychoice) + { + case 1: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << mysteryBookInfo[0] << endl << endl; + // Diplay Description + cout << "\tThe classic and terrifying story " << endl + << "of one of the most famous supernatural events" << endl + << "--the infamous possessed house on Long Island from " << endl + << "which the Lutz family fled in 1975." << endl; + } + break; + + case 2: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << mysteryBookInfo[0] << endl << endl; + // Diplay Description + cout << "\tHarriet Vanger, a scion of one of Sweden's " << endl + << "wealthiest families disappeared over forty years ago. " << endl + << "All these years later, her aged uncle continues to seek " << endl + << "the truth. He hires Mikael Blomkvist, a crusading " << endl + << "journalist recently trapped by a libel conviction, to investigate." << endl + << "He is aided by the pierced and tattooed punk prodigy Lisbeth " << endl + << "Salander. Together they tap into a vein of unfathomable " << endl + << "iniquity and astonishing corruption." << endl; + } + break; + + case 3: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << mysteryBookInfo[0] << endl << endl; + // Diplay Description + cout << "\tAn ingenious code hidden in " << endl + << "the works of Leonardo da Vinci. A desperate race " << endl + << "through the cathedrals and castles of Europe." << endl + << "An astonishing truth concealed for centuries...unveiled " << endl + << "at last." << endl << endl; + + cout << "\tWhile in Paris, Harvard symbologist " << endl + << "Robert Langdon is awakened by a phone call in " << endl + << "the dead of the night. The elderly curator of the " << endl + << "Louvre has been murdered inside the museum, his body covered " << endl + << "in baffling symbols. As Langdon and gifted French cryptologist" << endl + << "Sophie Neveu sort through the bizarre riddles, they are stunned " << endl + << "to discover a trail of clues hidden in the works of Leonardo da" << endl + << "Vinci clues visible for all to see and yet ingeniously disguised " << endl + << "by the painter." << endl; + } + break; + + case 4: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << mysteryBookInfo[0] << endl << endl; + // Diplay Description + cout << "\tIn the spring of 1998, Kouichi " << endl + << "Sakakibara transfers to Yomiyama North Middle School." << endl + << "In class, he develops a sense of unease as he notices that " << endl + << "the people around him act like they're walking on eggshells," << endl + << "and students and teachers alike seem frightened." << endl + << "As a chain of horrific deaths begin to unfold around him," << endl + << "he comes to discover that he has been placed in the cursed Class 3" << endl + << "in which the student body head count is always one more than expected." << endl + << "Class 3 is haunted by a vengeful spirit responsible for gruesome deaths " << endl + << "in an effort to satisfy its spite. To stop the vicious cycle gripping " << endl + << "his new school, Kouichi decides to get to the bottom of the curse," << endl + << "but is he prepared for the horror that lies ahead...?" << endl; + } + break; + default: + { + cout << " Invalid answer. Please try again." << endl; + } + break; + } + cout << endl << "Would you like to return to the Mystery menu? (Y/N)" << endl; + + // Receive user input into repeat_mysterymenu + cin >> repeat_mysterymenu; + // Error check repeat_mysterymenu + repeat_mysterymenu = errorCheckYorN(repeat_mysterymenu); + + } while (repeat_mysterymenu == 'Y' || repeat_mysterymenu == 'y'); // End do while loop +} diff --git a/Projects/BookFlix/music.cpp b/Projects/BookFlix/music.cpp new file mode 100644 index 0000000..aa6c4fc --- /dev/null +++ b/Projects/BookFlix/music.cpp @@ -0,0 +1,299 @@ +//********************************************************* +// This function is sent from a switch statement +// The menu selection is sheet music case 1 +// Display Author, Book, and date. Save file as csv +// +// By: Jesus Hilario Hernandez +// Last Updated: November 8, 2016 +//********************************************************* +#include +#include +#include +#include +using namespace std; + +// Directives for clearing the screen +#ifdef _WIN32 +char buffer[4] = "cls"; +const char* clearVar = buffer; +#ifdef _WIN64 +char buffer[4] = "cls"; +const char* clearVar = buffer; +#endif +#else +char buffer[6] = "clear"; +const char* clearVar = buffer; +#endif + +//Function Prototypes +void clearScreen(); +char errorCheckYorN(char); + +// Main Function +int main() +{ + // Input Stream Objects + ifstream inputAuthors, // For Authors.txt + inputBooks, // For Books.txt + inputDates, // For Date.txt + inputDiscription; // For Discription.txt + + // Output Stream Objects + ofstream keptBooks; // Output Stream Object + + // Constants + const int SIZE = 10, + SELECT_BOOK_1 = 0, + SELECT_BOOK_2 = 1, + SELECT_BOOK_3 = 2, + SELECT_BOOK_4 = 3, + SELECT_BOOK_5 = 4, + SELECT_BOOK_6 = 5, + SELECT_BOOK_7 = 6, + SELECT_BOOK_8 = 7, + SELECT_BOOK_9 = 8, + SELECT_BOOK_10 = 9; + + // Variables + string author[SIZE], // Holds author names + book[SIZE], // Holds book names + date[SIZE], // Holds book dates + discription[SIZE]; // Holds book discriptions + + int selectBook; // Holds book selection + char keepBook, // Holds Y or N + anotherSelection; // Holds Y or N to return to music menu or not + + // Open input/ouput files + inputAuthors.open("Authors.txt"); + inputBooks.open("Books.txt"); + inputDates.open("Date.txt"); + inputDiscription.open("Discriptions.txt"); + keptBooks.open("RememberedBooks.txt", ios::out | ios::app); + + + // Select Book from a list + do + { + + clearScreen(); + // Display list of music books + cout << "Here are the available music books: \n" << endl; + // Fill arrays with external file data and display contents + for (int count = 0; count < SIZE; count++) + { + getline(inputAuthors, author[count]); + getline(inputBooks, book[count]); + getline(inputDates, date[count]); + getline(inputDiscription, discription[count]); + cout << '\t' << (count + 1) << ". " + << book[count] << ", " << endl; + } + + // Close inputFiles + inputAuthors.close(); + inputBooks.close(); + inputDates.close(); + inputDiscription.close(); + + // Ask your to select a book + cout << "Select a book: "; + + // Receive into selectBook variable + // Error check for input validation + while (!(cin >> selectBook) || (selectBook < 1 || selectBook > 10)) // Error Check for valid input + { + // Describe error + cout << "ERROR: you must choose a number from 1 to 10."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + } + + switch (selectBook) + { + case (SELECT_BOOK_1 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_1] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_1] << endl << endl + << " " << discription[SELECT_BOOK_1] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + + break; + case (SELECT_BOOK_2 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_2] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_2] << endl << endl + << " " << discription[SELECT_BOOK_2] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + // Error check keepBook + keepBook = errorCheckYorN(keepBook); + + break; + case (SELECT_BOOK_3 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_3] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_3] << endl << endl + << " " << discription[SELECT_BOOK_3] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + break; + case (SELECT_BOOK_4 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_4] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_4] << endl << endl + << " " << discription[SELECT_BOOK_4] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + break; + case (SELECT_BOOK_5 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_5] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_5] << endl << endl + << " " << discription[SELECT_BOOK_5] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + break; + case (SELECT_BOOK_6 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_6] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_6] << endl << endl + << " " << discription[SELECT_BOOK_6] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + break; + case (SELECT_BOOK_7 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_7] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_7] << endl << endl + << " " << discription[SELECT_BOOK_7] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + break; + case (SELECT_BOOK_8 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_8] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_8] << endl << endl + << " " << discription[SELECT_BOOK_8] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + break; + case (SELECT_BOOK_9 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_9] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_9] << endl << endl + << " " << discription[SELECT_BOOK_9] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + break; + case (SELECT_BOOK_10 + 1): + clearScreen(); + cout << "\nYou've selected:" << endl + << '\t' << book[SELECT_BOOK_10] << ", by " << endl + << "\t\t" << author[SELECT_BOOK_10] << endl << endl + << " " << discription[SELECT_BOOK_10] << endl; + + // Ask is user would like to keep book + cout << "\nWould you like to keep this book?"; + cout << " (Y/N)"; + cin >> keepBook; + break; + default: + cout << "NO WORK." << endl; + } + + // If no. Say ok. + if (keepBook == 'N' || keepBook == 'n') + { + cout << "Ok.\n" << endl; + } + // If yes. Say awesome! + else if (keepBook == 'y' || keepBook == 'Y') + { + cout << "Awesome!\n" << endl; + // Write to output file books kept by user + keptBooks << book[selectBook - 1] << ", " + << author[selectBook -1] << ", " + << date [selectBook -1] << endl; + } + + // Ask if would like to make another music selection + cout << "Would you like to make another music genre selection?"; + cin >> anotherSelection; + + } while(anotherSelection == 'y' || anotherSelection == 'Y');// End Do While + + //Close output File + keptBooks.close(); + return 0; +} +//*************************************************** +// function errorCheckYN check for valid input. * +// In this case the user must enter a Y or and N. * +//*************************************************** +char errorCheckYorN(char letter) +{ + while (!(letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N')) + { + // Explain error + cout << "ERROR: you must choose either Y or N."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(123, '\n'); + // Receive input again + cin >> letter; + } + return letter; +} + + +//*************************************************** +// function to clear screen, using variable * +// created in PPD statement * +//*************************************************** +void clearScreen() +{ + system(clearVar); +} diff --git a/Projects/BookFlix/newbookproject(Romance)final.cpp b/Projects/BookFlix/newbookproject(Romance)final.cpp new file mode 100644 index 0000000..9b804a6 --- /dev/null +++ b/Projects/BookFlix/newbookproject(Romance)final.cpp @@ -0,0 +1,333 @@ +#include +#include +#include +using namespace std; + +int menu_choice; //declare variables +char repeat_menu; + +void Mystery(); +void MysteryDes(); +void Romance(); +void RomanceDes(); //function prototypes +void Adventure(); + + +int main() +{ + + cout << "This program allows you to find a book you would like to read\n" << + cout << "based on which genre you would prefer to read." << endl; + + do + { + + cout << "\nChoose a genre from the list below\n" << endl; + + cout << "\n1. Sheet Music " << endl; + cout << "\n2. Romance" << endl; + cout << "\n3. Adventure" << endl; + cout << "\n4. Mystery" << endl << endl; + + cin >> menu_choice; + cout << endl; + + switch (menu_choice) + { + + case 1: + { + + } + break; + + case 2: + { + + cout << "You have chosen Romance as your genre." << endl << endl; + Romance(); + + } + break; + + case 3: + { + + } + break; + + case 4: + { + + cout << "You have chosen Romance as your genre." << endl << endl; + Mystery(); + + } + break; + + default: + { + cout << "Invalid answer. Please try again." << endl; + } + break; + + } + + cout << endl << "Would you like to return to the main menu? (Y/N)" << endl; + + cin >> repeat_menu; + + } while (repeat_menu == 'Y' || repeat_menu == 'y'); + + cout << "Have a nice day!" << endl; +return 0; +} + +void Romance() +{ + int SIZE = 1024; + int position = 0; + char * array = new char [SIZE]; + + ifstream file("RomanceBooks.txt"); + + + if(file.is_open()) + { + cout << "File opened" << endl << endl; + cout << "Author Title Date" << endl; + + while (!file.eof() && position < SIZE) + { + file.get(array[position]); + position++; + } + array [position-1] = '\0'; + + for (int i = 0; array[i] != '\0'; i++) + { + + cout << array[i]; + + } + + } + else + { + cout << "File could not be opened." << endl; + } +file.close(); + +RomanceDes(); +} + + + +void RomanceDes() +{ + char repeat_romancemenu; + int menu_romancechoice; + do + { + cout << endl << "Chose a book to read the description" << endl << endl; + + cin >> menu_romancechoice; + cout << endl; + + switch(menu_romancechoice) + { + case 1: + { + cout << "Would you risk it all to change your destiny?" << endl << endl; + + cout << "The last thing Kelsey Hayes thought she'd be doing" << endl + << "this summer was trying to" << endl + << "break a 300-year old Indian curse." << endl + << "With a mysterious white tiger named Ren." << endl + << "Halfway around the world." << endl + << "But that's exactly what happened." << endl << endl; + + cout << "Face-to-face with dark forces, spellbinding magic,"<< endl + << "and mystical worlds where nothing is what it seems," << endl + << "Kelsey risks everything to piece together an ancient prophecy" << endl + << "that could break the curse forever." << endl + << "Packed with magic, action-adventure, and romance," << endl + << "the epic Tiger's Curse series will keep you breathless" << endl + << "and yearning for more." << endl; + + } + break; + case 2: + { + cout << "Back in Oregon, Kelsey tries to pick up the pieces of her life" << endl + << "and push aside her feelings for Ren." << endl + << "Kelsey Hayes's eighteenth summer was crazy." << endl + << "The kind of crazy nobody would ever believe." << endl; + + cout << "Aside From battling immortal sea monkeys and" << endl + << "trekking the jungles of India, she fell in love with Ren," << endl + << "a 300-year-old prince." << endl; + + cout << "When danger suddenly forces Kelsey on another Indian quest," << endl + << "with Ren's bad-boy brother, Kishan," << endl + << "the unlikely duo begins to question their true destiny." << endl + << "Ren's life hangs in the balance--so does the truth within Kelsey's heart." << endl; + + } + break; + case 3: + { + cout << "Galen, a Syrena prince, searches land for a girl he's heard can communicate with fish." << endl + << "It's while Emma is on vacation at the beach that she meets Galen." << endl + << "Although their connection is immediate and powerful," << endl + << "Galen's not fully convinced that Emma's the one he's been looking for." << endl + << "That is, until a deadly encounter with a shark proves that Emma" << endl + << "and her Gift may be the only thing that can save his kingdom." << endl + << "He needs her help�no matter what the risk." << endl; + + } + break; + case 4: + { + cout << "Emma has just learned that her mother is a long-lost Poseidon princess," << endl + << "and now struggles with an identity crisis:" << endl + << "As a Half-Breed, she's a freak in the human world and an abomination" <> repeat_romancemenu; + } + while (repeat_romancemenu == 'Y' || repeat_romancemenu == 'y'); +} + +void Mystery() +{ + int SIZE = 1024; + int position = 0; + char * array = new char [SIZE]; + + ifstream file("MysteryBooksAshley.txt"); + + + if(file.is_open()) + { + cout << "File opened" << endl << endl; + cout << "Author Title Date" << endl; + + while (!file.eof() && position < SIZE) + { + file.get(array[position]); + position++; + } + array [position-1] = '\0'; + + for (int i = 0; array[i] != '\0'; i++) + { + + cout << array[i]; + + } + + } + else + { + cout << "File could not be opened." << endl; + } +file.close(); + +MysteryDes(); +} + +void MysteryDes() +{ + char repeat_mysterymenu; + int menu_mysterychoice; + do + { + cout << endl << "Chose a book to read the description" << endl << endl; + + cin >> menu_mysterychoice; + cout << endl; + + switch(menu_mysterychoice) + { + case 1: + { + + cout << "The classic and terrifying story of one of the most famous supernatural events" << endl + << "--the infamous possessed house on Long Island from which" << endl + << "the Lutz family fled in 1975." << endl; + + } + break; + case 2: + { + + cout << "Harriet Vanger, a scion of one of Sweden's wealthiest families disappeared" << endl + << "over forty years ago. All these years later, her aged uncle continues to seek the truth." << endl + << "He hires Mikael Blomkvist, a crusading journalist recently trapped by a libel conviction," << endl + << "to investigate. He is aided by the pierced and tattooed punk prodigy Lisbeth Salander." << endl + << "Together they tap into a vein of unfathomable iniquity and astonishing corruption." << endl; + + } + break; + case 3: + { + cout << "An ingenious code hidden in the works of Leonardo da Vinci." << endl + << "A desperate race through the cathedrals and castles of Europe." << endl + << "An astonishing truth concealed for centuries . . . unveiled at last." << endl; + + cout << "While in Paris, Harvard symbologist Robert Langdon is awakened" << endl + << "by a phone call in the dead of the night." << endl + << "The elderly curator of the Louvre has been murdered inside the museum," << endl + << "his body covered in baffling symbols." << endl + << "As Langdon and gifted French cryptologist Sophie Neveu sort through the bizarre riddles," << endl + << "they are stunned to discover a trail of clues hidden in the works of Leonardo da Vinci�clues" << endl + << "visible for all to see and yet ingeniously disguised by the painter." << endl; + + } + break; + case 4: + { + + cout << "In the spring of 1998, Kouichi Sakakibara transfers to Yomiyama North Middle School." << endl + << "In class, he develops a sense of unease as he notices that the people around him act like they're walking on eggshells," << endl + << "and students and teachers alike seem frightened." << endl + << "As a chain of horrific deaths begin to unfold around him," << endl + << "he comes to discover that he has been placed in the cursed Class 3" << endl + << "in which the student body head count is always one more than expected." << endl + << "Class 3 is haunted by a vengeful spirit responsible for gruesome deaths in an effort to satisfy its spite." << endl + << "To stop the vicious cycle gripping his new school, Kouichi decides to get to the bottom of the curse," << endl + << "but is he prepared for the horror that lies ahead...?" << endl; + } + break; + default: + { + cout << "Invalid answer. Please try again." << endl; + } + break; + + } + cout << endl << "Would you like to return to the Mystery menu? (Y/N)" << endl; + + cin >> repeat_mysterymenu; + } + while (repeat_mysterymenu == 'Y' || repeat_mysterymenu == 'y'); +} diff --git a/Projects/BookFlix/optionRomance.cpp b/Projects/BookFlix/optionRomance.cpp new file mode 100644 index 0000000..3be076c --- /dev/null +++ b/Projects/BookFlix/optionRomance.cpp @@ -0,0 +1,159 @@ +//*************************************************** +// Romance Function. * +//*************************************************** +void Romance() +{ + // Variables + const int SIZE = 4; // Holds array size + int position = 0; + char repeat_romancemenu; // Holds Y or N to return to Romance menu or not + int menu_romancechoice; // Holds romance book selection + + // Arrays + string romanceBookInfo[SIZE]; // Holds Romance Book info: author, title, date + + // Input Files + ifstream file; + + do + { + + // Clear the screen + clearScreen(); + + // Open input file. + file.open("RomanceBooksAshley.txt"); + + // Display book selection + cout << "\n\n" << endl; + cout << " Author Title Date" << endl << endl; + + // This For loop get contents from the external file + // and Displays the to screen. + for (int count = 0; count < SIZE; count++) + { + // getting from external file + getline(file, romanceBookInfo[count]); + // displays contents to screen + cout << " " << romanceBookInfo[count] << endl; + } + + // Close input file. + file.close(); + + cout << endl << " Choose a book to read the description: "; + + cin >> menu_romancechoice; + cout << endl; + + switch(menu_romancechoice) + { + case 1: + { + // Clear the screen + clearScreen(); + // Display Selction + cout << endl << " " << romanceBookInfo[0] << endl << endl; + // Display Description + cout << "\tWould you risk it all to " << endl + << " change your destiny?" << endl << endl; + + cout << "\tThe last thing Kelsey Hayes thought she'd be" << endl + << " doing this summer was trying to break a 300-year" << endl + << " old Indian curse. With a mysterious white tiger " << endl + << " named Ren. Halfway around the world. But that's" << endl + << " exactly what happened." << endl << endl; + + cout << "\tFace-to-face with dark forces, spellbinding "<< endl + << " magic, and mystical worlds where nothing is " << endl + << " what it seems, Kelsey risks everything to piece " << endl + << " together an ancient prophecy that could break the " << endl + << " curse forever. Packed the epic with magic, " << endl + << " action-adventure, and romance, Tiger's Curse " << endl + << " series will keep you breathless and yearning for " << endl + << " more." << endl; + } + break; + case 2: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[1] << endl << endl; + // Display Description + cout << "\tBack in Oregon, Kelsey tries to pick up the " << endl + << " pieces of her life and push aside her feelings " << endl + << " for Ren. Kelsey Hayes's eighteenth summer was" << endl + << " crazy. The kind of crazy nobody would ever" << endl + << " believe." << endl << endl; + + cout << "\tAside From battling immortal sea monkeys and " << endl + << " trekking the jungles of India, she fell in love " << endl + << " with Ren, a 300-year-old prince." << endl << endl; + + cout << "\tWhen danger suddenly forces Kelsey on another " << endl + << " Indian quest, with Ren's bad-boy brother, " << endl + << " Kishan, the unlikely duo begins to question their " << endl + << " true destiny. Ren's life hangs in the balance--" << endl + << " so does the truth within Kelsey's heart." << endl; + + } + break; + case 3: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[2] << endl << endl; + // Display Description + cout << "\tGalen, a Syrena prince, searches land for a " << endl + << " girl he's heard can communicate with fish. " << endl + << " It's while Emma is on vacation at the beach" << endl + << " that she meets Galen. Although their connection " << endl + << " is immediate and powerful, Galen's not fully convinced " << endl + << " that Emma's the one he's been looking for. That is," << endl + << " until a deadly encounter with a shark proves" << endl + << " that Emma and her Gift may be the only thing that " << endl + << " can save his kingdom. He needs her help no matter" << endl + << " what the risk." << endl; + + } + break; + case 4: + { + // Clear the screen + clearScreen(); + // Display Selection + cout << endl << " " << romanceBookInfo[3] << endl << endl; + // Display Description + cout << "\tEmma has just learned that her mother is a " << endl + << " long-lost Poseidon princess, and now struggles " << endl + << " with an identity crisis: As a Half-Breed, " << endl + << " she's a freak in the human world and an abomination" << endl + << " in the Syrena realm. Syrena law states all " << endl + << " Half-Breeds should be put to death." << endl << endl; + + cout << "\tAs if that's not bad enough, her mother's " << endl + << " reappearance in the Syrena world turns the " << endl + << " two kingdoms Poseidon and Triton against one " << endl + << " another. Which leaves Emma with a decision to make:" << endl + << " Should she comply with Galen's request to keep" << endl + << " herself safe and just hope for the best? Or " << endl + << " should she risk it all and reveal herself and" << endl + << " her Gift to save a people she's never known?" << endl; + + } + break; + default: + { + cout << " Invalid answer. Please try again." << endl; + } + break; + + } + cout << endl << " Would you like to return to the Romance menu? (Y/N)" << endl; + + cin >> repeat_romancemenu; + } + while (repeat_romancemenu == 'Y' || repeat_romancemenu == 'y'); +} diff --git a/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5(1).cpp b/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5(1).cpp new file mode 100644 index 0000000..8e04484 --- /dev/null +++ b/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5(1).cpp @@ -0,0 +1,210 @@ +//******************************************************************** +// +// JESUS HILARIO HERNANDEZ +// Course: COSC 1436.001 Programming Fundamentals 1 +// Lab # 5 Ch 3 Programming Challenge #10 +// Celsius to Fahrenheit extended +// Due Date: October 5, 2016 +// Instructor: Korinne Caruso +// +// Purpose: This program converts Celsius to Fahrenheit or +// Fahrenheit to Celsius. A menu is provided for the user to choose from. +// The three choices will be 1. Convert Celsius to Fahrenheit, +// 2. Fahrenheit to Celsius, and 3. Quite Program. Aside from these +// three menu options an end session option is also available. +// +// Input: Input will come from the user, through the (cin) object. +// The information the user provides will either be stored +// in a double, char, or an int. Further, input validation will +// occur each time the user provides information at the keyboard. +// If invalid input should occur, the user will be redirected through +// a while loop, to input only valid information. +// +// Output: All output will be sent using the (cout) object. +// A brief description of what +// the program does will be displayed when the program is run. +// A menu with three options will be provided for the user +// to choose from. At one point in the program, +// the user will be given the option to continue the +// program, end the program, or quit the program. +// +//******************************************************************** + +#include +#include +#include +using namespace std; + +int main() +{ + //Constants + const int CHOICE_1 = 1, + CHOICE_2 = 2, + CHOICE_3 = 3; + + //Variables: + double C, //Holds Celsius Temp + F; //Holds Fahrenheit Temp + int choice; //Holds Menu choice + char choice2; //Hold (Y/N) Ans. + + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + + //Do-While menu + do + { + cout //display menu + << "\n\t\tHere are your options: \n" + << "\t\t\t1. Convert Celsius to Fahrenheit" << endl + << "\t\t\t2. Convert Fahrenheit to Celsius" << endl + << "\t\t\t3. Quit Program\t\t\t\t"; + + // Error checking menu choice + while(!(cin >> choice) || choice < CHOICE_1 || choice > CHOICE_3) + { + //explain error + cout << "\n\t\tError: You must choose either 1, 2, or 3. "; + //clear input stream + cin.clear(); + //discard previous input + cin.ignore(1200, '\n'); + } + + //switch menu + switch (choice) + { + //Choice 1 + case CHOICE_1: + //Ask for Celsius temp. + cout << "\n\t\tWhat is the Celsius temperature " + << "\n\t\tthat you would wish to convert? "; + + //Error check choice 1 + while (!(cin >> C)) + { + //Explain Error + cout << "\n\t\tError: A number must be entered. " + << "\n\t\tWhat is the Celsius temperature? "; + //clear input stream + cin.clear(); + //discard previous input + cin.ignore(1200, '\n'); + } + + //calculate C to F + F = (9.0/5.0) * C + 32; + + //Display C to F conversion + cout << "\n\n\t\t\t"<< C << " Celsius = " + << setprecision(1) << fixed << F << " Fahrenheit" << endl; + cout << endl; + + //Asking if user would like to make another conversion + cout << "\n\t\tWould you like to make another conversion?" << endl; + cout << "\t\tY: if yes" << endl; + cout << "\t\tN: if no \n\t\t"; + cin >> choice2; + + //Validating user input, whether y or n is pressed. + while(!(choice2 == 'y' || choice2 == 'Y' || choice2 == 'n' || choice2 == 'N')) + { + cout << "Error: choose either Y or N." << endl; + //Clear input stream + cin.clear(); + //Discard previous input + cin.ignore(1200, '\n'); + + cin >> choice2; + } + //if pressed Y, acknowledge that they did + if (choice2 == 'y' || choice2 == 'Y') + { + cout << "\n\n\t\tOk. " ; + + } + //if pressed N, acknowledge that they did + else if (choice2 == 'n' || choice2 == 'N') + { + cout << "\n\nThank you! Have a nice day.\n\n" << endl; + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + + } + break; //End of case 1 + + //Choice 2 + case CHOICE_2: + cout << "\n\t\tWhat is the Fahrenheit temperature " << endl; + cout << "\t\tthat you would wish to convert? "; + + //Error check choice 2 + while(!(cin >> F)) + { + //Explain Error + cout << "\n\t\tError: A number must be entered. " + << "\n\t\tWhat is the Fahrenheit temperature? "; + //Clear input stream + cin.clear(); + //Discard previous input + cin.ignore(1200, '\n'); + } + + //Calculate F to C + C = (F - 32) * (5.0/9.0); + + //Display F to C conversion + cout << "\n\n\t\t\t" << F << " Fahrenheit = " + << setprecision(1)<< fixed << C << " Celsius" << endl; + cout << endl; + + //Asking if user would like to make another conversion + cout << "\n\t\tWould you like to make another conversion?" << endl; + cout << "\t\tY: if yes" << endl; + cout << "\t\tN: if no \n\t\t"; + cin >> choice2; + + //Validating user input, whether y or n is pressed. + while(!(choice2 == 'y' || choice2 == 'Y' || choice2 == 'n' || choice2 == 'N')) + { + cout << "Error: choose either Y or N." << endl; + //Clear input stream + cin.clear(); + //Discard previous input + cin.ignore(1200, '\n'); + + cin >> choice2; + } + + //if Y pressed, acknowledge that they did + if (choice2 == 'y') + { + cout << "\n\n\t\tOk. " ; + + } + //if N pressed, acknowledge that they did + else if (choice2 == 'n') + { + cout << "\n\nThank you! Have a nice day.\n\n" << endl; + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + + } + break; //end of case 2 + + case CHOICE_3 : + //Let user know that they have chosen to quit the program. + cout << "\n\t\tQuitting program..." << endl; + cout << "\n\t\tProgram Ended." << endl; + break; //end of case 3 + + } //end Switch menu + + + } while (choice == 1 || choice == 2);//End Do-While menu. + + //for padding before the 0 exit code. + cout << endl << endl; + + return 0; +} diff --git a/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5(1).pdf b/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5(1).pdf new file mode 100644 index 0000000..b38453d Binary files /dev/null and b/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5(1).pdf differ diff --git a/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5.cpp b/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5.cpp new file mode 100644 index 0000000..8e04484 --- /dev/null +++ b/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5.cpp @@ -0,0 +1,210 @@ +//******************************************************************** +// +// JESUS HILARIO HERNANDEZ +// Course: COSC 1436.001 Programming Fundamentals 1 +// Lab # 5 Ch 3 Programming Challenge #10 +// Celsius to Fahrenheit extended +// Due Date: October 5, 2016 +// Instructor: Korinne Caruso +// +// Purpose: This program converts Celsius to Fahrenheit or +// Fahrenheit to Celsius. A menu is provided for the user to choose from. +// The three choices will be 1. Convert Celsius to Fahrenheit, +// 2. Fahrenheit to Celsius, and 3. Quite Program. Aside from these +// three menu options an end session option is also available. +// +// Input: Input will come from the user, through the (cin) object. +// The information the user provides will either be stored +// in a double, char, or an int. Further, input validation will +// occur each time the user provides information at the keyboard. +// If invalid input should occur, the user will be redirected through +// a while loop, to input only valid information. +// +// Output: All output will be sent using the (cout) object. +// A brief description of what +// the program does will be displayed when the program is run. +// A menu with three options will be provided for the user +// to choose from. At one point in the program, +// the user will be given the option to continue the +// program, end the program, or quit the program. +// +//******************************************************************** + +#include +#include +#include +using namespace std; + +int main() +{ + //Constants + const int CHOICE_1 = 1, + CHOICE_2 = 2, + CHOICE_3 = 3; + + //Variables: + double C, //Holds Celsius Temp + F; //Holds Fahrenheit Temp + int choice; //Holds Menu choice + char choice2; //Hold (Y/N) Ans. + + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + + //Do-While menu + do + { + cout //display menu + << "\n\t\tHere are your options: \n" + << "\t\t\t1. Convert Celsius to Fahrenheit" << endl + << "\t\t\t2. Convert Fahrenheit to Celsius" << endl + << "\t\t\t3. Quit Program\t\t\t\t"; + + // Error checking menu choice + while(!(cin >> choice) || choice < CHOICE_1 || choice > CHOICE_3) + { + //explain error + cout << "\n\t\tError: You must choose either 1, 2, or 3. "; + //clear input stream + cin.clear(); + //discard previous input + cin.ignore(1200, '\n'); + } + + //switch menu + switch (choice) + { + //Choice 1 + case CHOICE_1: + //Ask for Celsius temp. + cout << "\n\t\tWhat is the Celsius temperature " + << "\n\t\tthat you would wish to convert? "; + + //Error check choice 1 + while (!(cin >> C)) + { + //Explain Error + cout << "\n\t\tError: A number must be entered. " + << "\n\t\tWhat is the Celsius temperature? "; + //clear input stream + cin.clear(); + //discard previous input + cin.ignore(1200, '\n'); + } + + //calculate C to F + F = (9.0/5.0) * C + 32; + + //Display C to F conversion + cout << "\n\n\t\t\t"<< C << " Celsius = " + << setprecision(1) << fixed << F << " Fahrenheit" << endl; + cout << endl; + + //Asking if user would like to make another conversion + cout << "\n\t\tWould you like to make another conversion?" << endl; + cout << "\t\tY: if yes" << endl; + cout << "\t\tN: if no \n\t\t"; + cin >> choice2; + + //Validating user input, whether y or n is pressed. + while(!(choice2 == 'y' || choice2 == 'Y' || choice2 == 'n' || choice2 == 'N')) + { + cout << "Error: choose either Y or N." << endl; + //Clear input stream + cin.clear(); + //Discard previous input + cin.ignore(1200, '\n'); + + cin >> choice2; + } + //if pressed Y, acknowledge that they did + if (choice2 == 'y' || choice2 == 'Y') + { + cout << "\n\n\t\tOk. " ; + + } + //if pressed N, acknowledge that they did + else if (choice2 == 'n' || choice2 == 'N') + { + cout << "\n\nThank you! Have a nice day.\n\n" << endl; + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + + } + break; //End of case 1 + + //Choice 2 + case CHOICE_2: + cout << "\n\t\tWhat is the Fahrenheit temperature " << endl; + cout << "\t\tthat you would wish to convert? "; + + //Error check choice 2 + while(!(cin >> F)) + { + //Explain Error + cout << "\n\t\tError: A number must be entered. " + << "\n\t\tWhat is the Fahrenheit temperature? "; + //Clear input stream + cin.clear(); + //Discard previous input + cin.ignore(1200, '\n'); + } + + //Calculate F to C + C = (F - 32) * (5.0/9.0); + + //Display F to C conversion + cout << "\n\n\t\t\t" << F << " Fahrenheit = " + << setprecision(1)<< fixed << C << " Celsius" << endl; + cout << endl; + + //Asking if user would like to make another conversion + cout << "\n\t\tWould you like to make another conversion?" << endl; + cout << "\t\tY: if yes" << endl; + cout << "\t\tN: if no \n\t\t"; + cin >> choice2; + + //Validating user input, whether y or n is pressed. + while(!(choice2 == 'y' || choice2 == 'Y' || choice2 == 'n' || choice2 == 'N')) + { + cout << "Error: choose either Y or N." << endl; + //Clear input stream + cin.clear(); + //Discard previous input + cin.ignore(1200, '\n'); + + cin >> choice2; + } + + //if Y pressed, acknowledge that they did + if (choice2 == 'y') + { + cout << "\n\n\t\tOk. " ; + + } + //if N pressed, acknowledge that they did + else if (choice2 == 'n') + { + cout << "\n\nThank you! Have a nice day.\n\n" << endl; + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + + } + break; //end of case 2 + + case CHOICE_3 : + //Let user know that they have chosen to quit the program. + cout << "\n\t\tQuitting program..." << endl; + cout << "\n\t\tProgram Ended." << endl; + break; //end of case 3 + + } //end Switch menu + + + } while (choice == 1 || choice == 2);//End Do-While menu. + + //for padding before the 0 exit code. + cout << endl << endl; + + return 0; +} diff --git a/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5.pdf b/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5.pdf new file mode 100644 index 0000000..b38453d Binary files /dev/null and b/Projects/Lab5-celsius-to-fahrenhiet-conversion/JHernandez001Lab5.pdf differ diff --git a/Projects/Lab6-temperature-functions/JhernandezLab6TemperatureFunctions.cpp b/Projects/Lab6-temperature-functions/JhernandezLab6TemperatureFunctions.cpp new file mode 100644 index 0000000..4acf83a --- /dev/null +++ b/Projects/Lab6-temperature-functions/JhernandezLab6TemperatureFunctions.cpp @@ -0,0 +1,363 @@ +//******************************************************************** +// +// JESUS HILARIO HERNANDEZ +// Course: COSC 1436.001 Programming Fundamentals 1 +// Lab # 6 Temperature Functions +// Celsius to Fahrenheit modified +// Due Date: October 16, 2016 +// Instructor: Korinne Caruso +// +// PURPOSE: This program converts Celsius to Fahrenheit or +// Fahrenheit to Celsius. Functions will be used within the program to +// display a menu, convert C to F, convert F to C, display results, +// send results to an external text file, and to handle error checking +// +// INPUT: Input will come from the user, through the (cin) object. +// The information the user provides will either be stored +// in a double, char, or an int. Further, input validation will +// occur each time the user provides information at the keyboard. +// If invalid input should occur, the user will be redirected through +// a while loop, to input only valid information. +// +// OUTPUT: Output in this program is either printed on the screen using +// cout, or written to an external file label results.txt. +// The user chooses to convert a temperature. After the temperature is +// converted, it is then displayed to the screen as well as written to +// an external file. The user is displayed with the menu if they +// choose to make another conversion and has the option to quit the +// program. Upon quitting the program or choosing not to make another +// conversion, the user is displayed an appropriate message in either +// case. +// +//******************************************************************** + +#include +#include +#include +using namespace std; + +// PPD to determine OS and set appropriate clear command +#ifdef _WIN32 || _WIN64f +char buffer[4] = "cls"; +const char* clearVar = buffer; +#else +char buffer[6] = "clear"; +const char* clearVar = buffer; +#endif + +// Global Constants +const int CHOICE_1 = 1, + CHOICE_2 = 2, + CHOICE_3 = 3; + +// Function Prototypes +void clearScreen(); // Clear Screen +void displayMenu(); // Display menu +double convertCtoF(double); // C to F Conversion +double convertFtoC(double); // F to C Conversion +void displayResults(int, double, double); // Display result use pass by reference +void sendResults(int, double, double); // Send results to .txt file +int errorChecking1(int); // Error Checking Menu Choice +double errorChecking2(double); // Error Checking For Numbers +char errorChecking3(char); // Error Checking (Y/N) + +int main() +{ + // Variables: + double C, // Holds Celsius Temp + F; // Holds Fahrenheit Temp + int choice; // Holds Menu choice + char choice2; // Hold (Y/N) Ans. + + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + + // Do-While menu + do + { + // Display Menu + displayMenu(); + + // Error Check Menu Choice + choice = errorChecking1(choice); + + // Switch menu + switch (choice) + { + // Choice 1 + case CHOICE_1: + + // Ask for Celsius temp. + cout << "\n\t\tWhat is the Celsius temperature " + << "\n\t\tthat you would wish to convert? "; + + // Error Check For Numbers + C = errorChecking2(C); + + // Calculate C to F + F = convertCtoF(C); + + // Display C to F conversion + displayResults(choice, C, F); + + // Send Results to results.txt + sendResults(choice, C, F); + + // Asking if user would like to make another conversion + cout << "\n\t\tWould you like to make another conversion?" << endl; + cout << "\t\tY: if yes" << endl; + cout << "\t\tN: if no \n\t\t"; + cin >> choice2; + + // Validating user input, whether y or n is pressed. + choice2 = errorChecking3(choice2); + + clearScreen(); + + // If pressed Y, acknowledge that they did + if (choice2 == 'y' || choice2 == 'Y') + { + cout << "\n\n\t\tOk. " ; + + } + // If pressed N, acknowledge that they did + else if (choice2 == 'n' || choice2 == 'N') + { + cout << "\n\nThank you! Have a nice day.\n\n" << endl; + clearScreen(); + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + + } + break; // End of case 1 + + // Choice 2 + case CHOICE_2: + + // Ask for Fahrenheit Temp + cout << "\n\t\tWhat is the Fahrenheit temperature " << endl; + cout << "\t\tthat you would wish to convert? "; + + // Error check choice 2 + F = errorChecking2(F); + + // Calculate F to C + C = convertFtoC(F); + + // Display F to C conversion + displayResults(choice, F, C); + + // Send Results to results.txt + sendResults(choice, F, C); + + // Asking if user would like to make another conversion + cout << "\n\t\tWould you like to make another conversion?" << endl; + cout << "\t\tY: if yes" << endl; + cout << "\t\tN: if no \n\t\t"; + cin >> choice2; + + // Validating user input, whether y or n is pressed. + choice2 = errorChecking3(choice2); + + clearScreen(); + + // If Y pressed, acknowledge that they did + if (choice2 == 'y') + { + cout << "\n\n\t\tOk. " ; + + } + // If N pressed, acknowledge that they did + else if (choice2 == 'n') + { + cout << "\n\nThank you! Have a nice day.\n\n" << endl; + clearScreen(); + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl; + } + break; // End of case 2 + + // Choice 3 + case CHOICE_3 : + + // Let user know they program quitting. + cout << "\n\t\tQuitting program..." << endl; + cout << "\n\t\tProgram Ended." << endl; + break; // End of case 3 + + } // End Switch menu + + } while (choice == 1 || choice == 2);// End Do-While menu. + + // For padding before the 0 exit code. + cout << endl << endl; + + return 0; +} + +//******************************************* +// Function clearScreen clears the screen * +// when the user chooses not to make another* +// conversion. * +//******************************************* +void clearScreen() +{ + system(clearVar); +} + +//******************************************* +// The displayMenu() function display the * +// menu to the user. * +//******************************************* + +void displayMenu() +{ + cout << "\n\t\tHere are your options: \n" + << "\t\t\t1. Convert Celsius to Fahrenheit" << endl + << "\t\t\t2. Convert Fahrenheit to Celsius" << endl + << "\t\t\t3. Quit Program "; +} + +//******************************************* +// The convertCtoF() function converts a * +// celsius temperature to fahrenheit. * +//******************************************* + +double convertCtoF(double num1) +{ + return (9.0/5.0) * num1 + 32; + +} +//******************************************* +// The convertFtoC() function converts a * +// fahrenheit temperature to a celsius * +// temperature. * +//******************************************* + +double convertFtoC(double num1) +{ + return (num1 - 32) * (5.0/9.0); +} + +//******************************************* +// The displayResults() function displays * +// the result of the conversion to the user * +// using the cout object. * +//******************************************* + +void displayResults(int num, double num1, double num2) +{ + if (CHOICE_1 == num) + { + cout << "\n\n\t\t" << setprecision(1) << fixed << num1 << " Celsius = " + << num2 << " Fahrenheit" << endl; + } + else if (CHOICE_2 == num) + { + cout << "\n\n\t\t" << setprecision(1) << fixed << num1 << " Fahrenheit = " + << num2 << " Celsius" << endl; + } +} + +//******************************************* +// The sendResults() function writes each * +// conversion result to an external text * +// file called results.txt * +// It's very similer to the displayResults()* +// function. The only difference is this * +// function uses the outputFile object * +// instead of the cout object. * +//******************************************* + +void sendResults(int num, double num1, double num2) +{ + // File Stream Object + ofstream outputFile; + // Open file results.txt + outputFile.open("results.txt", ios::out | ios::app); + + if (CHOICE_1 == num) + { + outputFile << setprecision(1) << fixed << num1 << " Celsius = " + << num2 << " Fahrenheit" << endl; + } + else if (CHOICE_2 == num) + { + outputFile << setprecision(1) << fixed << num1 << " Fahrenheit = " + << num2 << " Celsius" << endl; + } + + // Close file results.txt + outputFile.close(); +} + +//******************************************* +// The errorChecking1() function is used to * +// check for either a 1, a 2, or a 3 in user* +// input. If something other than any one * +// of these number is enter at the keyboard,* +// the while loop will prompt the error * +// and give the user a chance to re-enter * +// valid input. * +//******************************************* + +int errorChecking1(int num) +{ + while(!(cin >> num) || num < CHOICE_1 || num > CHOICE_3) + { + // Explain error + cout << "\n\t\tError: You must choose either 1, 2, or 3. "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + return num; +} + +//*********************************************** +// Definition of function errorChecking2(). * +// This function is used to validate whether * +// the user has entered a number. If no * +// number is entered at the keyboard, the * +// while loop will prompt the error and ask * +// for valid input. * +//*********************************************** + +double errorChecking2(double num) +{ + while (!(cin >> num)) + { + // Explain Error + cout << "\n\t\tError: A number must be entered. " + << "\n\t\tWhat is the Celsius temperature? "; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + } + return num; +} + +//*********************************************** +// The errorChecking3() function is used to * +// check if the user has entered either a Y or * +// an N. Failure on the users part to enter * +// either will result in a prompt that will * +// receive valid input. * +//*********************************************** + +char errorChecking3(char letter) +{ + while(!(letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N')) + { + cout << "\n\t\tError: choose either Y or N."; + // Clear input stream + cin.clear(); + // Discard previous input + cin.ignore(1200, '\n'); + // Re-enter input + cin >> letter; + } + return letter; +} diff --git a/Projects/Lab6-temperature-functions/JhernandezLab6TemperatureFunctions.pdf b/Projects/Lab6-temperature-functions/JhernandezLab6TemperatureFunctions.pdf new file mode 100644 index 0000000..79ca257 Binary files /dev/null and b/Projects/Lab6-temperature-functions/JhernandezLab6TemperatureFunctions.pdf differ diff --git a/Projects/Lab6-temperature-functions/results.txt b/Projects/Lab6-temperature-functions/results.txt new file mode 100644 index 0000000..af89540 --- /dev/null +++ b/Projects/Lab6-temperature-functions/results.txt @@ -0,0 +1,14 @@ +33.0 Celsius = 91.4 Fahrenheit +91.4 Fahrenheit = 33.0 Celsius +91.4 Fahrenheit = 33.0 Celsius +33.0 Fahrenheit = 0.6 Celsius +54.0 Fahrenheit = 12.2 Celsius +5435.0 Celsius = 9815.0 Fahrenheit +33.0 Fahrenheit = 0.6 Celsius +91.0 Fahrenheit = 32.8 Celsius +67.0 Fahrenheit = 19.4 Celsius +54.0 Fahrenheit = 12.2 Celsius +65.0 Fahrenheit = 18.3 Celsius +234.0 Fahrenheit = 112.2 Celsius +234.0 Fahrenheit = 112.2 Celsius +432.0 Fahrenheit = 222.2 Celsius diff --git a/Projects/Lab7-math-tutor/1.practice-addition.cpp b/Projects/Lab7-math-tutor/1.practice-addition.cpp new file mode 100644 index 0000000..436ef85 --- /dev/null +++ b/Projects/Lab7-math-tutor/1.practice-addition.cpp @@ -0,0 +1,74 @@ +//************************************** +// 1. Practice Addition +// +// By: Jesus HIlario Hernandez +// Last updated: Octobe 31, 2016 +//************************************** +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +int main() +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + const int MIN_VALUE = 0; // Minimum value + const int MAX_VALUE = 9; // Maximum value + + // Variables + int num1; // Holds a value + int num2; // Holds a value + int sum, answer; + char enterKey; + + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + sum = num1 + num2; + + cout << num1 << " + " << num2 << endl; + cout << "\nPress [enter] to see the answer..."; + cin.get(enterKey); + cout << "\nThe answer is " << sum << endl << endl; + do + { + cout << "Problem: " << endl; + cout << "\tIf I have " << num1 ; + + if (num1 == 1) + { + cout << " pencil"; + } + else + { + cout << " pencils"; + } + cout << " and " << num2; + + if (num2 == 1) + { + cout << " pen"; + } + else + { + cout << " pens"; + } + cout << endl + << "\thow many pens and pencils do I have altogether? "; + cin >> answer; + if (answer == sum) + { + cout << "\nGreat work! " << endl; + } + else + { + cout << "\nSorry, try again.\n" << endl; + + } + + } while (answer != sum); +} diff --git a/Projects/Lab7-math-tutor/2.practice-subtraction.cpp b/Projects/Lab7-math-tutor/2.practice-subtraction.cpp new file mode 100644 index 0000000..bbead6c --- /dev/null +++ b/Projects/Lab7-math-tutor/2.practice-subtraction.cpp @@ -0,0 +1,74 @@ +//************************************** +// 2. Practice Subtraction +// +// By: Jesus HIlario Hernandez +// Last updated: Octobe 31, 2016 +//************************************** +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +int main() +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + const int MIN_VALUE = 0; // Minimum value + const int MAX_VALUE = 9; // Maximum value + + // Variables + int num1; // Holds a value + int num2; // Holds a value + int sum, answer; + char enterKey; + + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + sum = num1 + num2; + + cout << num1 << " + " << num2 << endl; + cout << "\nPress [enter] to see the answer..."; + cin.get(enterKey); + cout << "\nThe answer is " << sum << endl << endl; + do + { + cout << "Problem: " << endl; + cout << "\tIf I have " << num1 ; + + if (num1 == 1) + { + cout << " pencil"; + } + else + { + cout << " pencils"; + } + cout << " and " << num2; + + if (num2 == 1) + { + cout << " pen"; + } + else + { + cout << " pens"; + } + cout << endl + << "\thow many pens and pencils do I have altogether? "; + cin >> answer; + if (answer == sum) + { + cout << "\nGreat work! " << endl; + } + else + { + cout << "\nSorry, try again.\n" << endl; + + } + + } while (answer != sum); +} diff --git a/Projects/Lab7-math-tutor/3.practice-multiplication.cpp b/Projects/Lab7-math-tutor/3.practice-multiplication.cpp new file mode 100644 index 0000000..a95c0ef --- /dev/null +++ b/Projects/Lab7-math-tutor/3.practice-multiplication.cpp @@ -0,0 +1,48 @@ +//************************************** +// 3. Practice Multiplication +// +// By: Jesus HIlario Hernandez +// Last updated: Octobe 31, 2016 +//************************************** +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +int main() +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + const int MIN_VALUE = 0; // Minimum value + const int MAX_VALUE = 9; // Maximum value + + // Variables + int num1; // Holds a value + int num2; // Holds a value + int sum, answer; + char enterKey; + + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + sum = num1 * num2; + + cout << num1 << " x " << num2 << endl; + cout << "\nPress [enter] to see the answer..."; + cin.get(enterKey); + cout << "\nThe answer is " << sum << endl << endl; + do + { + cout << "Problem: " << endl; + cout << "\tIf I have " << num1 << " sets of " + << num2 << " swans, how many do I have " + << "altogether? "; + cin >> answer; + } while (answer != sum); + + cout << endl; + return 0; +} diff --git a/Projects/Lab7-math-tutor/4.practice-division.cpp b/Projects/Lab7-math-tutor/4.practice-division.cpp new file mode 100644 index 0000000..4340ccf --- /dev/null +++ b/Projects/Lab7-math-tutor/4.practice-division.cpp @@ -0,0 +1,51 @@ +//************************************** +// 3. Practice Division +// +// By: Jesus HIlario Hernandez +// Last updated: Octobe 31, 2016 +//************************************** +#include +#include // For rand and srand +#include // For the time function +#include // For fomatting +using namespace std; + +int main() +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + const int MIN_VALUE = 0; // Minimum value + const int MAX_VALUE = 9; // Maximum value + + // Variables + int num1; // Holds a value + int num2; // Holds a value + int sum, answer; + char enterKey; + + cout << fixed << showpoint << setprecision(2); + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + sum = num1 / num2; + + cout << num1 << " / " << num2 << endl; + cout << "\nPress [enter] to see the answer..."; + cin.get(enterKey); + cout << "\nThe answer is " << sum << " with a remainder of " << (num1 % num2) + << endl << endl; + do + { + cout << "Problem: " << endl; + cout << "\tIf I have " << num1 << " sets of " + << num2 << " swans, how many do I have " + << "altogether? "; + cin >> answer; + } while (answer != sum); + + cout << endl; + return 0; +} diff --git a/Projects/Lab7-math-tutor/5.calculate-area-of-rectangle.cpp b/Projects/Lab7-math-tutor/5.calculate-area-of-rectangle.cpp new file mode 100644 index 0000000..b1f9fb4 --- /dev/null +++ b/Projects/Lab7-math-tutor/5.calculate-area-of-rectangle.cpp @@ -0,0 +1,36 @@ +//************************************** +// 5. Calculate Area of Rectangle +// +// By: Jesus HIlario Hernandez +// Last updated: Octobe 31, 2016 +//************************************** +#include +using namespace std; + +int main() +{ + // Variables: Hold length, width, and area. + double area, length, width; + + // Explain program, then get length + cout << "This program calculates the area " + << "of a rectangle." << endl; + cout << "Let's start off with the length.\n" + << "What is the length of the rectangle? "; + cin >> length; + + // Get width + cout << "Ok, what is the width? "; + cin >> width; + + // Calculate and display + area = length * width; + cout << "The area of a rectangle " + << "whose length is " << length + << "\nand whose width is " << width + << "\nis " << area; + + // Space before return 0 + cout << '\n' << endl; + return 0; +} diff --git a/Projects/Lab7-math-tutor/6.calculate-area-of-circle.cpp b/Projects/Lab7-math-tutor/6.calculate-area-of-circle.cpp new file mode 100644 index 0000000..c7524a2 --- /dev/null +++ b/Projects/Lab7-math-tutor/6.calculate-area-of-circle.cpp @@ -0,0 +1,36 @@ +//************************************** +// 6. Calculate Area of a Circle +// +// By: Jesus HIlario Hernandez +// Last updated: November 1, 2016 +//************************************** +#include +using namespace std; + +int main() +{ + // Variables: Hold area, radius, PI. + const double PI = 3.14; + double area, radius, radSquare; + + // Explain program, then get radius + cout << "This program calculates the area " + << "of a circle.\n" << endl; + cout << "Let's start off with the radius.\n" + << "What is the radius of the circle? "; + cin >> radius; + cout << "\n\t\tAwesome!" << endl << endl; + + // Calculate and display + radSquare = (radius * radius); + area = PI * (radius * radius); + cout << "When finding the area of a circle, \n" + << "the radius must be squared and then\n" + << "multiplied by PI(3.14). " << endl; + cout << "\nSo, " << radius << " x " << radius << " = " << radSquare << endl + << "and " << radSquare << " x " << PI << " = " << area << "." << endl + << "The area of the circle is "<< area << endl; + // Space before return 0 + cout << '\n' << endl; + return 0; +} diff --git a/Projects/Lab7-math-tutor/7.calculate-area-of-triangle.cpp b/Projects/Lab7-math-tutor/7.calculate-area-of-triangle.cpp new file mode 100644 index 0000000..04aada1 --- /dev/null +++ b/Projects/Lab7-math-tutor/7.calculate-area-of-triangle.cpp @@ -0,0 +1,41 @@ +//************************************** +// 7. Calculate Area of a Triangle +// +// By: Jesus HIlario Hernandez +// Last updated: November 1, 2016 +//************************************** +#include +using namespace std; + +int main() +{ + // Variables: Hold length, width, and area. + double area, height, base; + + // Explain program, then get length + cout << "This program calculates the area " + << "of a triangle." << endl; + cout << "Let's start off with the height.\n" + << "What is the height of the triangle? "; + cin >> height; + + // Get width + cout << "Ok, what is the length of the base of our triangle? "; + cin >> base; + + // Calculate and display + area = (height * base) / 2; + cout << "The area of a triangle " + << "whose height is " << height + << "\nand whose base is " << base + << "\nis " << area << endl; + cout << "To figure this out, " << endl + << "we must multiply the base(" << + base << ") by the height(" << + height << ") " << endl + << "and divide their sum by 2. " << endl; + + // Space before return 0 + cout << '\n' << endl; + return 0; +} diff --git a/Projects/Lab7-math-tutor/MathTutorRecord.txt b/Projects/Lab7-math-tutor/MathTutorRecord.txt new file mode 100644 index 0000000..2d66fb6 --- /dev/null +++ b/Projects/Lab7-math-tutor/MathTutorRecord.txt @@ -0,0 +1 @@ +The area of the rectangle is 25 diff --git a/Projects/Lab7-math-tutor/math-tutor-main.cpp b/Projects/Lab7-math-tutor/math-tutor-main.cpp new file mode 100644 index 0000000..25727e7 --- /dev/null +++ b/Projects/Lab7-math-tutor/math-tutor-main.cpp @@ -0,0 +1,876 @@ +//****************************************************************** +// +// JESUS HILARIO HERNANDEZ +// Course: COSC 1436.001 Programming Fundamentals 1 +// Lab # 7 Math Tutor +// Due Date: November 6, 2016 +// Instructor: Korinne Caruso +// +// PURPOSE: This program functions as a math tutor to students in +// the elementary - middle school range. This program will have +// a menu selection to choose from that will include: addition +// practice, subtraction practice, multiplication practice, division +// practice, calculating the area of a triangle, the area of a circle, +// and the area of a rectangle. +// +// INPUT: Input for calculating the area selections will require the +// user to input information through the cin object. Input will then +// be checked to be sure that valid data is input at the keyboard. +// +// OUTPUT: For the practice selctions, random numbers will be +// displayed, answered, and sent to an exeternal file. For the +// calculation selections the area of an object will be calculated, +// displayed, and then sent to an external file. +// +//****************************************************************** +#include +#include +#include +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +// Directives for clearing the screen +#ifdef _WIN32 +char buffer[4] = "cls"; +const char* clearVar = buffer; + #ifdef _WIN64 + char buffer[4] = "cls"; + const char* clearVar = buffer; + #endif +#else +char buffer[6] = "clear"; +const char* clearVar = buffer; +#endif + +// Global Constants for menu selection. +const int CHOICE_1 = 1, + CHOICE_2 = 2, + CHOICE_3 = 3, + CHOICE_4 = 4, + CHOICE_5 = 5, + CHOICE_6 = 6, + CHOICE_7 = 7, + CHOICE_8 = 8; + +// Function Prototypes +bool inputVal(bool); // Error Checking +int menu(int); // Menu +bool additionPractice(); // Addition Practice +bool subtractionPractice(); // Subtraction Practice +bool multiplicationPractice(); // Multiplication practice +bool divisionPractice(); // Division practice +bool calculateAreaOfRectangle(); // Calculate area of rectangle +bool calculateAreaOfCircle(); // Calculate area of circle +bool calculateAreaOfTriangle(); // Calculate area of triangle +void clearScreen(); // Clear screen +int inputVal(int); // Error Checking +double inputVal(double); // Error Checking + +int main() +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + // Constant + const string SHUTDOWN = "CarusoShutDown"; // To shutdown program + + // Variables + int menuSelection; // Holds Menu Selection + string teacherPass; // Holds Shudown Password + + // Do While used to iterate menu + do + { + clearScreen(); + // Display Menu, receive user input + menuSelection = menu(menuSelection); + cout << endl << endl; + + // Switch used as menu + switch (menuSelection) + { + case CHOICE_1: + additionPractice(); // Calling additionPractice function + break; + case CHOICE_2: + subtractionPractice(); // Calling subtractionPractice function + break; + case CHOICE_3: + multiplicationPractice(); // Calling multiplicationPractice function + break; + case CHOICE_4: + divisionPractice(); // Calling divisionPractice function + break; + case CHOICE_5: + calculateAreaOfRectangle(); // Calling calculateAreaOfRectangle function + break; + case CHOICE_6: + calculateAreaOfCircle(); // Calling acalculateAreaOfCircle function + break; + case CHOICE_7: + calculateAreaOfTriangle(); // Calling calculateAreaOfTriangle function + break; + case CHOICE_8: + + // Clear Screen + clearScreen(); + + // Ask for password, recieve password + cout << "Password please: "; + cin >> teacherPass; + + // If statement checks for valid password. + if (teacherPass != SHUTDOWN) + { + int tries = 4; + for (int num = 0; num < 4; num++) + { + cout << "I'm sorry wrong password." << endl + << "You have " << tries << " more tries: "; + cin >> teacherPass; + tries--; + if (teacherPass == SHUTDOWN) + { + break; + } + } + } + } + } while (!(teacherPass == SHUTDOWN)); + + // End program valediction + cout << "Ending Program...\n"; + cout << "Program ended." << endl << endl; + + return 0; +} + +//******************************************************* +// The inputVal Function check for valid input. In * +// this case a boolean must be enter as valid input. * +// The user will be promted to enter valid data if * +// they've entered invalid data. * +//******************************************************* + +bool inputVal(bool num) +{ + while (!(cin >> num)) + { + cout << "\nI'm sorry either a 1 or a 0 \n" + << "must be entered to proceed: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} + +//******************************************************************* +// Function menu displays the main menu, receives user selection, * +// and checks for valid input. * +//******************************************************************* + +int menu(int num) +{ + cout << "\t-----------------------------------------------------\n" + << "\t\t\tWelcome to Math Tutor!\n" + << "\t-----------------------------------------------------\n\n" + << "\tChoose from the menu to continue: \n\n" + << "\t\t1. Practice Addition \n" + << "\t\t2. Practice Subtraction \n" + << "\t\t3. Practice Multiplication\n" + << "\t\t4. Practice Division\n" + << "\t\t5. Calculate the Area of a Rectangle\n" + << "\t\t6. Calculate the Area of a Circle\n" + << "\t\t7. Calculate the Area of a Triangle\n" + << "\t\t8. Program Shutdown "; + + while (!(cin >> num && num <= CHOICE_8 && num >= CHOICE_1)) + { + cout << "I'm sorry, choose a number from the menu: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} + +//*************************************************************** +// The additionPractice function shows a random addition * +// problem, asks for user input, and returns a boolean value. * +//*************************************************************** + +bool additionPractice() +{ + // File object + ofstream outputFile; + // Open outputFile + outputFile.open("MathTutorRecord.txt"); + + //Varable + bool anotherProb; + + // Another problem? Do While + do + { + // Constants + const int MIN_VALUE = 0; // Minimum value + const int MAX_VALUE = 9; // Maximum value + + // Variables + int num1; // Holds a value + int num2; // Holds a value + int sum, answer; + + // Assigning a random number to num1 + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + // Assigning a random number to num2 + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + // Summing random num1 and num2 + sum = num1 + num2; + + // Clear Screen + clearScreen(); + + // Display problem + cout << num1 << " + " << num2 << endl; + cout << "\nType in your answer: "; + // Receive answer + answer = inputVal(answer); + + // Process answer + do + { + // If right answer + if (answer == sum) + { + cout << "\nGreat work!\n" << endl; + } + // Else wrong answer + else + { + cout << "\nNot correct, hopefully this will help...\n" << endl; + + cout << "\tIf I have " << num1 ; + + // If num1 is 1, use singular + if (num1 == 1) + { + cout << " pencil"; + } + + // Else use plural + else + { + cout << " pencils"; + } + cout << " and " << num2; + + // If num2 is 1 use singular + if (num2 == 1) + { + cout << " pen"; + } + + // Else use plural + else + { + cout << " pens"; + } + cout << endl + + // Ask for answer to problem + << "\thow many pens and pencils do I have altogether? "; + + // Error Check answer + answer = inputVal(answer); + + // If answer correct + if (answer == sum) + { + cout << "\nGreat work!\n" << endl; + } + } + // End Process answeer Do While + } while (answer != sum); + + // Write to outputFile + outputFile << num1 << " + " << num2 << " = " << sum << endl; + + // Ask if would like another problem + cout << "\nWould you like another addition problem?\n" + << "1. Yes.\n" + << "0. No. Return to main menu "; + + // Error Check + anotherProb = inputVal(anotherProb); + cout << endl; + + // Clear Screen + clearScreen(); + + // End of Another problem? Do While + } while (anotherProb == true); + + // Close outputfile + outputFile.close(); + + // Return boolean value either to + // main menu or another problem. + return anotherProb; +} + +//*************************************************************** +// The subtractionPractice function shows a random subtraction * +// problem, asks for user input, and returns a boolean value. * +//*************************************************************** + +bool subtractionPractice() +{ + // Output file stream object + ofstream outputFile; + // Open outputFile + outputFile.open("MathTutorRecord.txt"); + + // Variable + bool anotherProb; + + // Another problem? Do While + do + { + const int MIN_VALUE = 0; // Minimum value + const int MAX_VALUE = 9; // Maximum value + + // Variables + int num1; // Holds a value + int num2; // Holds a value + int sum, answer; + + // Assign random value to num1 + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + // Assign random value to num2 + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + // Sum of num1 and num2 + sum = num1 - num2; + + // Clear Screen + clearScreen(); + + // Display problem + cout << num1 << " - " << num2 << endl; + // Ask for a receive answer + cout << "\nType in your answer: "; + // Error Check answer + answer = inputVal(answer); + + // Process answer + do + { + // If right answer + if (answer == sum) + { + cout << "\nGreat work!\n" << endl; + } + + // Else wrong answer + else + { + cout << "\nSorry, hopefully this will help...\n" << endl; + cout << "\tIf I have " << num1 ; + + // If num1 is 1, use singular + if (num1 == 1) + { + cout << " pencil"; + } + + // Else use plural + else + { + cout << " pencils"; + } + cout << " and " << num2; + + // If num2 is 1, use singular + if (num2 == 1) + { + cout << " pen"; + } + + // Else use plural + else + { + cout << " pens"; + } + + // Ask for answer to problem + cout << endl + << "\tand subtract them from each other,\n" + << "\thow many do I have? "; + // Error Check answer + answer = inputVal(answer); + + // If answer correct + if (answer == sum) + { + cout << "\nGreat work!\n" << endl; + } + } + + // End Process answeer Do While + } while (answer != sum); + + // Write data to outputFile + outputFile << num1 << " - " << num2 << " = "<< sum << endl; + + // Ask if would like another problem + cout << "\nWould you like another subtraction problem?\n" + << "1. Yes.\n" + << "0. No. Return to main menu "; + // Error check + anotherProb = inputVal(anotherProb); + cout << endl; + + // End of Another problem? Do While + } while (anotherProb == true); + + // Close outputFile + outputFile.close(); + + // Return boolean value either to + // main menu or another problem. + return anotherProb; +} + +//*************************************************************** +// The multiplicationPractice function shows a random * +// multiplication problem, asks for user input, and returns a * +// boolean value. * +//*************************************************************** + +bool multiplicationPractice() +{ + // Output stream object + ofstream outputFile; + // Open file + outputFile.open("MathTutorRecord.txt"); + + // Variable + bool anotherProb; + + // Another problem? Do While + do + { + // Constants + const int MIN_VALUE = 0; // Minimum value + const int MAX_VALUE = 9; // Maximum value + + // Variables + int num1; // Holds a value + int num2; // Holds a value + int sum, answer; + + // Assign random number to num1 + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + // Assign random number to num2 + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + // Sum of num1 and num2 + sum = num1 * num2; + + // Clear screen + clearScreen(); + + // Display problem and receive answer. + cout << num1 << " * " << num2 << endl; + cout << "\nType in your answer: "; + // Error Check answer + answer = inputVal(answer); + + // Process answer + do + { + // If right answer + if (answer == sum) + { + cout << "\nGreat work!\n" << endl; + } + + // Else wrong answer + else + { + // Explain how to solve problem and + // ask for new answer. + cout << "\nNot correct, hopefully this will help...\n" << endl; + cout << "\tIf I have " << num1 << " sets of " + << num2 << " swans, how many do I have " + << "altogether? "; + // Error check answer + answer = inputVal(answer); + + // If answer right + if (answer == sum) + { + cout << "\nGreat work!\n" << endl; + } + } + // End of Processing answer. + } while (answer != sum); + + // Write data to outputFile + outputFile << num1 << " x " << num2 << " = " << sum << endl; + + // Ask if would like another problem + cout << "\nWould you like another multiplication problem?\n" + << "1. Yes.\n" + << "0. No. Return to main menu "; + // Error check anotherProb + anotherProb = inputVal(anotherProb); + cout << endl; + + // End of Another problem? Do While + } while(anotherProb == true); + + // Close outputFile + outputFile.close(); + + // Return boolean value either to + // main menu or another problem. + return anotherProb; +} + +//*************************************************************** +// The divisionPractice function shows a random division * +// problem, asks for user input, and returns a boolean value. * +//*************************************************************** + +bool divisionPractice() +{ + // Output stream object + ofstream outputFile; + // Open file + outputFile.open("MathTutorRecord.txt"); + + // Variable + bool anotherProb; + + // Another Problem? + do + { + // Constants + const int MIN_VALUE = 1; // Minimum value + const int MAX_VALUE = 9; // Maximum value + + // Variables + int num1; // Holds a value + int num2; // Holds a value + int sum, answer, remain; + + // Assign random number to num1 + num1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + // Assign random number to num2 + num2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + // Sum of num1 and num2 + sum = num1 / num2; + // Calculate the remainded or num1 and num2 + remain = num1 % num2; + + // Clear the screen + clearScreen(); + + // Display problem + cout << num1 << " / " << num2 << endl; + + // Ask to press enter to continue + cout << "\nPress [ENTER] to see answer: "; + // Clear previous input + cin.clear(); + cin.ignore(123, '\n'); + cin.get(); + + // Discribe now to solve problem + cout << endl << sum << " remainder " << remain << endl; + cout << "\n\tIf I take " << num1 << " and divide it by " << num2 + << ", \n\t" << "I will get " << sum << " with a remainder of " + << remain << endl; + + // Write data to file + outputFile << num1 << " / " << num2 << " = " << sum << " remainder " << remain << endl; + + // Ask to press enter to continue + cout << "\nPress [ENTER] twice to continue: "; + // Clear previous input + cin.clear(); + cin.ignore(123, '\n'); + cin.get(); + + // Ask if would like another problem + cout << "\nWould you like another addition problem?\n" + << "1. Yes.\n" + << "0. No. Return to main menu "; + // Error check anotherProb input + anotherProb = inputVal(anotherProb); + cout << endl; + + // End of Another Problem? do while loop + } while(anotherProb == true); + + // Close outputFile + outputFile.close(); + + // Return boolean value either to + // main menu or another problem. + return anotherProb; +} + +//*************************************************************** +// The calculateAreaOfRectangle function receives the length and* +// width from the user, calculates the area of a rectangle, and * +// prints that calculation to screen. * +//*************************************************************** + +bool calculateAreaOfRectangle() +{ + // Output stream object + ofstream outputFile; + // Open file + outputFile.open("MathTutorRecord.txt"); + + // Variable + bool anotherCal; + + // Another problem? do while loop + do + { + // Variables: Hold length, width, and area. + double area, length, width; + + clearScreen(); + + // Ask for length + cout << "What is the length of the rectangle? "; + length = inputVal(length); + + // Get width + cout << "What is the width? "; + width = inputVal(width); + + // Calculate and display + area = length * width; + cout << "\nMultiplying the length by the width " << endl + << "determines the area of a rectangle. \n" << endl; + + // Ask to pree enter ton continue + cout << "Type [ENTER] to continue: "; + // Clear previous input + cin.clear(); + cin.ignore(123, '\n'); + cin.get(); + + // Discribe how to solve the problem + cout << "\nThe area of the rectangle is " << area << endl << endl; + + // Write data to file + outputFile << "The area of the rectangle is " << area << endl; + + // Ask if would like another problem. + cout << "\nWould you like to make another calculation?\n" + << "1. Yes.\n" + << "0. No. Return to main menu "; + // Error check anotherCal + anotherCal = inputVal(anotherCal); + cout << endl; + + // End of Another probelm? do while loop + } while(anotherCal == true); + + // CLose outputFile + outputFile.close(); + + // Return boolean value either to + // main menu or another problem. + return anotherCal; +} + +//******************************************************************* +// The calculateAreaOfCircle function receives the radius of a * +// circle from the user, calculates the area, and prints the * +// calculation to screen. * +//******************************************************************* + +bool calculateAreaOfCircle() +{ + // Output stream object + ofstream outputFile; + // Open file + outputFile.open("MathTutorRecord.txt"); + + // Variable + bool anotherCal; + + // Another problem? do while loop + do + { + // Variables: Hold area, radius, PI. + const double PI = 3.14; + double area, radius, radSquare; + + // Clear Screen + clearScreen(); + + // Ask for radius + cout << "What is the radius of the circle? "; + radius = inputVal(radius); + + // Calculate and display + radSquare = (radius * radius); + area = PI * (radius * radius); + + // Explain how to solve for area + cout << "\nSquaring the radius and then multiplying" << endl + << "it's sum by PI determines the area of a circle.\n" << endl; + + // Ask to press enter to proceed + cout << "Type [ENTER] to continue: " << endl; + // Clear previous input + cin.clear(); + cin.ignore(123, '\n'); + cin.get(); + + // Display area of circle + cout << "The area of the circle is: " << area << endl << endl; + + // Write data to file + outputFile << "The area of the circle is: " << area << endl; + + // Ask if would like to make another calculation + cout << "\nWould you like to make another calculation?\n" + << "1. Yes.\n" + << "0. No. Return to main menu "; + anotherCal = inputVal(anotherCal); + cout << endl; + + // End of Another problem? do while loop + } while(anotherCal == true); + + // Close outputFile + outputFile.close(); + + // Return boolean value either to + // main menu or another problem. + return anotherCal; +} + +//******************************************************************* +// The calculateAreaOfTriangle function receives the height and base* +// of a triangle from the user, calculates the area, and prints the * +// calculation to screen. * +//******************************************************************* + +bool calculateAreaOfTriangle() +{ + // Output stream object + ofstream outputFile; + // Open file + outputFile.open("MathTutorRecord.txt"); + + // Variable + bool anotherCal; + + // Another Problem? Do while loop + do + { + // Variables: Hold length, width, and area. + double area, height, base; + + clearScreen(); // Explain program, then get length + cout << "What is the height of the triangle? "; + height = inputVal(height); + + // Get width + cout << "What is the base? "; + base = inputVal(base); + + + // Calculate and display + area = (height * base) / 2; + // Explain how to solve for area + cout << "\nMultiplying the base by the height and dividing\n" + << "their sum by 2 determines the area of a triangle.\n" << endl; + + // Ask to press enter to proceed + cout << "Type [ENTER] to continue: " << endl; + // Clear previous input + cin.clear(); + cin.ignore(123, '\n'); + cin.get(); + + // Dipslay area + cout << "The area of the triangle is " << area << endl << endl; + + // Write data to a file + outputFile << "The area of the triangle is " << area << endl; + + // Ask if would like to make another calculation + cout << "\nWould you like to make another calculation?\n" + << "1. Yes.\n" + << "0. No. Return to main menu "; + // Error check anotherCal + anotherCal = inputVal(anotherCal); + cout << endl; + + // End of Another problem? do while loop + } while(anotherCal == true); + + // Close outputFile + outputFile.close(); + + // Return boolean value either to + // main menu or another problem. + return anotherCal; +} + +//*************************************************** +// function to clear screen, using variable * +// created in PPD statement * +//*************************************************** +void clearScreen() +{ +system(clearVar); +} + +//*************************************************************** +// Function inputVal (int) check for valid input. * +// If the user types in anything other than the int data type, * +// they will be promted to enter the valid input. * +//*************************************************************** + +int inputVal(int num) +{ + while (!(cin >> num)) + { + cout << "\n\tI'm sorry a whole number must be entered: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} + +//*************************************************************** +// Function inputVal (double) check for valid input. * +// If the user types in anything other than double data type, * +// they will be promted to enter the valid data type. * +//*************************************************************** + +double inputVal(double num) +{ + while (!(cin >> num)) + { + cout << "\n\tI'm sorry a whole number must be entered: "; + cin.clear(); + cin.ignore(123, '\n'); + } + return num; +} diff --git a/Replicated Programs/CtoF-expanded.cpp b/Replicated Programs/CtoF-expanded.cpp new file mode 100644 index 0000000..0b1080c --- /dev/null +++ b/Replicated Programs/CtoF-expanded.cpp @@ -0,0 +1,173 @@ +//******************************************************************** +// +// JESUS HILARIO HERNANDEZ +// Course: COSC 1436.001 Programming Fundamentals 1 +// Lab # 5 Ch 3 Programming Challenge #10 +// Celsius to Fahrenheit extended +// Due Date: October 5, 2016 +// Instructor: Korinne Caruso +// +// Purpose: This program converts Celsius to Fahrenheit or +// Fahrenheit to Celsius. A menu is provided for the user to choose from. +// The three choices will be 1. Convert Celsius to Fahrenheit, +// 2. Fahrenheit to Celsius, and 3. End session. Aside from these +// three menu options a quit the program option is available as well. +// +// Input: Input will come from the user, through the (cin) object. +// The information the user provides will either be stored +// in a double, string, char, or an int. Further, input validation will +// occur each time the user provides information at the keyboard. +// If invalid input should occur, the user will be redirected through +// a while loop, to input valid a valid choice. +// +// Output: All output will be sent using the (cout) object. +// The user's user name along with a brief description of what +// the program does is displayed when the program is run. +// A menu with three options will be provided for the user +// to choose from. At one point in the program, +// the user will be given the option to continue the +// program or to quit the program. +// +//******************************************************************** + +#include +#include +#include +#include +using namespace std; + +int main() +{ + //Constants + const int CHOICE_1 = 1, + CHOICE_2 = 2, + CHOICE_3 = 3; + + //Variables: + double C, //Holds Celsius Temp + F; //Holds Fahrenheit Temp + string name; //Holds User name + char keepGoing; //Holds (Y/N) Ans. + int choice; //Holds Menu choice + + + //Do-While menu + do + { + cout << "\n\n\t\tThis program converts Celsius to fahrenheit " + << "\n\t\tor Fahrenheit to Celsius." << endl + << "\n\t\tSelect an option to continue: \n" + << "\t\t\t1. Convert Celsius to Fahrenheit" << endl + << "\t\t\t2. Convert Fahrenheit to Celsius" << endl + << "\t\t\t3. Quit Program\t\t\t\t"; + + // Error checking menu choice + while(!(cin >> choice) || choice < CHOICE_1 || choice > CHOICE_3) + { + //explain error + cout << "\n\t\tError: You must choose either 1, 2, or 3."; + //clear input stream + cin.clear(); + //discard previous input + cin.ignore(1200, '\n'); + } + + //switch menu + switch (choice) + { + //Choice 1 + case CHOICE_1: + //Ask for Celsius temp. + cout << "\n\t\tWhat is the Celsius temperature " + << "\n\t\tthat you would wish to convert? "; + + //Error check choice 1 + while (!(cin >> C)) + { + //Explain Error + cout << "\n\t\tError: A number must be entered. " + << "\n\t\tWhat is the Celsius temperature? "; + //clear input stream + cin.clear(); + //discard previous input + cin.ignore(1200, '\n'); + } + + //calculate C to F + F = (9.0/5.0) * C + 32; + + //Display C to F conversion + cout << "\n\n\t\t\t"<< C << " Celsius = " + << setprecision(1) << fixed << F << " Fahrenheit" << endl; + cout << endl; + //Ask user if would like to make another conversion + cout << "\n\t\tWould you like to make another " + << "conversion?\n\t\tY: to make another conversion\n\t\t" + << "N: to quit the program "; + break; + + //Choice 2 + case CHOICE_2: + cout << "\n\t\tWhat is the Fahrenheit temperature " << endl; + cout << "\t\tthat you would wish to convert? "; + + //Error check choice 2 + while(!(cin >> F)) + { + //Explain Error + cout << "\n\t\tError: A number must be entered. " + << "\n\t\tWhat is the Fahrenheit temperature?"; + //Clear input stream + cin.clear(); + //Discard previous input + cin.ignore(1200, '\n'); + } + + //Calculate F to C + C = (F - 32) * (5.0/9.0); + + //Display F to C conversion + cout << "\n\n\t\t\t" << F << " Fahrenheit = " + << setprecision(1)<< fixed << C << " Celsius" << endl; + cout << endl; + //Ask user if would like to make another conversion + cout << "\n\t\tWould you like to make another " + << "conversion (Y/N)? "; + break; + + case CHOICE_3 : + cout << "\n\t\tAre you sure you want to " + << "quit the program? (Y/N)\n\n" << endl; + + //end Switch menu + } + + cin >> keepGoing; + while(!(keepGoing == 'y' || keepGoing == 'Y' || keepGoing == 'n' || keepGoing == 'N')) + { + //Explain error + cout << "\n\t\tError: Neither Y nor N was pressed." << endl + << "\t\tWould you like to make another conversion? "; + //Clear input stream + cin.clear(); + //Discard previous input + cin.ignore(1200, '\n'); + + cin >> keepGoing; + } + + + //If NO or choice 3 + if (keepGoing == 'n' || keepGoing == 'N' || choice == 3) + { + cout << "\n\t\tThank you.\n\n\n" << endl; + } + + //End Do-While menu. + } while (keepGoing == 'y' || keepGoing == 'Y' || keepGoing == 'n' || keepGoing == 'N' || choice == 3); + + //for padding before the 0 exit code. + cout << endl << endl; + + return 0; +} diff --git a/Replicated Programs/CtoF.cpp b/Replicated Programs/CtoF.cpp new file mode 100644 index 0000000..ee59609 --- /dev/null +++ b/Replicated Programs/CtoF.cpp @@ -0,0 +1,90 @@ +//******************************************************************** +// +// Jesus H. Hernandez +// Course: COSC 1436.001 Programming FUndamentals +// Lab # 4 Ch 3 Programming Challenge #12 Celsius to Fahrenheit +// Due Date: September 25, 2016 +// Instructor: Korinne Caruso + +// Purpose: This program converts Celsius to Fahrenheit. +// Input: The program receives Celsius temperature from the user + +// Last modified: Sept. 23, 2016 + +#include +#include +using namespace std; + +int main() +{ + double C; // Celsius Variable + double F; // Fahrenheit Variable + char ans; // Answer variable + + //Description of program + cout << "This program converts celsius to fahrenheit." << endl; + cout << "Would you like to continue? (Y/N) "; + cin >> ans; + + //if statement (Y/N) responds to YES + if (ans == 'y'|| ans == 'Y') + { + cout << "\nWhat is your temperature in celsius? "; + cin.ignore() >> C; + + // calculates C to F. + F = (9.0/5.0) * C + 32; + + cout << setprecision(5); + cout << '\n' << C; + cout << "°C = " << F; + cout << "°F." << endl << endl; + + //these if/else if statements display type of weather that may occur + if (F >= 120) + { + cout << "That's oven hot!\n" << endl; //if >= 120 + } + else if (F >= 70 && F <= 120) + { + cout << "Beach weather, ay?\n" << endl;//if between 70 and 120 F + } + else if (F >= 60 && F <= 70) + { + cout << "Fall is on it's way.\n" << endl;//if between 60 and 70 F + } + else if (F >= 50 && F <= 60) + { + cout << "Grab a sweater, it's cool out.\n" << endl;//if between 50 and 60 F + } + else if (F >= 35 && F <= 50) + { + cout << "It's cold out.\n" << endl;//if between 35 and 60 F + } + else if (F >= -20 && F <= 35) + { + cout << "Stay inside! It's cold out.\n" << endl;//if between -20 and 35 F + } + else + { + cout << "Traveling to distant planets, are we?\n" << endl;//if lower that -20 F + } + + } + //else if respond to NO + else if(ans == 'n' || ans == 'N') + cout << "\nNo? Ok.\n" << endl; + + //When neither Y nor N are pressed + else + cout << "\nOops! Neither Y nor N was pressed!" << endl << endl; + + //Tells user to have a great day + cout << "Have a great day.\n" << endl; + + return 0; +} + +// Output: Program outputs the conversion from Celsius to Fahrenheit. +// +//******************************************************************** diff --git a/Replicated Programs/DISTANCE.cpp b/Replicated Programs/DISTANCE.cpp new file mode 100644 index 0000000..3c7d1f8 --- /dev/null +++ b/Replicated Programs/DISTANCE.cpp @@ -0,0 +1,28 @@ +/* + PROGRAM: DISTANCE.CPP + Written by Jesus Hilario Hernandez + This program calculates the distance + using speed and time. + Last modification: 9/21/2016 + */ + +#include + +//declares that the program will be +//accessing entities whose names are +//part of the namespace call std. + +using namespace std; + +int main() +{ + int speed = 10, time = 10, distance; //variables + + //mulitiplying speed by time. + distance = speed * time; + + //displays the result of distance calculation + cout << "The distance of speed by time is " << distance << endl; + + return 0; //terminates when program has run succesfully. +} diff --git a/Replicated Programs/NameAddPhone.cpp b/Replicated Programs/NameAddPhone.cpp new file mode 100644 index 0000000..6a93032 --- /dev/null +++ b/Replicated Programs/NameAddPhone.cpp @@ -0,0 +1,26 @@ +// This program will displays my name, +// address, and phone number. + +// JESUS HILARIO HERNANDEZ + +#include +#include +using namespace std; + + +int main() +{ + string name, address, phoneNumber; + + name = "Jesus"; address = "789 Fred Creek"; phoneNumber = "5"; + + //Display name + cout << "My name is " << name << '\n'; + //display address + cout << "I live at " << address << endl; + //diaplay phone number. + cout << "You can reach me at " << phoneNumber << endl << endl; + + + return 0; +} diff --git a/Replicated Programs/NamedConstants.cpp b/Replicated Programs/NamedConstants.cpp new file mode 100644 index 0000000..3ac6cbb --- /dev/null +++ b/Replicated Programs/NamedConstants.cpp @@ -0,0 +1,38 @@ +// This program uses the const qualifier to create constants for literals +// JESUS HILARIO HERNANDEZ + +#include +#include +using namespace std; + + +int main() +{ + //constants + const double e = 2.71828; + const long double NumOfMinInYear = 5.256E5; + const long double GravAccelFtPerSec = 32.2; + const long double GravAccelMetPerSec = 9.8; + const long double NumOfMetInMil = 1609; + + //variables that will utilize constants + double c1, c2, c3, c4 , c5; + + //5 examples of calculations utilizing Named Constants + c1 = e * NumOfMinInYear; + c2 = e * GravAccelFtPerSec; + c3 = GravAccelFtPerSec * GravAccelMetPerSec; + c4 = NumOfMinInYear - NumOfMetInMil; + c5 = GravAccelMetPerSec / NumOfMetInMil; + + //Output of each variables using the Names Constants + cout << c1 << endl; + cout << c2 << endl; + cout << c3 << endl; + cout << c4 << endl; + cout << c5 << endl; + + + + return 0; +} diff --git a/Replicated Programs/OverUnderFlow.cpp b/Replicated Programs/OverUnderFlow.cpp new file mode 100644 index 0000000..d497588 --- /dev/null +++ b/Replicated Programs/OverUnderFlow.cpp @@ -0,0 +1,17 @@ +// This program can be used to see how your system handles +// floating point overflow and underflow. + +//JESUS HILARIO HERNANDEZ +#include +using namespace std; + +int main() +{ + float test; + + test = 2.0e38 * 1000; //Should overflow test. + cout << test << endl; + test = 2.0e-38 / 2.0e38;//Should underflow test. + cout << test << endl; + return 0; +} diff --git a/Replicated Programs/ageandweight.cpp b/Replicated Programs/ageandweight.cpp new file mode 100644 index 0000000..e7a404a --- /dev/null +++ b/Replicated Programs/ageandweight.cpp @@ -0,0 +1,17 @@ +//This program displays my age and weight. +//Jesus Hilario Hernandez + +#include +using namespace std; + +int main() +{ + + int age = 45; + float weight = 390; + + cout << "My age is " << age << " and my weight is " << weight << "." << endl; + + + return 0; +} diff --git a/Replicated Programs/average-test-scores-if-statement.cpp b/Replicated Programs/average-test-scores-if-statement.cpp new file mode 100644 index 0000000..5fa5433 --- /dev/null +++ b/Replicated Programs/average-test-scores-if-statement.cpp @@ -0,0 +1,31 @@ +// This program averages three test scores + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/27/2016 + +#include //for input output +#include //for formatting output +using namespace std; + +int main() +{ + const int HIGH_SCORE = 95; //A high score is 95 or greater + int score1, score2, score3; //To hold three test scores + double average; //to hold the average score + + //Get three test scores from user. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + //Calcuate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); //formatting statement + cout << "Your average is " << average << endl; + + //If the average is a high score, the user is congratulated + if(average > HIGH_SCORE) + cout << "Congratulations! That's a high score!\n"; + + return 0; +} diff --git a/Replicated Programs/avg-of-nums.cpp b/Replicated Programs/avg-of-nums.cpp new file mode 100644 index 0000000..b387e4a --- /dev/null +++ b/Replicated Programs/avg-of-nums.cpp @@ -0,0 +1,32 @@ +// This program asks for three numbers, then +// displays the average of the numbers. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/26/2016 + +#include //for input output. This is the only library needed. +using namespace std; + +int main() +{ + double num1, num2, num3, avg; + + cout << "Enter the first number: "; + + cin >> num1; + + cout << "Enter the second number: "; + + cin >> num2; + + cout << "Enter the third number: "; + + cin >> num3; + + avg = (num1 + num2 + num3) / 3; + + cout << "The average is: " << avg << endl << endl; + + return 0; +} diff --git a/Replicated Programs/batavg.cpp b/Replicated Programs/batavg.cpp new file mode 100644 index 0000000..7105ee6 --- /dev/null +++ b/Replicated Programs/batavg.cpp @@ -0,0 +1,24 @@ +// This program will determine the batting average of a player. +// The number of hits and at bats are set internally in the program. + +// JESUS HILARIO HERNANDEZ + +#include +using namespace std; + + +const int AT_BAT = 421; +const int HITS = 123; + +int main() +{ + float batAvg; + + //an assignment statement + batAvg = static_cast(HITS) / AT_BAT; + + //output the result + cout << "The batting average is " << batAvg << endl << endl; + + return 0; +} diff --git a/Replicated Programs/bill.cpp b/Replicated Programs/bill.cpp new file mode 100644 index 0000000..9d14c42 --- /dev/null +++ b/Replicated Programs/bill.cpp @@ -0,0 +1,56 @@ +// This program will read in the quantity of a particular item and its price. +// It will then print out the total price. +// The input will come from the keyboard and the output will go to +// the screen. + +//JESUS HILARIO HERNANDEZ + +#include +#include +#include +using namespace std; + + + + +int main() + +{ + int quantity; // contains the amount of items purchased + float itemPrice; // contains the price of each item + float totalBill; // contains the total bill. + string item; //variable item + + + //formatted outputed numbers + cout << setprecision(2) << fixed << showpoint; + + //ask for name of item + cout << "Please input the name of the item" << endl; + + //receiving name of item + getline(cin, item); + + //ask for number of items bought + cout << "Please input the number of items bought" << endl; + + //receiving qunatitiy + cin >> quantity; + + //ask for price of each item + cout << "Please input the price of each item" << endl; + + //receiving price of item + cin >> itemPrice; + + //calculate quantity * itemPrice + totalBill = quantity * itemPrice; + + //display item bought and total cost + cout << "The item that you bought is " << item << "\nThe total bill is $" << totalBill << + endl << endl; + + // with a label to the screen. + + return 0; +} diff --git a/Replicated Programs/cin-ignore.cpp b/Replicated Programs/cin-ignore.cpp new file mode 100644 index 0000000..97bc789 --- /dev/null +++ b/Replicated Programs/cin-ignore.cpp @@ -0,0 +1,24 @@ +// This program sucessfully uses both +// cin >> and cin.ignore() for keyboard unput + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/26/2016 + +#include +using namespace std; + +int main() +{ + char ch; + int number; + + cout << "Enter a number: "; + cin >> number; + cin.ignore(); //Skip the newline '\n' character [Enter] + cout << "Enter a character: "; + ch = cin.get(); + cout << "Thank You!" << endl; + + return 0; +} diff --git a/Replicated Programs/cin.getfunction.cpp b/Replicated Programs/cin.getfunction.cpp new file mode 100644 index 0000000..3d92af4 --- /dev/null +++ b/Replicated Programs/cin.getfunction.cpp @@ -0,0 +1,20 @@ +//This program demonstrates three ways +// to use cin.get() to pause a program. +#include + +using namespace std; + +int main() +{ + char ch; // cin.get() uses any character to achieve it's purpose + + cout << "This program has paused. Press Enter to continue." << endl; + cin.get(ch); //FIRST WAY, YES VARIABLE USED + cout << "It has paused a second time. Please press Enter again." << endl; + ch = cin.get(); //SECOND WAY, YES VARIABLE USED + cout << "It as paused a third time. Please press the Enter key again." << endl; + cin.get(); // THIRD WAY, NO VARIABLE USED. + cout << "THANK YOU!" << " Have a nice day." << endl << endl; + + return 0; +} diff --git a/Replicated Programs/cin.ignore.cpp b/Replicated Programs/cin.ignore.cpp new file mode 100644 index 0000000..53e42b0 --- /dev/null +++ b/Replicated Programs/cin.ignore.cpp @@ -0,0 +1,22 @@ +//This program successfully uses both +//cin >> and cin.get() for keyboard input. + +//JESUS HILARIO HERNANDEZ + +#include +using namespace std; + +int main() +{ + char ch; + int number; + + cout << "Enter a number: " << endl; + cin >> number; + cin.ignore(); //Skip the newline character. + cout << "Enter a character: " << endl; + ch = cin.get(); + cout << "Thank You!\n" << endl; + + return 0; +} diff --git a/Replicated Programs/converts-kph-to-mph-for-loop.cpp b/Replicated Programs/converts-kph-to-mph-for-loop.cpp new file mode 100644 index 0000000..8982664 --- /dev/null +++ b/Replicated Programs/converts-kph-to-mph-for-loop.cpp @@ -0,0 +1,46 @@ +//******************************************************************** +// This program converts the speed 60 kph through +// 130 kph (in 10kph increments) to mph. +// +// JESUS HILARIO HERNANDEZ +// Last updated: October 5, 2016 +// +//******************************************************************** + +#include +#include +using namespace std; + +int main() +{ + // Constants for the speeds + const int START_KPH = 60, // Starting speed + END_KPH = 130, // Ending speed + INCREMENT = 10; // Speed increment + + // Constant for the conversion factor + const double CONVERSION_FACTOR = 0.6214; + + // Variables + int kph; // To hold speeds in kph + double mph; // To hold speeds in mph + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Display the table headings. + cout << "KPH\t\t\tMPH\n"; + cout << "---------------\n"; + + // Display the speeds. + for (kph = START_KPH; kph <= END_KPH; kph += INCREMENT) + { + // Calculate mph + mph = kph * CONVERSION_FACTOR; + + // Display the speeds in kph and mph. + cout << kph << "\t\t\t" << mph << endl; + + } + return 0; +} diff --git a/Replicated Programs/if-elseif.cpp b/Replicated Programs/if-elseif.cpp new file mode 100644 index 0000000..bd6948d --- /dev/null +++ b/Replicated Programs/if-elseif.cpp @@ -0,0 +1,40 @@ +// This program illustrates the use of the if / else if statement. + +// JESUS HILARIO HERNANDEZ + +#include +using namespace std; + + +int main() +{ + char grade; + + cout << "What grade did you earn in Programming I ?" << endl; + cin >> grade; + + //For grades A-D, output YOU PASSED! + if (grade == 'A' || grade == 'B' || grade == 'C' || grade == 'D') + cout << "YOU PASSED!" << endl; + + + if(grade == 'A') //grade == A + cout << "an A - excellent work !" << endl; + + else if(grade == 'B') //grade == B + cout << "you got a B - good job" << endl; + + else if(grade == 'C') //grade == C + cout << "earning a C is satisfactory" << endl; + + else if(grade == 'D') //grade == D + cout << "while D is passing, there is a problem" << endl; + + else if(grade == 'F') //grade == F + cout << "you failed - better luck next time" << endl; + + else //Invalid Input + cout << "You did not enter an A, B, C, D, or F" << endl; + + return 0; +} diff --git a/Replicated Programs/increment-decrement.cpp b/Replicated Programs/increment-decrement.cpp new file mode 100644 index 0000000..f2e20c1 --- /dev/null +++ b/Replicated Programs/increment-decrement.cpp @@ -0,0 +1,55 @@ +//This program demonstrates the ++ and -- operators. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/30/16 + +#include +#include +using namespace std; + +int main() +{ + int num = 4; // num starts out with 4. + + //Display the value in num. + cout << "The variable num is " << num << endl; + cout << "I will increment num.\n\n"; + + //Use postfix ++ to increment num. + num++; + cout << "Now the variable num is " << num << endl; + cout << "I will increment num again.\n\n"; + + //Use prefix ++ to increment num. + ++num; + cout << "Now the variable num is " << num << endl; + cout << "I will now decrement num.\n\n"; + + //Use postfix -- to increment num. + num--; + cout << "Now the variable num is " << num << endl; + cout << "I will now decrement num again.\n\n"; + + //Use prefix -- to increment num. + --num; + cout << "Now the variable num is " << num << endl; + + //Prefix / Postfix example. + + int num = 4; + + cout << num << endl; //displays 4 + cout << num ++ << endl; //Displays 4, then adds 1 to num + cout << num << endl; //Displays 5 + cout << ++num << endl; //Adds 1 to num, then displays 6 + cout << endl; //Displlays a blank line + + cout << num << endl; //Displays 6 + cout << num-- << endl; //Displays 6, then subtracts 1 from num + cout << num << endl; //Displays 5 + cout << --num << endl; //Subtracts 1 from num, then displays 4 + + + return 0; +} diff --git a/Replicated Programs/initials.cpp b/Replicated Programs/initials.cpp new file mode 100644 index 0000000..179bc83 --- /dev/null +++ b/Replicated Programs/initials.cpp @@ -0,0 +1,22 @@ +// This program will display my initials + +// JESUS HILARIO HERNANDEZ + +#include +using namespace std; + + +int main() +{ + char first, middle, last; + + first = 'J'; + middle = 'H'; + last = 'H'; + + //this statement outputs my initials + cout << first << middle << last << endl << endl; + + + return 0; +} diff --git a/Replicated Programs/logical-OR-operator.cpp b/Replicated Programs/logical-OR-operator.cpp new file mode 100644 index 0000000..379684f --- /dev/null +++ b/Replicated Programs/logical-OR-operator.cpp @@ -0,0 +1,41 @@ +//This program demonstrates the logical || operator. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/27/16 + +#include +#include +using namespace std; + +int main() +{ + //Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + double income; //annual income + int years; //Years at the current job. + + //Get the annual income + cout << "What is your annual income? "; + cin >> income; + + //Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job. "; + cin >> years; + + //Determine the user's loan qualifications. + if (income >= MIN_INCOME || years > MIN_YEARS) + cout << "You qualify.\n"; + else + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more that " << MIN_YEARS + << " years.\n"; + } + + return 0; +} diff --git a/Replicated Programs/rand-srand-time-functions.cpp b/Replicated Programs/rand-srand-time-functions.cpp new file mode 100644 index 0000000..3993d93 --- /dev/null +++ b/Replicated Programs/rand-srand-time-functions.cpp @@ -0,0 +1,28 @@ +// This program demostrates random number. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/26/2016 + +#include //for input output +#include //For rand() and srand() +#include //for the time() function +using namespace std; + +int main() +{ + //Get the system time. + unsigned seed = time(0); + + //Seed the random number generator. + //srand() accepts an unsigned int argument, + //which acts as a seed value for the algorithm. + srand(seed); + + //Display three random numbers. + cout << rand() << endl; + cout << rand() << endl; + cout << rand() << endl; + + return 0; +} diff --git a/Replicated Programs/righttrig.cpp b/Replicated Programs/righttrig.cpp new file mode 100644 index 0000000..0d1d1f0 --- /dev/null +++ b/Replicated Programs/righttrig.cpp @@ -0,0 +1,33 @@ +// This program will input the value of two sides of a right triangle and then +// determine the size of the hypotenuse. + +// JESUS HILARIO HERNANDEZ + +#include +#include // needed for math functions like sqrt() +#include //needed for formatting output +using namespace std; + + + +int main() + +{ + + float a,b; // the smaller two sides of the triangle + float hyp; // the hypotenuse calculated by the program + + cout << "Please input the value of the two sides" << endl; + cin >> a >> b; + + + // Fill in the assignment statement that determines the hypotenuse. + hyp = sqrt(pow(a, 2) + pow(b, 2)); + + cout << "The sides of the right triangle are " << a << " and " << b << endl; + + //setprecision(3) used for round to 2nd decimal place + cout << "The hypotenuse is " << setprecision(3) << hyp << endl << endl; + + return 0; +} diff --git a/Replicated Programs/rollingdice.cpp b/Replicated Programs/rollingdice.cpp new file mode 100644 index 0000000..8266206 --- /dev/null +++ b/Replicated Programs/rollingdice.cpp @@ -0,0 +1,73 @@ +// This program simulates rolling dice. With win-lose results in if/else if statements + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/26/2016 + +#include //for input output +#include //For rand() and srand() +#include //for the time() function +using namespace std; + +int main() +{ + //Constants + const int MIN_VALUE = 1; //Minimum die value + const int MAX_VALUE = 6; //Maximum die value + + //Variables + int die1; //to hold the value of die #1 + int die2; //To hold the value of die #2 + + //Get the system time. + unsigned seed = time(0); + + //Seed the random number generator. + srand(seed); + + //Dice roll 1 + cout << "Rolling the dice...\n"; + die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << die1 << endl; + cout << die2 << endl; + + //Win-Lose results 1 + if (die1 + die2 == 7 || die1 + die2 == 11) + cout << "YOU WIN!\n" << endl; + else if (die1 + die2 == 2) + cout << "SNAKE EYES!\n" << endl; + else + cout << "Keep shooting!\n" << endl; + + //Dice roll 2 + cout << "Rolling the dice...\n"; + die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << die1 << endl; + cout << die2 << endl; + + //Win-Lose results 2 + if (die1 + die2 == 7 || die1 + die2 == 11) + cout << "YOU WIN!\n" << endl; + else if (die1 + die2 == 2) + cout << "SNAKE EYES!\n" << endl; + else + cout << "Keep shooting!\n" << endl; + + //Dice roll 3 + cout << "Rolling the dice...\n"; + die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << die1 << endl; + cout << die2 << endl; + + //Win-Lose results 3 + if (die1 + die2 == 7 || die1 + die2 == 11) + cout << "YOU WIN!\n" << endl; + else if (die1 + die2 == 2) + cout << "SNAKE EYES!\n" << endl; + else + cout << "Keep shooting!\n" << endl; + return 0; +} diff --git a/Replicated Programs/setprecision-floating-point.cpp b/Replicated Programs/setprecision-floating-point.cpp new file mode 100644 index 0000000..0da8f5b --- /dev/null +++ b/Replicated Programs/setprecision-floating-point.cpp @@ -0,0 +1,31 @@ +//This program demonstrates how setprecision rounds +// a floating point value + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/27/2016 + +#include //for input output +#include // REQUIRED FOR setprecision() manipulator +using namespace std; + +int main() +{ + double quotient, number1 = 132.3664, number2 = 26.91; + + quotient = number1 / number2; + cout << quotient << endl; + cout << setprecision(5) << quotient << endl; //float 5 digits NOT! decimal places + cout << setprecision(4) << quotient << endl; //float 4 digits NOT! decimal places + cout << setprecision(3) << quotient << endl; //float 3 digits NOT! decimal places + cout << setprecision(2) << quotient << endl; //float 2 digits NOT! decimal places + cout << setprecision(1) << quotient << endl; //float 1 digits NOT! decimal places + + //If the value of a number is expressed in fewer digits of precision than specified, + //the manipulator will have no effect. + cout << '\n' << setprecision(5) << 21.2 << endl; + cout << setprecision(5) << 54 << endl; + cout << setprecision(5) << 67.34552 << endl; + + return 0; +} diff --git a/Replicated Programs/setw-setprecision-fixed.cpp b/Replicated Programs/setw-setprecision-fixed.cpp new file mode 100644 index 0000000..77793d7 --- /dev/null +++ b/Replicated Programs/setw-setprecision-fixed.cpp @@ -0,0 +1,36 @@ +//This program asks for sales figures for 3 days. The total +// sales are calculated and displayed in a table. +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + //Get the sales for each day. + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + //Calculate the total sales. + total = day1 + day2 + day3; + + //Display the sales figures. + cout << "\nSales Figures\n"; + cout << "-------------\n"; + // All floating point numbers that are subsequently + // printed will be + // displayed in fixed point notation. + cout << setprecision(2) << fixed; + + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + + return 0; +} diff --git a/Replicated Programs/setw-stream-manipulator.cpp b/Replicated Programs/setw-stream-manipulator.cpp new file mode 100644 index 0000000..4a7b371 --- /dev/null +++ b/Replicated Programs/setw-stream-manipulator.cpp @@ -0,0 +1,47 @@ +//This program displays three rows of numbers. +//setw() stream manipulator practice and notice + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/27/2016 + +#include //for input output +#include // REQUIRED FOR setw() stream manipulator +using namespace std; + +int main() +{ + int num1 = 2897, num2 = 5, num3 = 837, + num4 = 34, num5 = 7, num6 = 1623, + num7 = 390, num8 = 3456, num9 = 12; + + //Display the first row of numbers + cout << setw(6) << num1 + << setw(6) << num2 + << setw(6) << num3 + << endl; + + //Display the second row of numbers + cout << setw(6) << num4 + << setw(6) << num5 + << setw(6) << num6 + << endl; + + //Display the third row of numbers + cout << setw(6) << num7 + << setw(6) << num8 + << setw(6) << num9 + << endl; + + int intValue = 3928; + double doubleValue = 91.5; + //This name is larger than setw(16), thus cout + // will overide the setw value refer to line 43. + string stringValue = "Jesus H. Hernandez"; + + cout << "(" << setw(5) << intValue << ")" << endl; //setw(5) + cout << "(" << setw(8) << doubleValue << ")" << endl; //setw(8) + cout << "(" << setw(16) << stringValue << ")" << endl; //setw(16) + + return 0; +} diff --git a/Replicated Programs/sqrt-pow-functions.cpp b/Replicated Programs/sqrt-pow-functions.cpp new file mode 100644 index 0000000..8ca679f --- /dev/null +++ b/Replicated Programs/sqrt-pow-functions.cpp @@ -0,0 +1,29 @@ +// This program asks for the lengths of the two side of a +// right triangle. The length of the hypotenuse is then +// calculated and displayed. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/26/2016 + +#include //for input output +#include //for setprecision() +#include //For the sqrt() and pow() functions. +using namespace std; + +int main() +{ + double a, b, c; + + cout << "Enter the length of side a: "; + cin >> a; + cout << "Enter the length of side b: "; + cin >> b; + + //use pathag theorem + c = sqrt(pow(a, 2.0) + pow(b, 2.0)); //Use 2.0 for decimal answers, instead of just 2 + cout << "The length of the hypotenuse is "; + cout << setprecision(2) << c << endl << '\n'; + + return 0; +} diff --git a/Replicated Programs/static_cast-mathematics.cpp b/Replicated Programs/static_cast-mathematics.cpp new file mode 100644 index 0000000..181e772 --- /dev/null +++ b/Replicated Programs/static_cast-mathematics.cpp @@ -0,0 +1,30 @@ +//This program uses static_cast expressions +// with mathematical expressions + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/27/2016 + +#include //for input output + +using namespace std; + +int main() +{ + int a = 5, b = 12; + double x = 3.4, z = 9.1; + + + cout << b / a << endl; + cout << x * a << endl; + cout << static_cast(b / a) << endl; + cout << static_cast(b) / a << endl; + cout << b / static_cast(a) << endl; + cout << static_cast(b) / static_cast(a) << endl; + cout << b / static_cast(x)<< endl; + cout << static_cast(x) * static_cast(z) << endl; + cout << static_cast(x * z)<< endl; + cout << static_cast(static_cast(x) * static_cast(z))<< endl; + + return 0; +} diff --git a/Replicated Programs/tabledata.cpp b/Replicated Programs/tabledata.cpp new file mode 100644 index 0000000..dbd32f7 --- /dev/null +++ b/Replicated Programs/tabledata.cpp @@ -0,0 +1,46 @@ +// This program will bring in two prices and two quantities of items +// from the keyboard and print those numbers in a formatted chart. + +//JESUS HILARIO HERNANDEZ + +#include +#include // Needed for formatted output +using namespace std; + + +int main() + +{ + float price1, price2; // The price of 2 items + int quantity1, quantity2; // The quantity of 2 items + + + cout << setprecision(2) << fixed << showpoint; + cout << "Please input the price and quantity of the first item" << endl; + + // Fill in the input statement that reads in price1 and + // quantity1 from the keyboard. + cin >> price1 >> quantity1; + + //ask for price and quantity of second item + cout << "\nPlease input the price and quantity of the second item" << endl; + + // Fill in the prompt for the second price and quantity. + cin >> price2 >> quantity2; + + // Fill in the input statement that reads in price2 and + // quantity2 from the keyboard. + + cout << endl << setw(15) << "PRICE" << setw(12) << "QUANTITY\n\n"; + + // Fill in the output statement that prints the first price + // and quantity. Be sure to use setw() statements. + cout << setw(14) << price1 << setw(8) << quantity1 << endl; + + // Fill in the output statement that prints the second price + // and quantity. + cout << setw(14) << price2 << setw(8) << quantity2 << endl << endl; + + return 0; + +} diff --git a/Replicated Programs/type-cast-expression-int2char.cpp b/Replicated Programs/type-cast-expression-int2char.cpp new file mode 100644 index 0000000..0b3d5de --- /dev/null +++ b/Replicated Programs/type-cast-expression-int2char.cpp @@ -0,0 +1,24 @@ +//This program uses a type cast expression +// to print a character from a number. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/27/2016 + +#include //for input output + +using namespace std; + +int main() +{ + int number = 65; + + //Display the value of the number variable + cout << number << endl; + + //DIsplay the value of number converted to + //The char data type. + cout << static_cast(number) << endl; //the asci character for 65 is A + + return 0; +} diff --git a/Replicated Programs/type-cast-integer-division.cpp b/Replicated Programs/type-cast-integer-division.cpp new file mode 100644 index 0000000..e726a17 --- /dev/null +++ b/Replicated Programs/type-cast-integer-division.cpp @@ -0,0 +1,28 @@ +// This program uses a type cast to avoid integer division. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/27/2016 + +#include //for input output + +using namespace std; + +int main() +{ + int books; //Number of books to read + int months; //Number of months spent reading + double perMonth; //Average number of books per month + + cout << "How many books do you plan to read? "; + cin >> books; + cout << "How many months will it take you to read them? "; + cin >> months; + + //The following statement turns the int books into a + // double before it is divided by months! + perMonth = static_cast(books) / months; + cout << "That's " << perMonth << " books per month.\n"; + + return 0; +} diff --git a/Replicated Programs/user-controlled-for-loop.cpp b/Replicated Programs/user-controlled-for-loop.cpp new file mode 100644 index 0000000..798f7d4 --- /dev/null +++ b/Replicated Programs/user-controlled-for-loop.cpp @@ -0,0 +1,35 @@ +//******************************************************************** +// This program demonstrates a user controlled for loop. +// +// JESUS HILARIO HERNANDEZ +// Last updated: October 5, 2016 +// +//******************************************************************** + +#include +using namespace std; + +int main() +{ + int minNumber, // Starting number to square + maxNumber; // Maximum number to square + + // Get the minimum and maximum values to display + cout << "I will display a table of numbers and " + << "their squares.\n" + << "Enter the starting number: "; + cin >> minNumber; + cout << "Enter the ending number: "; + cin >> maxNumber; + cout << "Enter the ending number: "; + + // Display the table + cout << "Number Number Squared\n" + << "-------------------------\n"; + + for (int num = minNumber; num <= maxNumber; num++) + { + cout << num << "\t\t" << (num * num) << endl; + } + return 0; +} diff --git a/Replicated Programs/volume-cost-charge-profit.cpp b/Replicated Programs/volume-cost-charge-profit.cpp new file mode 100644 index 0000000..0738f67 --- /dev/null +++ b/Replicated Programs/volume-cost-charge-profit.cpp @@ -0,0 +1,61 @@ +// This program calculates the volume (in cubic feet), +// cost, customer price, and profit of any crate that +// is built. + +//JESUS HILARIO HERNANDEZ + +//Last modified: 9/26/2016 + +#include //for input output. This is the only library needed. +#include // for setprecision() and formatting. +using namespace std; + +int main() +{ + const double COST_PER_CUBIC_FOOT = 0.23; //2 const double integers + const double CHARGE_PER_CUBIC_FOOT = 0.5; + + double length, //7 double integers TBD + width, + height, + volume, + cost, + charge, + profit; + + //Set the desired output formatting for numbers + cout << setprecision(2) << fixed << showpoint; + + //Ask and receive crate's length from user + cout << "Enter the crate's length: "; + cin >> length; + + //Ask and receive crate's width from user + cout << "Enter the crate's width: "; + cin >> width; + + //Ask and receive crate's height from user + cout << "Enter the crate's height: "; + cin >> height; + + + + //Calculates and displays the volume of the crate. + volume = length * width * height; + cout << "\nThe crate's volume is: " << volume << " cubic feet." << endl; + + //Calculates and displays the cost of building the crate. + cost = volume * COST_PER_CUBIC_FOOT; + cout << "The cost to make the crate is: $" << cost << endl; + + //Calculates and displays the customer's charge. + charge = volume * CHARGE_PER_CUBIC_FOOT; + cout << "Your charge is: $" << charge << endl; + + //Calculates and displays the profit made. + profit = charge - cost; + cout << "The profit made is: $" << profit << endl << endl; + + + return 0; +} diff --git a/SourceCode/Appendix F/PrF-1.cpp b/SourceCode/Appendix F/PrF-1.cpp new file mode 100755 index 0000000..d98756c --- /dev/null +++ b/SourceCode/Appendix F/PrF-1.cpp @@ -0,0 +1,19 @@ +// Demonstrates a simple namespace +#include +using namespace std; + +namespace test +{ +int x, y, z; +} + +int main() +{ + test::x = 10; + test::y = 20; + test::z = 30; + cout << "The values are:\n"; + cout << test::x << " " << test::y + << " " << test::z << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix F/PrF-2.cpp b/SourceCode/Appendix F/PrF-2.cpp new file mode 100755 index 0000000..a60fa7b --- /dev/null +++ b/SourceCode/Appendix F/PrF-2.cpp @@ -0,0 +1,30 @@ +// Demonstrates two namespaces +#include +using namespace std; + +namespace test1 +{ + int x, y, z; +} + +namespace test2 +{ + int x, y, z; +} + +int main() +{ + test1::x = 10; + test1::y = 20; + test1::z = 30; + cout << "The test1 values are:\n"; + cout << test1::x << " " << test1::y + << " " << test1::z << endl; + test2::x = 1; + test2::y = 2; + test2::z = 3; + cout << "The test2 values are:\n"; + cout << test2::x << " " << test2::y + << " " << test2::z << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix F/PrF-3.cpp b/SourceCode/Appendix F/PrF-3.cpp new file mode 100755 index 0000000..7117485 --- /dev/null +++ b/SourceCode/Appendix F/PrF-3.cpp @@ -0,0 +1,17 @@ +// A demonstration of the using namespace statement. +#include +#include "nsdemo.h" +using namespace std; +using namespace demo; + +int main() +{ + testObject.x = 10; + testObject.y = 20; + testObject.z = 30; + cout << "The values are:\n" + << testObject.x << " " + << testObject.y << " " + << testObject.z << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix F/nsdemo.h b/SourceCode/Appendix F/nsdemo.h new file mode 100755 index 0000000..51d2997 --- /dev/null +++ b/SourceCode/Appendix F/nsdemo.h @@ -0,0 +1,15 @@ +// This file defines a namespace named demo. +// In the demo namespace a class named NsDemo +// is declared, and an instance of the class +// named testObject is defined. + +namespace demo +{ + class NsDemo + { + public: + int x, y, z; + }; + + NsDemo testObject; +} \ No newline at end of file diff --git a/SourceCode/Appendix G/argdemo.cpp b/SourceCode/Appendix G/argdemo.cpp new file mode 100755 index 0000000..e5bf3e1 --- /dev/null +++ b/SourceCode/Appendix G/argdemo.cpp @@ -0,0 +1,17 @@ +// This program demonstrates how to read +// command line arguments. +#include +using namespace std; + +int main(int argc, char *argv[]) +{ + cout << "You entered " << (argc - 1); + cout << " command line arguments.\n"; + if (argc > 1) + { + cout << "Here they are:\n"; + for (int count = 1; count < argc; count++) + cout << argv[count] << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix G/sum.cpp b/SourceCode/Appendix G/sum.cpp new file mode 100755 index 0000000..454455f --- /dev/null +++ b/SourceCode/Appendix G/sum.cpp @@ -0,0 +1,18 @@ +// This program takes two command line arguments, +// assumed to be numbers, and displays their sum. +#include +#include // Needed for atof +using namespace std; + +int main(int argc, char *argv[]) +{ + double total = 0; + + if (argc > 1) + { + for (int count = 1; count < argc; count++) + total += atof(argv[count]); + cout << total << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix J/Pet.cpp b/SourceCode/Appendix J/Pet.cpp new file mode 100755 index 0000000..ed021aa --- /dev/null +++ b/SourceCode/Appendix J/Pet.cpp @@ -0,0 +1,16 @@ +// Pet class implementation file +#include +#include "Pet.h" +using namespace std; + +// Constructor +Pet::Pet(string str) +{ + name = str; +} + +// getName member function +string Pet::getName() const +{ + return name; +} diff --git a/SourceCode/Appendix J/Pet.h b/SourceCode/Appendix J/Pet.h new file mode 100755 index 0000000..f20cacd --- /dev/null +++ b/SourceCode/Appendix J/Pet.h @@ -0,0 +1,20 @@ +// Pet class specification file +#ifndef PET_H +#define PET_H +#include +using namespace std; + +class Pet +{ +private: + string name; // To hold the pet's name + +public: + // Constructor + Pet(string); + + // Accessor function for name + string getName() const; +}; + +#endif diff --git a/SourceCode/Appendix J/PrJ-1.cpp b/SourceCode/Appendix J/PrJ-1.cpp new file mode 100755 index 0000000..2d9190e --- /dev/null +++ b/SourceCode/Appendix J/PrJ-1.cpp @@ -0,0 +1,13 @@ +#include +#include "Pet.h" +using namespace std; + +int main() +{ + // Create an instance of the Pet class. + Pet myPet("Fido"); + + // Display my pet's name. + cout << "My pet's name is " << myPet.getName() << endl; + return 0; +} diff --git a/SourceCode/Appendix J/PrJ-2.cpp b/SourceCode/Appendix J/PrJ-2.cpp new file mode 100755 index 0000000..c027d25 --- /dev/null +++ b/SourceCode/Appendix J/PrJ-2.cpp @@ -0,0 +1,34 @@ +// This program uses the Rectangle class, which is declared in +// the Rectangle.h file. The Rectangle class's member functions +// are defined in the Rectangle.cpp file. This program should +// be compiled with those files in a project. +#include +#include "Rectangle.h" // Needed for Rectangle class +using namespace std; + +int main() +{ + Rectangle box; // Define an instance of the Rectangle class + double rectWidth; // Local variable for width + double rectLength; // Local variable for length + + // Get the rectangle's width and length from the user. + cout << "This program will calculate the area of a\n"; + cout << "rectangle. What is the width? "; + cin >> rectWidth; + cout << "What is the length? "; + cin >> rectLength; + + // Store the width and length of the rectangle + // in the box object. + box.setWidth(rectWidth); + box.setLength(rectLength); + + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + + return 0; +} diff --git a/SourceCode/Appendix J/Rectangle.cpp b/SourceCode/Appendix J/Rectangle.cpp new file mode 100755 index 0000000..a962792 --- /dev/null +++ b/SourceCode/Appendix J/Rectangle.cpp @@ -0,0 +1,62 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// getWidth returns the value in the member variable width. * +//*********************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//************************************************************* +// getLength returns the value in the member variable length. * +//************************************************************* + +double Rectangle::getLength() const +{ + return length; +} + +//************************************************************ +// getArea returns the product of width times length. * +//************************************************************ + +double Rectangle::getArea() const +{ + return width * length; +} \ No newline at end of file diff --git a/SourceCode/Appendix J/Rectangle.h b/SourceCode/Appendix J/Rectangle.h new file mode 100755 index 0000000..ed481b4 --- /dev/null +++ b/SourceCode/Appendix J/Rectangle.h @@ -0,0 +1,20 @@ +// Specification file for the Rectangle class. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +// Rectangle class declaration. + +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +#endif diff --git a/SourceCode/Appendix J/RectangleData.cpp b/SourceCode/Appendix J/RectangleData.cpp new file mode 100755 index 0000000..cdd7eed --- /dev/null +++ b/SourceCode/Appendix J/RectangleData.cpp @@ -0,0 +1,33 @@ +// This program uses the Rectangle class's specification +// and implementation files. +#include +#include "Rectangle.h" // Contains the class declaration. +using namespace std; + +int main() +{ + Rectangle box; // Define an instance of the class. + float rectWidth, // Local varibale for width. + rectLength; // Local variable for length. + + // Get the rectangle's width and length from the user. + cout << "This program will calculate the area of a\n"; + cout << "rectangle. What is the width? "; + cin >> rectWidth; + cout << "What is the length? "; + cin >> rectLength; + + if (!box.setWidth(rectWidth)) // Store the width. + cout << "Invalid value for width.\n"; + else if (!box.setLength(rectLength)) // Store the length. + cout << "Invalid value for length.\n"; + else + { + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + } + return 0; +} diff --git a/SourceCode/Appendix K/PrK-1.cpp b/SourceCode/Appendix K/PrK-1.cpp new file mode 100755 index 0000000..8f6d4bc --- /dev/null +++ b/SourceCode/Appendix K/PrK-1.cpp @@ -0,0 +1,31 @@ +// This program asks for sales figures for 3 days. The total +// sales is calculated and displayed in a table. +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + total = day1 + day2 + day3; + + cout.precision(2); + cout.setf(ios::fixed | ios::showpoint); + + cout << "\nSales Figures\n"; + cout << "-------------\n"; + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix K/PrK-2.cpp b/SourceCode/Appendix K/PrK-2.cpp new file mode 100755 index 0000000..f34de41 --- /dev/null +++ b/SourceCode/Appendix K/PrK-2.cpp @@ -0,0 +1,14 @@ +// This program uses cin's width member function. +#include +using namespace std; + +int main() +{ + char word[5]; + + cout << "Enter a word: "; + cin.width(5); + cin >> word; + cout << "You entered " << word << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix K/PrK-3.cpp b/SourceCode/Appendix K/PrK-3.cpp new file mode 100755 index 0000000..89eff61 --- /dev/null +++ b/SourceCode/Appendix K/PrK-3.cpp @@ -0,0 +1,27 @@ +// This program uses the precision member function of a +// file stream object to format file output. +#include +#include +using namespace std; + +int main() +{ + fstream dataFile; + double num = 123.456; + + // Open the file. + dataFile.open("numfile.txt", ios::out); + + // Write a value at various digits of precision + dataFile << num << endl; + dataFile.precision(5); + dataFile << num << endl; + dataFile.precision(4); + dataFile << num << endl; + dataFile.precision(3); + dataFile << num << endl; + + // Close the file. + dataFile.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix K/numfile.txt b/SourceCode/Appendix K/numfile.txt new file mode 100755 index 0000000..4b2128f --- /dev/null +++ b/SourceCode/Appendix K/numfile.txt @@ -0,0 +1,4 @@ +123.456 +123.46 +123.5 +123 \ No newline at end of file diff --git a/SourceCode/Chapter 01/Pr1-1.cpp b/SourceCode/Chapter 01/Pr1-1.cpp new file mode 100755 index 0000000..f4efad8 --- /dev/null +++ b/SourceCode/Chapter 01/Pr1-1.cpp @@ -0,0 +1,23 @@ +// This progam calculates the user's pay. +#include +using namespace std; + +int main() +{ + double hours, rate, pay; + + // Get the number of hours worked. + cout << "How many hours did you work? "; + cin >> hours; + + // Get the hourly pay rate. + cout << "How much do you get paid per hour? "; + cin >> rate; + + // Calculate the pay. + pay = hours * rate; + + // Display the pay. + cout << "You have earned $" << pay << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-1.cpp b/SourceCode/Chapter 02/Pr2-1.cpp new file mode 100755 index 0000000..b4b174b --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-1.cpp @@ -0,0 +1,9 @@ +// A simple C++ program +#include +using namespace std; + +int main() +{ + cout << "Programming is great fun!"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-10.cpp b/SourceCode/Chapter 02/Pr2-10.cpp new file mode 100755 index 0000000..1f250d8 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-10.cpp @@ -0,0 +1,20 @@ +// This program has variables of several of the integer types. +#include +using namespace std; + +int main() +{ + int checking; + unsigned int miles; + long days; + + checking = -20; + miles = 4276; + days = 189000; + cout << "We have made a long journey of " << miles; + cout << " miles.\n"; + cout << "Our checking account balance is " << checking; + cout << "\nAbout " << days << " days ago Columbus "; + cout << "stood on this spot.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-11.cpp b/SourceCode/Chapter 02/Pr2-11.cpp new file mode 100755 index 0000000..6af16e8 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-11.cpp @@ -0,0 +1,16 @@ +// This program shows three variables defined on the same line. +#include +using namespace std; + +int main() +{ + int floors, rooms, suites; + + floors = 15; + rooms = 300; + suites = 30; + cout << "The Grande Hotel has " << floors << " floors\n"; + cout << "with " << rooms << " rooms and " << suites; + cout << " suites.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-12.cpp b/SourceCode/Chapter 02/Pr2-12.cpp new file mode 100755 index 0000000..efa5f44 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-12.cpp @@ -0,0 +1,14 @@ +// This program works with characters. +#include +using namespace std; + +int main() +{ + char letter; + + letter = 'A'; + cout << letter << endl; + letter = 'B'; + cout << letter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-13.cpp b/SourceCode/Chapter 02/Pr2-13.cpp new file mode 100755 index 0000000..965508b --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-13.cpp @@ -0,0 +1,15 @@ +// This program demonstrates the close relationship between +// characters and integers. +#include +using namespace std; + +int main() +{ + char letter; + + letter = 65; + cout << letter << endl; + letter = 66; + cout << letter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-14.cpp b/SourceCode/Chapter 02/Pr2-14.cpp new file mode 100755 index 0000000..cbc96d0 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-14.cpp @@ -0,0 +1,14 @@ +// This program uses character literals. +#include +using namespace std; + +int main() +{ + char letter; + + letter = 'A'; + cout << letter << '\n'; + letter = 'B'; + cout << letter << '\n'; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-15.cpp b/SourceCode/Chapter 02/Pr2-15.cpp new file mode 100755 index 0000000..68dd49c --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-15.cpp @@ -0,0 +1,13 @@ +// This program demonstrates the string class. +#include +#include // Required for the string class. +using namespace std; + +int main() +{ + string movieTitle; + + movieTitle = "Wheels of Fury"; + cout << "My favorite movie is " << movieTitle << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-16.cpp b/SourceCode/Chapter 02/Pr2-16.cpp new file mode 100755 index 0000000..5a9ebc5 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-16.cpp @@ -0,0 +1,15 @@ +// This program uses floating point data types. +#include +using namespace std; + +int main() +{ + float distance; + double mass; + + distance = 1.495979E11; + mass = 1.989E30; + cout << "The Sun is " << distance << " meters away.\n"; + cout << "The Sun\'s mass is " << mass << " kilograms.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-17.cpp b/SourceCode/Chapter 02/Pr2-17.cpp new file mode 100755 index 0000000..58d3f0e --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-17.cpp @@ -0,0 +1,14 @@ +// This program demonstrates boolean variables. +#include +using namespace std; + +int main() +{ + bool boolValue; + + boolValue = true; + cout << boolValue << endl; + boolValue = false; + cout << boolValue << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-18.cpp b/SourceCode/Chapter 02/Pr2-18.cpp new file mode 100755 index 0000000..3f8d7df --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-18.cpp @@ -0,0 +1,17 @@ +// This program determines the size of integers, long +// integers, and long doubles. +#include +using namespace std; + +int main() +{ + long double apple; + + cout << "The size of an integer is " << sizeof(int); + cout << " bytes.\n"; + cout << "The size of a long integer is " << sizeof(long); + cout << " bytes.\n"; + cout << "An apple can be eaten in " << sizeof(apple); + cout << " bytes!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-19.cpp b/SourceCode/Chapter 02/Pr2-19.cpp new file mode 100755 index 0000000..e45a747 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-19.cpp @@ -0,0 +1,11 @@ +// This program shows variable initialization. +#include +using namespace std; + +int main() +{ + int month = 2, days = 28; + + cout << "Month " << month << " has " << days << " days.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-2.cpp b/SourceCode/Chapter 02/Pr2-2.cpp new file mode 100755 index 0000000..2999954 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-2.cpp @@ -0,0 +1,9 @@ +// A simple C++ program +#include +using namespace std; + +int main() +{ + cout << "Programming is " << "great fun!"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-20.cpp b/SourceCode/Chapter 02/Pr2-20.cpp new file mode 100755 index 0000000..c75035f --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-20.cpp @@ -0,0 +1,11 @@ +// This program can't find its variable. +#include +using namespace std; + +int main() +{ + cout << value; // ERROR! value not defined yet! + + int value = 100; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-21.cpp b/SourceCode/Chapter 02/Pr2-21.cpp new file mode 100755 index 0000000..6362f93 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-21.cpp @@ -0,0 +1,27 @@ +// This program calculates hourly wages, including overtime. +#include +using namespace std; + +int main() +{ + double regularWages, // To hold regular wages + basePayRate = 18.25, // Base pay rate + regularHours = 40.0, // Hours worked less overtime + overtimeWages, // To hold overtime wages + overtimePayRate = 27.78, // Overtime pay rate + overtimeHours = 10, // Overtime hours worked + totalWages; // To hold total wages + + // Calculate the regular wages. + regularWages = basePayRate * regularHours; + + // Calculate the overtime wages. + overtimeWages = overtimePayRate * overtimeHours; + + // Calculate the total wages. + totalWages = regularWages + overtimeWages; + + // Display the total wages. + cout << "Wages for this week are $" << totalWages << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-22.cpp b/SourceCode/Chapter 02/Pr2-22.cpp new file mode 100755 index 0000000..46a6f64 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-22.cpp @@ -0,0 +1,29 @@ +// This program calculates the amount of pay that will +// be contributed to a retirement plan if 5%, 7%, or 10% +// of monthly pay is withheld. +#include +using namespace std; + +int main() +{ + // Variables to hold the monthly pay and the + // amount of contribution. + double monthlyPay = 6000.0, contribution; + + // Calculate and display a 5% contribution. + contribution = monthlyPay * 0.05; + cout << "5 percent is $" << contribution + << " per month.\n"; + + // Calculate and display a 7% contribution. + contribution = monthlyPay * 0.07; + cout << "7 percent is $" << contribution + << " per month.\n"; + + // Calculate and display a 10% contribution. + contribution = monthlyPay * 0.1; + cout << "10 percent is $" << contribution + << " per month.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-23.cpp b/SourceCode/Chapter 02/Pr2-23.cpp new file mode 100755 index 0000000..c6f8c8d --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-23.cpp @@ -0,0 +1,25 @@ +// This program calculates the sale price of an item +// that is regularly priced at $59.95, with a 20 percent +// discount subtracted. +#include +using namespace std; + +int main() +{ + // Variables to hold the regular price, the + // amount of a discount, and the sale price. + double regularPrice = 59.95, discount, salePrice; + + // Calculate the amount of a 20% discount. + discount = regularPrice * 0.20; + + // Calculate the sale price by subtracting the + // discount from the regular price. + salePrice = regularPrice - discount; + + // Display the results. + cout << "Regular price: $" << regularPrice << endl; + cout << "Discount amount: $" << discount << endl; + cout << "Sale price: $" << salePrice << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-24.cpp b/SourceCode/Chapter 02/Pr2-24.cpp new file mode 100755 index 0000000..40576e6 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-24.cpp @@ -0,0 +1,15 @@ +// This program extracts the rightmost digit of a number. +#include +using namespace std; + +int main() +{ + int number = 12345; + int rightMost = number % 10; + + cout << "The rightmost digit in " + << number << " is " + << rightMost << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-25.cpp b/SourceCode/Chapter 02/Pr2-25.cpp new file mode 100755 index 0000000..c61968b --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-25.cpp @@ -0,0 +1,24 @@ +// This program converts seconds to minutes and seconds. +#include +using namespace std; + +int main() +{ + // The total seconds is 125. + int totalSeconds = 125; + + // Variables for minutes and seconds + int minutes, seconds; + + // Get the number of minutes. + minutes = totalSeconds / 60; + + // Get the remaining seconds. + seconds = totalSeconds % 60; + + // Display the results. + cout << totalSeconds << " is equivalent to:\n"; + cout << "Minutes: " << minutes << endl; + cout << "Seconds: " << seconds << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-26.cpp b/SourceCode/Chapter 02/Pr2-26.cpp new file mode 100755 index 0000000..b8ed337 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-26.cpp @@ -0,0 +1,17 @@ +// PROGRAM: PAYROLL.CPP +// Written by Herbert Dorfmann +// This program calculates company payroll +// Last modification: 8/20/2008 +#include +using namespace std; + +int main() +{ + double payRate; // Holds the hourly pay rate + double hours; // Holds the hours worked + int employNumber; // Holds the employee number + + // The remainder of this program is left out. + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-27.cpp b/SourceCode/Chapter 02/Pr2-27.cpp new file mode 100755 index 0000000..f919e1a --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-27.cpp @@ -0,0 +1,20 @@ +/* + PROGRAM: PAYROLL.CPP + Written by Herbert Dorfmann + This program calculates company payroll + Last modification: 8/20/2008 +*/ + +#include +using namespace std; + +int main() +{ + double payRate; // Holds the hourly pay rate + double hours; // Holds the hours worked + int employNumber; // Holds the employee number + + /* The remainder of this program is left out. */ + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-28.cpp b/SourceCode/Chapter 02/Pr2-28.cpp new file mode 100755 index 0000000..cc82f54 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-28.cpp @@ -0,0 +1,20 @@ +// This program calculates the circumference of a circle. +#include +using namespace std; + +int main() +{ + // Constants + const double PI = 3.14159; + const double DIAMETER = 10.0; + + // Variable to hold the circumference + double circumference; + + // Calculate the circumference. + circumference = PI * DIAMETER; + + // Display the circumference. + cout << "The circumference is: " << circumference << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-29.cpp b/SourceCode/Chapter 02/Pr2-29.cpp new file mode 100755 index 0000000..437750e --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-29.cpp @@ -0,0 +1,5 @@ +#include +using namespace std;int main(){double shares=220.0; +double avgPrice=14.67;cout<<"There were "< +using namespace std; + +int main() +{ + cout << "Programming is "; + cout << "great fun!"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-30.cpp b/SourceCode/Chapter 02/Pr2-30.cpp new file mode 100755 index 0000000..606e061 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-30.cpp @@ -0,0 +1,13 @@ +// This example is much more readable than Program 2-29. +#include +using namespace std; + +int main() +{ + double shares = 220.0; + double avgPrice = 14.67; + + cout << "There were " << shares << " shares sold at $"; + cout << avgPrice << " per share.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-4.cpp b/SourceCode/Chapter 02/Pr2-4.cpp new file mode 100755 index 0000000..040cb65 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-4.cpp @@ -0,0 +1,13 @@ +// An unruly printing program +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers"; + cout << "during the month of June:"; + cout << "Computer games"; + cout << "Coffee"; + cout << "Aspirin"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-5.cpp b/SourceCode/Chapter 02/Pr2-5.cpp new file mode 100755 index 0000000..37b640b --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-5.cpp @@ -0,0 +1,13 @@ +// A well-adjusted printing program +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers" << endl; + cout << "during the month of June:" << endl; + cout << "Computer games" << endl; + cout << "Coffee" << endl; + cout << "Aspirin" << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-6.cpp b/SourceCode/Chapter 02/Pr2-6.cpp new file mode 100755 index 0000000..6eafa61 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-6.cpp @@ -0,0 +1,12 @@ +// Yet another well-adjusted printing program +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers\n"; + cout << "during the month of June:\n"; + cout << "Computer games\nCoffee"; + cout << "\nAspirin\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-7.cpp b/SourceCode/Chapter 02/Pr2-7.cpp new file mode 100755 index 0000000..33bd0ac --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-7.cpp @@ -0,0 +1,12 @@ +// This program has a variable. +#include +using namespace std; + +int main() +{ + int number; + + number = 5; + cout << "The value in number is " << number << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-8.cpp b/SourceCode/Chapter 02/Pr2-8.cpp new file mode 100755 index 0000000..f8c4763 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-8.cpp @@ -0,0 +1,12 @@ +// This program has a variable. +#include +using namespace std; + +int main() +{ + int number; + + number = 5; + cout << "The value in number is " << "number" << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-9.cpp b/SourceCode/Chapter 02/Pr2-9.cpp new file mode 100755 index 0000000..00724d8 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-9.cpp @@ -0,0 +1,12 @@ +// This program has literals and a variable. +#include +using namespace std; + +int main() +{ + int apples; + + apples = 20; + cout << "Today we sold " << apples << " bushels of apples.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-1.cpp b/SourceCode/Chapter 03/Pr3-1.cpp new file mode 100755 index 0000000..954e022 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-1.cpp @@ -0,0 +1,20 @@ +// This program asks the user to enter the length and width of +// a rectangle. It calculates the rectangle's area and displays +// the value on the screen. +#include +using namespace std; + +int main() +{ + int length, width, area; + + cout << "This program calculates the area of a "; + cout << "rectangle.\n"; + cout << "What is the length of the rectangle? "; + cin >> length; + cout << "What is the width of the rectangle? "; + cin >> width; + area = length * width; + cout << "The area of the rectangle is " << area << ".\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-10.cpp b/SourceCode/Chapter 03/Pr3-10.cpp new file mode 100755 index 0000000..9d3f281 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-10.cpp @@ -0,0 +1,17 @@ +// This program uses a type cast expression to print a character +// from a number. +#include +using namespace std; + +int main() +{ + int number = 65; + + // Display the value of the number variable. + cout << number << endl; + + // Display the value of number converted to + // the char data type. + cout << static_cast(number) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-11.cpp b/SourceCode/Chapter 03/Pr3-11.cpp new file mode 100755 index 0000000..802a63b --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-11.cpp @@ -0,0 +1,47 @@ +// This program tracks the inventory of three widget stores +// that opened at the same time. Each store started with the +// same number of widgets in inventory. By subtracting the +// number of widgets each store has sold from its inventory, +// the current inventory can be calculated. +#include +using namespace std; + +int main() +{ + int begInv, // Begining inventory for all stores + sold, // Number of widgets sold + store1, // Store 1's inventory + store2, // Store 2's inventory + store3; // Store 3's inventory + + // Get the beginning inventory for all the stores. + cout << "One week ago, 3 new widget stores opened\n"; + cout << "at the same time with the same beginning\n"; + cout << "inventory. What was the beginning inventory? "; + cin >> begInv; + + // Set each store's inventory. + store1 = store2 = store3 = begInv; + + // Get the number of widgets sold at store 1. + cout << "How many widgets has store 1 sold? "; + cin >> sold; + store1 -= sold; // Adjust store 1's inventory. + + // Get the number of widgets sold at store 2. + cout << "How many widgets has store 2 sold? "; + cin >> sold; + store2 -= sold; // Adjust store 2's inventory. + + // Get the number of widgets sold at store 3. + cout << "How many widgets has store 3 sold? "; + cin >> sold; + store3 -= sold; // Adjust store 3's inventory. + + // Display each store's current inventory. + cout << "\nThe current inventory of each store:\n"; + cout << "Store 1: " << store1 << endl; + cout << "Store 2: " << store2 << endl; + cout << "Store 3: " << store3 << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-12.cpp b/SourceCode/Chapter 03/Pr3-12.cpp new file mode 100755 index 0000000..e3ace42 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-12.cpp @@ -0,0 +1,20 @@ +// This program displays three rows of numbers. +#include +using namespace std; + +int main() +{ + int num1 = 2897, num2 = 5, num3 = 837, + num4 = 34, num5 = 7, num6 = 1623, + num7 = 390, num8 = 3456, num9 = 12; + + // Display the first row of numbers + cout << num1 << " " << num2 << " " << num3 << endl; + + // Display the second row of numbers + cout << num4 << " " << num5 << " " << num6 << endl; + + // Display the third row of numbers + cout << num7 << " " << num8 << " " << num9 << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-13.cpp b/SourceCode/Chapter 03/Pr3-13.cpp new file mode 100755 index 0000000..73be502 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-13.cpp @@ -0,0 +1,24 @@ +// This program displays three rows of numbers. +#include +#include // Required for setw +using namespace std; + +int main() +{ + int num1 = 2897, num2 = 5, num3 = 837, + num4 = 34, num5 = 7, num6 = 1623, + num7 = 390, num8 = 3456, num9 = 12; + + // Display the first row of numbers + cout << setw(6) << num1 << setw(6) + << num2 << setw(6) << num3 << endl; + + // Display the second row of numbers + cout << setw(6) << num4 << setw(6) + << num5 << setw(6) << num6 << endl; + + // Display the third row of numbers + cout << setw(6) << num7 << setw(6) + << num8 << setw(6) << num9 << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-14.cpp b/SourceCode/Chapter 03/Pr3-14.cpp new file mode 100755 index 0000000..c3eb9c0 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-14.cpp @@ -0,0 +1,18 @@ +// This program demonstrates the setw manipulator being +// used with values of various data types. +#include +#include +#include +using namespace std; + +int main() +{ + int intValue = 3928; + double doubleValue = 91.5; + string stringValue = "John J. Smith"; + + cout << "(" << setw(5) << intValue << ")" << endl; + cout << "(" << setw(8) << doubleValue << ")" << endl; + cout << "(" << setw(16) << stringValue << ")" << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-15.cpp b/SourceCode/Chapter 03/Pr3-15.cpp new file mode 100755 index 0000000..9aaaeea --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-15.cpp @@ -0,0 +1,19 @@ +// This program demonstrates how setprecision rounds a +// floating point value. +#include +#include +using namespace std; + +int main() +{ + double quotient, number1 = 132.364, number2 = 26.91; + + quotient = number1 / number2; + cout << quotient << endl; + cout << setprecision(5) << quotient << endl; + cout << setprecision(4) << quotient << endl; + cout << setprecision(3) << quotient << endl; + cout << setprecision(2) << quotient << endl; + cout << setprecision(1) << quotient << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-16.cpp b/SourceCode/Chapter 03/Pr3-16.cpp new file mode 100755 index 0000000..8129817 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-16.cpp @@ -0,0 +1,31 @@ +// This program asks for sales figures for 3 days. The total +// sales are calculated and displayed in a table. +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + // Get the sales for each day. + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + // Calculate the total sales. + total = day1 + day2 + day3; + + // Display the sales figures. + cout << "\nSales Figures\n"; + cout << "-------------\n"; + cout << setprecision(5); + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-17.cpp b/SourceCode/Chapter 03/Pr3-17.cpp new file mode 100755 index 0000000..01fefd2 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-17.cpp @@ -0,0 +1,31 @@ +// This program asks for sales figures for 3 days. The total +// sales are calculated and displayed in a table. +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + // Get the sales for each day. + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + // Calculate the total sales. + total = day1 + day2 + day3; + + // Display the sales figures. + cout << "\nSales Figures\n"; + cout << "-------------\n"; + cout << setprecision(2) << fixed; + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-18.cpp b/SourceCode/Chapter 03/Pr3-18.cpp new file mode 100755 index 0000000..8bb3007 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-18.cpp @@ -0,0 +1,20 @@ +// This program illustrates a problem that can occur if +// cin is used to read character data into a string object. +#include +#include +using namespace std; + +int main() +{ + string name; + string city; + + cout << "Please enter your name: "; + cin >> name; + cout << "Enter the city you live in: "; + cin >> city; + + cout << "Hello, " << name << endl; + cout << "You live in " << city << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-19.cpp b/SourceCode/Chapter 03/Pr3-19.cpp new file mode 100755 index 0000000..5c8853a --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-19.cpp @@ -0,0 +1,20 @@ +// This program demonstrates using the getline function +// to read character data into a string object. +#include +#include +using namespace std; + +int main() +{ + string name; + string city; + + cout << "Please enter your name: "; + getline(cin, name); + cout << "Enter the city you live in: "; + getline(cin, city); + + cout << "Hello, " << name << endl; + cout << "You live in " << city << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-2.cpp b/SourceCode/Chapter 03/Pr3-2.cpp new file mode 100755 index 0000000..725c3f6 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-2.cpp @@ -0,0 +1,19 @@ +// This program asks the user to enter the length and width of +// a rectangle. It calculates the rectangle's area and displays +// the value on the screen. +#include +using namespace std; + +int main() +{ + int length, width, area; + + cout << "This program calculates the area of a "; + cout << "rectangle.\n"; + cout << "Enter the length and width of the rectangle "; + cout << "separated by a space.\n"; + cin >> length >> width; + area = length * width; + cout << "The area of the rectangle is " << area << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-20.cpp b/SourceCode/Chapter 03/Pr3-20.cpp new file mode 100755 index 0000000..d87daf0 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-20.cpp @@ -0,0 +1,13 @@ +// This program reads a single character into a char variable. +#include +using namespace std; + +int main() +{ + char ch; + + cout << "Type a character and press Enter: "; + cin >> ch; + cout << "You entered " << ch << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-21.cpp b/SourceCode/Chapter 03/Pr3-21.cpp new file mode 100755 index 0000000..840cd66 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-21.cpp @@ -0,0 +1,18 @@ +// This program demonstrates three ways +// to use cin.get() to pause a program +#include +using namespace std; + +int main() +{ + char ch; + + cout << "This program has paused. Press Enter to continue."; + cin.get(ch); + cout << "It has paused a second time. Please press Enter again."; + ch = cin.get(); + cout << "It has paused a third time. Please press Enter again."; + cin.get(); + cout << "Thank you!"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-22.cpp b/SourceCode/Chapter 03/Pr3-22.cpp new file mode 100755 index 0000000..88d00f2 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-22.cpp @@ -0,0 +1,17 @@ +// This program demonstrates a problem that occurs +// when you mix cin >> with cin.get(). +#include +using namespace std; + +int main() +{ + char ch; // Define a character variable + int number; // Define an integer variable + + cout << "Enter a number: "; + cin >> number; // Read an integer + cout << "Enter a character: "; + ch = cin.get(); // Read a character + cout << "Thank You!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-23.cpp b/SourceCode/Chapter 03/Pr3-23.cpp new file mode 100755 index 0000000..b9fce11 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-23.cpp @@ -0,0 +1,18 @@ +// This program successfully uses both +// cin >> and cin.get() for keyboard input. +#include +using namespace std; + +int main() +{ + char ch; + int number; + + cout << "Enter a number: "; + cin >> number; + cin.ignore(); // Skip the newline character + cout << "Enter a character: "; + ch = cin.get(); + cout << "Thank You!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-24.cpp b/SourceCode/Chapter 03/Pr3-24.cpp new file mode 100755 index 0000000..5bae12c --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-24.cpp @@ -0,0 +1,21 @@ +// This program asks for the lengths of the two sides of a +// right triangle. The length of the hypotenuse is then +// calculated and displayed. +#include +#include // For setprecision +#include // For the sqrt and pow functions +using namespace std; + +int main() +{ + double a, b, c; + + cout << "Enter the length of side a: "; + cin >> a; + cout << "Enter the length of side b: "; + cin >> b; + c = sqrt(pow(a, 2.0) + pow(b, 2.0)); + cout << "The length of the hypotenuse is "; + cout << setprecision(2) << c << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-25.cpp b/SourceCode/Chapter 03/Pr3-25.cpp new file mode 100755 index 0000000..45649b5 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-25.cpp @@ -0,0 +1,20 @@ +// This program demonstrates random numbers. +#include +#include // rand and srand +#include // For the time function +using namespace std; + +int main() +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + // Display three random numbers. + cout << rand() << endl; + cout << rand() << endl; + cout << rand() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-26.cpp b/SourceCode/Chapter 03/Pr3-26.cpp new file mode 100755 index 0000000..97125e5 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-26.cpp @@ -0,0 +1,29 @@ +// This program simulates rolling dice. +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +int main() +{ + // Constants + const int MIN_VALUE = 1; // Minimum die value + const int MAX_VALUE = 6; // Maximum die value + + // Variables + int die1; // To hold the value of die #1 + int die2; // To hold the value of die #2 + + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + cout << "Rolling the dice...\n"; + die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << die1 << endl; + cout << die2 << endl; + return 0; +} diff --git a/SourceCode/Chapter 03/Pr3-27.cpp b/SourceCode/Chapter 03/Pr3-27.cpp new file mode 100755 index 0000000..09209f2 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-27.cpp @@ -0,0 +1,19 @@ +// This program asks for three numbers, then +// displays the average of the numbers. +#include +using namespace std; + +int main() +{ + double num1, num2, num3, avg; + + cout << "Enter the first number: "; + cin >> num1; + cout << "Enter the second number: "; + cin >> num2; + cout << "Enter the third number: "; + cin >> num3; + avg = (num1 + num2 + num3) / 3; + cout << "The average is " << avg << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-28.cpp b/SourceCode/Chapter 03/Pr3-28.cpp new file mode 100755 index 0000000..b48623a --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-28.cpp @@ -0,0 +1,50 @@ +// This program is used by General Crates, Inc. to calculate +// the volume, cost, customer charge, and profit of a crate +// of any size. It calculates this data from user input, which +// consists of the dimensions of the crate. +#include +#include +using namespace std; + +int main() +{ + // Constants for cost and amount charged + const double COST_PER_CUBIC_FOOT = 0.23; + const double CHARGE_PER_CUBIC_FOOT = 0.5; + + // Variables + double length, // The crate's length + width, // The crate's width + height, // The crate's height + volume, // The volume of the crate + cost, // The cost to build the crate + charge, // The customer charge for the crate + profit; // The profit made on the crate + + // Set the desired output formatting for numbers. + cout << setprecision(2) << fixed << showpoint; + + // Prompt the user for the crate's length, width, and height + cout << "Enter the dimensions of the crate (in feet):\n"; + cout << "Length: "; + cin >> length; + cout << "Width: "; + cin >> width; + cout << "Height: "; + cin >> height; + + // Calculate the crate's volume, the cost to produce it, + // the charge to the customer, and the profit. + volume = length * width * height; + cost = volume * COST_PER_CUBIC_FOOT; + charge = volume * CHARGE_PER_CUBIC_FOOT; + profit = charge - cost; + + // Display the calculated data. + cout << "The volume of the crate is "; + cout << volume << " cubic feet.\n"; + cout << "Cost to build: $" << cost << endl; + cout << "Charge to customer: $" << charge << endl; + cout << "Profit: $" << profit << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-3.cpp b/SourceCode/Chapter 03/Pr3-3.cpp new file mode 100755 index 0000000..0aaa41d --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-3.cpp @@ -0,0 +1,18 @@ +// This program demonstrates how cin can read multiple values +// of different data types. +#include +using namespace std; + +int main() +{ + int whole; + double fractional; + char letter; + + cout << "Enter an integer, a double, and a character: "; + cin >> whole >> fractional >> letter; + cout << "Whole: " << whole << endl; + cout << "Fractional: " << fractional << endl; + cout << "Letter: " << letter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-4.cpp b/SourceCode/Chapter 03/Pr3-4.cpp new file mode 100755 index 0000000..61ee984 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-4.cpp @@ -0,0 +1,21 @@ +// This program asks the user to enter the numerator +// and denominator of a fraction and it displays the +// decimal value. + +#include +using namespace std; + +int main() +{ + double numerator, denominator; + + cout << "This program shows the decimal value of "; + cout << "a fraction.\n"; + cout << "Enter the numerator: "; + cin >> numerator; + cout << "Enter the denominator: "; + cin >> denominator; + cout << "The decimal value is "; + cout << (numerator / denominator) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-5.cpp b/SourceCode/Chapter 03/Pr3-5.cpp new file mode 100755 index 0000000..1c1fea9 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-5.cpp @@ -0,0 +1,19 @@ +// This program calculates the area of a circle. +// The formula for the area of a circle is Pi times +// the radius squared. Pi is 3.14159. +#include +#include // needed for pow function +using namespace std; + +int main() +{ + const double PI = 3.14159; + double area, radius; + + cout << "This program calculates the area of a circle.\n"; + cout << "What is the radius of the circle? "; + cin >> radius; + area = PI * pow(radius, 2.0); + cout << "The area is " << area << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-6.cpp b/SourceCode/Chapter 03/Pr3-6.cpp new file mode 100755 index 0000000..0843f2c --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-6.cpp @@ -0,0 +1,26 @@ +// This program calculates the average +// of three test scores. +#include +#include +using namespace std; + +int main() +{ + double test1, test2, test3; // To hold the scores + double average; // To hold the average + + // Get the three test scores. + cout << "Enter the first test score: "; + cin >> test1; + cout << "Enter the second test score: "; + cin >> test2; + cout << "Enter the third test score: "; + cin >> test3; + + // Calculate the average of the scores. + average = (test1 + test2 + test3) / 3.0; + + // Display the average. + cout << "The average score is: " << average << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-7.cpp b/SourceCode/Chapter 03/Pr3-7.cpp new file mode 100755 index 0000000..29447a4 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-7.cpp @@ -0,0 +1,21 @@ +// This program demonstrates integer overflow and underflow. +#include +using namespace std; + +int main() +{ + // testVar is initialized with the maximum value for a short. + short testVar = 32767; + + // Display testVar. + cout << testVar << endl; + + // Add 1 to testVar to make it overflow. + testVar = testVar + 1; + cout << testVar << endl; + + // Subtract 1 from testVar to make it underflow. + testVar = testVar - 1; + cout << testVar << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-8.cpp b/SourceCode/Chapter 03/Pr3-8.cpp new file mode 100755 index 0000000..521e691 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-8.cpp @@ -0,0 +1,15 @@ +// This program can be used to see how your system handles +// floating point overflow and underflow. +#include +using namespace std; + +int main() +{ + float test; + + test = 2.0e38 * 1000; // Should overflow test. + cout << test << endl; + test = 2.0e-38 / 2.0e38; // Should underflow test. + cout << test << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-9.cpp b/SourceCode/Chapter 03/Pr3-9.cpp new file mode 100755 index 0000000..bc287fb --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-9.cpp @@ -0,0 +1,18 @@ +// This program uses a type cast to avoid integer division. +#include +using namespace std; + +int main() +{ + int books; // Number of books to read + int months; // Number of months spent reading + double perMonth; // Average number of books per month + + cout << "How many books do you plan to read? "; + cin >> books; + cout << "How many months will it take you to read them? "; + cin >> months; + perMonth = static_cast(books) / months; + cout << "That is " << perMonth << " books per month.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-1.cpp b/SourceCode/Chapter 04/Pr4-1.cpp new file mode 100755 index 0000000..62862ad --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-1.cpp @@ -0,0 +1,16 @@ +// This program displays the values of true and false states. +#include +using namespace std; + +int main() +{ + bool trueValue, falseValue; + int x = 5, y = 10; + + trueValue = x < y; + falseValue = y == x; + + cout << "True is " << trueValue << endl; + cout << "False is " << falseValue << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-10.cpp b/SourceCode/Chapter 04/Pr4-10.cpp new file mode 100755 index 0000000..36dc67d --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-10.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the nested if statement. +#include +using namespace std; + +int main() +{ + char employed, // Currently employed, Y or N + recentGrad; // Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or "; + cout << "N for No.\n"; + cout << "Are you employed? "; + cin >> employed; + cout << "Have you graduated from college "; + cout << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qualifications. + if (employed == 'Y') + { + if (recentGrad == 'Y') //Nested if + { + cout << "You qualify for the special "; + cout << "interest rate.\n"; + } + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-11.cpp b/SourceCode/Chapter 04/Pr4-11.cpp new file mode 100755 index 0000000..f312f4e --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-11.cpp @@ -0,0 +1,40 @@ +// This program demonstrates the nested if statement. +#include +using namespace std; + +int main() +{ + char employed, // Currently employed, Y or N + recentGrad; // Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or "; + cout << "N for No.\n"; + cout << "Are you employed? "; + cin >> employed; + cout << "Have you graduated from college "; + cout << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qualifications. + if (employed == 'Y') + { + if (recentGrad == 'Y') // Nested if + { + cout << "You qualify for the special "; + cout << "interest rate.\n"; + } + else // Not a recent grad, but employed + { + cout << "You must have graduated from "; + cout << "college in the past two\n"; + cout << "years to qualify.\n"; + } + } + else // Not employed + { + cout << "You must be employed to qualify.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-12.cpp b/SourceCode/Chapter 04/Pr4-12.cpp new file mode 100755 index 0000000..c831120 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-12.cpp @@ -0,0 +1,53 @@ +// This program uses nested if/else statements to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n"; + cout << "tell you the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + { + cout << "Your grade is A.\n"; + } + else + { + if (testScore >= B_SCORE) + { + cout << "Your grade is B.\n"; + } + else + { + if (testScore >= C_SCORE) + { + cout << "Your grade is C.\n"; + } + else + { + if (testScore >= D_SCORE) + { + cout << "Your grade is D.\n"; + } + else + { + cout << "Your grade is F.\n"; + } + } + } + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-13.cpp b/SourceCode/Chapter 04/Pr4-13.cpp new file mode 100755 index 0000000..a2d282f --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-13.cpp @@ -0,0 +1,34 @@ +// This program uses an if/else if statement to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell you the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + cout << "Your grade is A.\n"; + else if (testScore >= B_SCORE) + cout << "Your grade is B.\n"; + else if (testScore >= C_SCORE) + cout << "Your grade is C.\n"; + else if (testScore >= D_SCORE) + cout << "Your grade is D.\n"; + else + cout << "Your grade is F.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-14.cpp b/SourceCode/Chapter 04/Pr4-14.cpp new file mode 100755 index 0000000..acc40db --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-14.cpp @@ -0,0 +1,36 @@ +// This program uses an if/else if statement to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell you the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + cout << "Your grade is A.\n"; + else if (testScore >= B_SCORE) + cout << "Your grade is B.\n"; + else if (testScore >= C_SCORE) + cout << "Your grade is C.\n"; + else if (testScore >= D_SCORE) + cout << "Your grade is D.\n"; + else if (testScore >= 0) + cout << "Your grade is F.\n"; + else + cout << "Invalid test score.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-15.cpp b/SourceCode/Chapter 04/Pr4-15.cpp new file mode 100755 index 0000000..d3019b9 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-15.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the && logical operator. +#include +using namespace std; + +int main() +{ + char employed, // Currently employed, Y or N + recentGrad; // Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or N for No.\n"; + + cout << "Are you employed? "; + cin >> employed; + + cout << "Have you graduated from college " + << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qualifications. + if (employed == 'Y' && recentGrad == 'Y') + { + cout << "You qualify for the special " + << "interest rate.\n"; + } + else + { + cout << "You must be employed and have\n" + << "graduated from college in the\n" + << "past two years to qualify.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-16.cpp b/SourceCode/Chapter 04/Pr4-16.cpp new file mode 100755 index 0000000..029ec6b --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-16.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the logical || operator. +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + double income; // Annual income + int years; // Years at the current job + + // Get the annual income + cout << "What is your annual income? "; + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + cin >> years; + + // Determine the user's loan qualifications. + if (income >= MIN_INCOME || years > MIN_YEARS) + cout << "You qualify.\n"; + else + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << " years.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-17.cpp b/SourceCode/Chapter 04/Pr4-17.cpp new file mode 100755 index 0000000..7497012 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-17.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the logical ! operator. +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + double income; // Annual income + int years; // Years at the current job + + // Get the annual income + cout << "What is your annual income? "; + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + cin >> years; + + // Determine the user's loan qualifications. + if (!(income >= MIN_INCOME || years > MIN_YEARS)) + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << "years.\n"; + } + else + cout << "You qualify.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-18.cpp b/SourceCode/Chapter 04/Pr4-18.cpp new file mode 100755 index 0000000..aa9271c --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-18.cpp @@ -0,0 +1,69 @@ +// This program displays a menu and asks the user to make a +// selection. An if/else if statement determines which item +// the user has chosen. +#include +#include +using namespace std; + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold the number of months + double charges; // To hold the monthly charges + + // Constants for membership rates + const double ADULT = 40.0, + SENIOR = 30.0, + CHILD = 20.0; + + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Display the menu and get a choice. + cout << "\t\tHealth Club Membership Menu\n\n"; + cout << "1. Standard Adult Membership\n"; + cout << "2. Child Membership\n"; + cout << "3. Senior Citizen Membership\n"; + cout << "4. Quit the Program\n\n"; + cout << "Enter your choice: "; + cin >> choice; + + // Set the numeric ouput formatting. + cout << fixed << showpoint << setprecision(2); + + // Respond to the user's menu selection. + if (choice == ADULT_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * ADULT; + cout << "The total charges are $" << charges << endl; + } + else if (choice == CHILD_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * CHILD; + cout << "The total charges are $" << charges << endl; + } + else if (choice == SENIOR_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * SENIOR; + cout << "The total charges are $" << charges << endl; + } + else if (choice == QUIT_CHOICE) + { + cout << "Program ending.\n"; + } + else + { + cout << "The valid choices are 1 through 4. Run the\n"; + cout << "program again and select one of those.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-19.cpp b/SourceCode/Chapter 04/Pr4-19.cpp new file mode 100755 index 0000000..33e21b7 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-19.cpp @@ -0,0 +1,47 @@ +// This test scoring program does not accept test scores +// that are less than 0 or greater than 100. +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60, + MIN_SCORE = 0, // Minimum valid score + MAX_SCORE = 100; // Maximum valid score + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell you the letter grade you earned: "; + cin >> testScore; + + // Validate the input and determine the grade. + if (testScore >= MIN_SCORE && testScore <= MAX_SCORE) + { + // Determine the letter grade. + if (testScore >= A_SCORE) + cout << "Your grade is A.\n"; + else if (testScore >= B_SCORE) + cout << "Your grade is B.\n"; + else if (testScore >= C_SCORE) + cout << "Your grade is C.\n"; + else if (testScore >= D_SCORE) + cout << "Your grade is D.\n"; + else + cout << "Your grade is F.\n"; + } + else + { + // An invalid score was entered. + cout << "That is an invalid score. Run the program\n" + << "again and enter a value in the range of\n" + << MIN_SCORE << " through " << MAX_SCORE << ".\n"; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-2.cpp b/SourceCode/Chapter 04/Pr4-2.cpp new file mode 100755 index 0000000..470c80b --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-2.cpp @@ -0,0 +1,25 @@ +// This program averages three test scores +#include +#include +using namespace std; + +int main() +{ + const int HIGH_SCORE = 95; // A high score is 95 or greater + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average score + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // If the average is a high score, congratulate the user. + if (average > HIGH_SCORE) + cout << "Congratulations! That's a high score!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-20.cpp b/SourceCode/Chapter 04/Pr4-20.cpp new file mode 100755 index 0000000..3f3b13a --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-20.cpp @@ -0,0 +1,25 @@ +// This program demonstrates how characters can be +// compared with the relational operators. +#include +using namespace std; + +int main() +{ + char ch; + + // Get a character from the user. + cout << "Enter a digit or a letter: "; + ch = cin.get(); + + // Determine what the user entered. + if (ch >= '0' && ch <= '9') + cout << "You entered a digit.\n"; + else if (ch >= 'A' && ch <= 'Z') + cout << "You entered an uppercase letter.\n"; + else if (ch >= 'a' && ch <= 'z') + cout << "You entered a lowercase letter.\n"; + else + cout << "That is not a digit or a letter.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-21.cpp b/SourceCode/Chapter 04/Pr4-21.cpp new file mode 100755 index 0000000..f1d2fc5 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-21.cpp @@ -0,0 +1,34 @@ +// This program uses relational operators to compare a string +// entered by the user with valid stereo part numbers. +#include +#include +#include +using namespace std; + +int main() +{ + const double PRICE_A = 249.0, + PRICE_B = 299.0; + + string partNum; // Holds a stereo part number + + // Display available parts and get the user's selection + cout << "The stereo part numbers are:\n" + << "Boom Box : part number S-29A \n" + << "Shelf Model: part number S-29B \n" + << "Enter the part number of the stereo you\n" + << "wish to purchase: "; + cin >> partNum; + + // Set the numeric output formatting + cout << fixed << showpoint << setprecision(2); + + // Determine and display the correct price + if (partNum == "S-29A") + cout << "The price is $" << PRICE_A << endl; + else if (partNum == "S-29B") + cout << "The price is $" << PRICE_B << endl; + else + cout << partNum << " is not a valid part number.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-22.cpp b/SourceCode/Chapter 04/Pr4-22.cpp new file mode 100755 index 0000000..42d7980 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-22.cpp @@ -0,0 +1,27 @@ +// This program calculates a consultant's charges at $50 +// per hour, for a minimum of 5 hours. The ?: operator +// adjusts hours to 5 if less than 5 hours were worked. +#include +#include +using namespace std; + +int main() +{ + const double PAY_RATE = 50.0; // Hourly pay rate + const int MIN_HOURS = 5; // Minimum billable hours + double hours, // Hours worked + charges; // Total charges + + // Get the hours worked. + cout << "How many hours were worked? "; + cin >> hours; + + // Determine the hours to charge for. + hours = hours < MIN_HOURS ? MIN_HOURS : hours; + + // Calculate and display the charges. + charges = PAY_RATE * hours; + cout << fixed << showpoint << setprecision(2) + << "The charges are $" << charges << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-23.cpp b/SourceCode/Chapter 04/Pr4-23.cpp new file mode 100755 index 0000000..b380437 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-23.cpp @@ -0,0 +1,23 @@ +// The switch statement in this program tells the user something +// he or she already knows: what they just entered! +#include +using namespace std; + +int main() +{ + char choice; + + cout << "Enter A, B, or C: "; + cin >> choice; + switch (choice) + { + case 'A': cout << "You entered A.\n"; + break; + case 'B': cout << "You entered B.\n"; + break; + case 'C': cout << "You entered C.\n"; + break; + default: cout << "You did not enter A, B, or C!\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-24.cpp b/SourceCode/Chapter 04/Pr4-24.cpp new file mode 100755 index 0000000..8150e8a --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-24.cpp @@ -0,0 +1,22 @@ +// The switch statement in this program tells the user something +// he or she already knows: what they just entered! +#include +using namespace std; + +int main() +{ + char choice; + + cout << "Enter A, B, or C: "; + cin >> choice; + // The following switch is + // missing its break statements! + switch (choice) + { + case 'A': cout << "You entered A.\n"; + case 'B': cout << "You entered B.\n"; + case 'C': cout << "You entered C.\n"; + default: cout << "You did not enter A, B, or C!\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-25.cpp b/SourceCode/Chapter 04/Pr4-25.cpp new file mode 100755 index 0000000..5c8d5ea --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-25.cpp @@ -0,0 +1,27 @@ +// This program is carefully constructed to use the "fallthrough" +// feature of the switch statement. +#include +using namespace std; + +int main() +{ + int modelNum; // Model number + + // Get a model number from the user. + cout << "Our TVs come in three models:\n"; + cout << "The 100, 200, and 300. Which do you want? "; + cin >> modelNum; + + // Display the model's features. + cout << "That model has the following features:\n"; + switch (modelNum) + { + case 300: cout << "\tPicture-in-a-picture.\n"; + case 200: cout << "\tStereo sound.\n"; + case 100: cout << "\tRemote control.\n"; + break; + default: cout << "You can only choose the 100,"; + cout << "200, or 300.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-26.cpp b/SourceCode/Chapter 04/Pr4-26.cpp new file mode 100755 index 0000000..ee15e63 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-26.cpp @@ -0,0 +1,31 @@ +// The switch statement in this program uses the "fall through" +// feature to catch both uppercase and lowercase letters entered +// by the user. +#include +using namespace std; + +int main() +{ + char feedGrade; + + // Get the desired grade of feed. + cout << "Our pet food is available in three grades:\n"; + cout << "A, B, and C. Which do you want pricing for? "; + cin >> feedGrade; + + // Display the price. + switch(feedGrade) + { + case 'a': + case 'A': cout << "30 cents per pound.\n"; + break; + case 'b': + case 'B': cout << "20 cents per pound.\n"; + break; + case 'c': + case 'C': cout << "15 cents per pound.\n"; + break; + default: cout << "That is an invalid choice.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-27.cpp b/SourceCode/Chapter 04/Pr4-27.cpp new file mode 100755 index 0000000..edcc0d9 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-27.cpp @@ -0,0 +1,70 @@ +// This program uses a switch statement to determine +// the item selected from a menu. +#include +#include +using namespace std; + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold the number of months + double charges; // To hold the monthly charges + + // Constants for membership rates + const double ADULT = 40.0, + SENIOR = 30.0, + CHILD = 20.0; + + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Display the menu and get a choice. + cout << "\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; + cin >> choice; + + // Set the numeric ouput formatting. + cout << fixed << showpoint << setprecision(2); + + // Respond to the user's menu selection. + switch (choice) + { + case ADULT_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * ADULT; + cout << "The total charges are $" << charges << endl; + break; + + case CHILD_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * CHILD; + cout << "The total charges are $" << charges << endl; + break; + + case SENIOR_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * SENIOR; + cout << "The total charges are $" << charges << endl; + break; + + case QUIT_CHOICE: + cout << "Program ending.\n"; + break; + + default: + cout << "The valid choices are 1 through 4. Run the\n" + << "program again and select one of those.\n"; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-28.cpp b/SourceCode/Chapter 04/Pr4-28.cpp new file mode 100755 index 0000000..3edc77d --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-28.cpp @@ -0,0 +1,33 @@ +// This program demonstrates late variable definition +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + // Get the annual income. + cout << "What is your annual income? "; + double income; // Variable definition + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + int years; // Variable definition + cin >> years; + + // Determine the user's loan qualifications. + if (income >= MIN_INCOME || years > MIN_YEARS) + cout << "You qualify.\n"; + else + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << " years.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-29.cpp b/SourceCode/Chapter 04/Pr4-29.cpp new file mode 100755 index 0000000..5289690 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-29.cpp @@ -0,0 +1,39 @@ +// This program demonstrates a variable defined in an inner block. +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + // Get the annual income. + cout << "What is your annual income? "; + double income; // Variable definition + cin >> income; + + if (income >= MIN_INCOME) + { + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + int years; // Variable definition + cin >> years; + + if (years > MIN_YEARS) + cout << "You qualify.\n"; + else + { + cout << "You must have been employed for\n" + << "more than " << MIN_YEARS + << " years to qualify.\n"; + } + } + else + { + cout << "You must earn at least $" << MIN_INCOME + << " to qualify.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-3.cpp b/SourceCode/Chapter 04/Pr4-3.cpp new file mode 100755 index 0000000..e835d6a --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-3.cpp @@ -0,0 +1,14 @@ +// This program demonstrates how a misplaced semicolon +// prematurely terminates an if statement. +#include +using namespace std; + +int main() +{ + int x = 0, y = 10; + + cout << "x is " << x << " and y is " << y << endl; + if (x > y); // Error! Misplaced semicolon + cout << "x is greater than y\n"; //This is always executed. + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-30.cpp b/SourceCode/Chapter 04/Pr4-30.cpp new file mode 100755 index 0000000..a20392f --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-30.cpp @@ -0,0 +1,22 @@ +// This program uses two variables with the name number. +#include +using namespace std; + +int main() +{ + // Define a variable named number. + int number; + + cout << "Enter a number greater than 0: "; + cin >> number; + if (number > 0) + { + int number; // Another variable named number. + cout << "Now enter another number: "; + cin >> number; + cout << "The second number you entered was " + << number << endl; + } + cout << "Your first number was " << number << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-4.cpp b/SourceCode/Chapter 04/Pr4-4.cpp new file mode 100755 index 0000000..07001e9 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-4.cpp @@ -0,0 +1,18 @@ +// This program demonstrates how floating-point +// round-off errors can make equality operations unreliable. +#include +using namespace std; + +int main() +{ + double a = 1.5; // a is 1.5. + double b = 1.5; // b is 1.5. + + a += 0.0000000000000001; // Add a little to a. + if (a == b) + cout << "Both a and b are the same.\n"; + else + cout << "a and b are not the same.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-5.cpp b/SourceCode/Chapter 04/Pr4-5.cpp new file mode 100755 index 0000000..19f250d --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-5.cpp @@ -0,0 +1,26 @@ +// This program averages 3 test scores. The if statement +// uses the = operator, but the == operator was intended. +#include +#include +using namespace std; + +int main() +{ + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average score + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // Our intention is to congratulate the user + // for having a perfect score. But, this doesn't work. + if (average = 100) // WRONG! This is an assignment! + cout << "Congratulations! That's a perfect score!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-6.cpp b/SourceCode/Chapter 04/Pr4-6.cpp new file mode 100755 index 0000000..5fd279b --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-6.cpp @@ -0,0 +1,31 @@ +// This program averages 3 test scores. +// It demonstrates an if statement executing +// a block of statements. +#include +#include +using namespace std; + +int main() +{ + const int HIGH_SCORE = 95; // A high score is 95 or greater + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average score + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // If the average is high, congratulate the user. + if (average > HIGH_SCORE) + { + cout << "Congratulations!\n"; + cout << "That's a high score.\n"; + cout << "You deserve a pat on the back!\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-7.cpp b/SourceCode/Chapter 04/Pr4-7.cpp new file mode 100755 index 0000000..6ba37a6 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-7.cpp @@ -0,0 +1,27 @@ +// This program averages 3 test scores. The braces +// were inadvertently left out of the if statement. +#include +#include +using namespace std; + +int main() +{ + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average score + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // ERROR! This if statement is missing its braces! + if (average > 95) + cout << "Congratulations!\n"; + cout << "That's a high score.\n"; + cout << "You deserve a pat on the back!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-8.cpp b/SourceCode/Chapter 04/Pr4-8.cpp new file mode 100755 index 0000000..e36dda3 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-8.cpp @@ -0,0 +1,19 @@ +// This program uses the modulus operator to determine +// if a number is odd or even. If the number is evenly divisible +// by 2, it is an even number. A remainder indicates it is odd. +#include +using namespace std; + +int main() +{ + int number; + + cout << "Enter an integer and I will tell you if it\n"; + cout << "is odd or even. "; + cin >> number; + if (number % 2 == 0) + cout << number << " is even.\n"; + else + cout << number << " is odd.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-9.cpp b/SourceCode/Chapter 04/Pr4-9.cpp new file mode 100755 index 0000000..048d9ce --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-9.cpp @@ -0,0 +1,35 @@ +// This program asks the user for two numbers, num1 and num2. +// num1 is divided by num2 and the result is displayed. +// Before the division operation, however, num2 is tested +// for the value 0. If it contains 0, the division does not +// take place. +#include +using namespace std; + +int main() +{ + double num1, num2, quotient; + + // Get the first number. + cout << "Enter a number: "; + cin >> num1; + + // Get the second number. + cout << "Enter another number: "; + cin >> num2; + + // If num2 is not zero, perform the division. + if (num2 == 0) + { + cout << "Division by zero is not possible.\n"; + cout << "Please run the program again and enter\n"; + cout << "a number other than zero.\n"; + } + else + { + quotient = num1 / num2; + cout << "The quotient of " << num1 << " divided by "; + cout<< num2 << " is " << quotient << ".\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Friends.txt b/SourceCode/Chapter 05/Friends.txt new file mode 100755 index 0000000..fbd56b8 --- /dev/null +++ b/SourceCode/Chapter 05/Friends.txt @@ -0,0 +1,3 @@ +Joe +Chris +Geri diff --git a/SourceCode/Chapter 05/ListOfNumbers.txt b/SourceCode/Chapter 05/ListOfNumbers.txt new file mode 100755 index 0000000..c910440 --- /dev/null +++ b/SourceCode/Chapter 05/ListOfNumbers.txt @@ -0,0 +1,7 @@ +100 +200 +300 +400 +500 +600 +700 \ No newline at end of file diff --git a/SourceCode/Chapter 05/Numbers.txt b/SourceCode/Chapter 05/Numbers.txt new file mode 100755 index 0000000..e8d05cd --- /dev/null +++ b/SourceCode/Chapter 05/Numbers.txt @@ -0,0 +1,3 @@ +100 +200 +300 diff --git a/SourceCode/Chapter 05/NumericData.txt b/SourceCode/Chapter 05/NumericData.txt new file mode 100755 index 0000000..17b1d2b --- /dev/null +++ b/SourceCode/Chapter 05/NumericData.txt @@ -0,0 +1,3 @@ +10 +20 +30 \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-1.cpp b/SourceCode/Chapter 05/Pr5-1.cpp new file mode 100755 index 0000000..6430715 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-1.cpp @@ -0,0 +1,32 @@ +// This program demonstrates the ++ and -- operators. +#include +using namespace std; + +int main() +{ + int num = 4; // num starts out with 4. + + // Display the value in num. + cout << "The variable num is " << num << endl; + cout << "I will now increment num.\n\n"; + + // Use postfix ++ to increment num. + num++; + cout << "Now the variable num is " << num << endl; + cout << "I will increment num again.\n\n"; + + // Use prefix ++ to increment num. + ++num; + cout << "Now the variable num is " << num << endl; + cout << "I will now decrement num.\n\n"; + + // Use postfix -- to decrement num. + num--; + cout << "Now the variable num is " << num << endl; + cout << "I will decrement num again.\n\n"; + + // Use prefix -- to increment num. + --num; + cout << "Now the variable num is " << num << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-10.cpp b/SourceCode/Chapter 05/Pr5-10.cpp new file mode 100755 index 0000000..b5d75ee --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-10.cpp @@ -0,0 +1,26 @@ +// This program demonstrates a user controlled for loop. +#include +using namespace std; + +int main() +{ + int minNumber, // Starting number to square + maxNumber; // Maximum number to square + + // Get the minimum and maximum values to display. + cout << "I will display a table of numbers and " + << "their squares.\n" + << "Enter the starting number: "; + cin >> minNumber; + cout << "Enter the ending number: "; + cin >> maxNumber; + + // Display the table. + cout << "Number Number Squared\n" + << "-------------------------\n"; + + for (int num = minNumber; num <= maxNumber; num++) + cout << num << "\t\t" << (num * num) << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-11.cpp b/SourceCode/Chapter 05/Pr5-11.cpp new file mode 100755 index 0000000..63d030b --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-11.cpp @@ -0,0 +1,39 @@ +// This program converts the speeds 60 kph through +// 130 kph (in 10 kph increments) to mph. +#include +#include +using namespace std; + +int main() +{ + // Constants for the speeds + const int START_KPH = 60, // Starting speed + END_KPH = 130, // Ending speed + INCREMENT = 10; // Speed increment + + // Constant for the conversion factor + const double CONVERSION_FACTOR = 0.6214; + + // Variables + int kph; // To hold speeds in kph + double mph; // To hold speeds in mph + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Display the table headings. + cout << "KPH\tMPH\n"; + cout << "---------------\n"; + + // Display the speeds. + for (kph = START_KPH; kph <= END_KPH; kph += INCREMENT) + { + // Calculate mph + mph = kph * CONVERSION_FACTOR; + + // Display the speeds in kph and mph. + cout << kph << "\t" << mph << endl; + + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-12.cpp b/SourceCode/Chapter 05/Pr5-12.cpp new file mode 100755 index 0000000..9a493f5 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-12.cpp @@ -0,0 +1,29 @@ +// This program takes daily sales figures over a period of time +// and calculates their total. +#include +#include +using namespace std; + +int main() +{ + int days; // Number of days + double total = 0.0; // Accumulator, initialized with 0 + + // Get the number of days. + cout << "For how many days do you have sales figures? "; + cin >> days; + + // Get the sales for each day and accumulate a total. + for (int count = 1; count <= days; count++) + { + double sales; + cout << "Enter the sales for day " << count << ": "; + cin >> sales; + total += sales; // Accumulate the running total. + } + + // Display the total sales. + cout << fixed << showpoint << setprecision(2); + cout << "The total sales are $" << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-13.cpp b/SourceCode/Chapter 05/Pr5-13.cpp new file mode 100755 index 0000000..8f5c873 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-13.cpp @@ -0,0 +1,27 @@ +// This program calculates the total number of points a +// soccer team has earned over a series of games. The user +// enters a series of point values, then -1 when finished. +#include +using namespace std; + +int main() +{ + int game = 1, // Game counter + points, // To hold a number of points + total = 0; // Accumulator + + cout << "Enter the number of points your team has earned\n"; + cout << "so far in the season, then enter -1 when finished.\n\n"; + cout << "Enter the points for game " << game << ": "; + cin >> points; + + while (points != -1) + { + total += points; + game++; + cout << "Enter the points for game " << game << ": "; + cin >> points; + } + cout << "\nThe total points are " << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-14.cpp b/SourceCode/Chapter 05/Pr5-14.cpp new file mode 100755 index 0000000..d27d88f --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-14.cpp @@ -0,0 +1,43 @@ +// This program averages test scores. It asks the user for the +// number of students and the number of test scores per student. +#include +#include +using namespace std; + +int main() +{ + int numStudents, // Number of students + numTests; // Number of tests per student + double total, // Accumulator for total scores + average; // Average test score + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Get the number of students. + cout << "This program averages test scores.\n"; + cout << "For how many students do you have scores? "; + cin >> numStudents; + + // Get the number of test scores per student. + cout << "How many test scores does each student have? "; + cin >> numTests; + + // Determine each student's average score. + for (int student = 1; student <= numStudents; student++) + { + total = 0; // Initialize the accumulator. + for (int test = 1; test <= numTests; test++) + { + double score; + cout << "Enter score " << test << " for "; + cout << "student " << student << ": "; + cin >> score; + total += score; + } + average = total / numTests; + cout << "The average score for student " << student; + cout << " is " << average << ".\n\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-15.cpp b/SourceCode/Chapter 05/Pr5-15.cpp new file mode 100755 index 0000000..4af305c --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-15.cpp @@ -0,0 +1,23 @@ +// This program writes data to a file. +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + outputFile.open("demofile.txt"); + + cout << "Now writing data to the file.\n"; + + // Write four names to the file. + outputFile << "Bach\n"; + outputFile << "Beethoven\n"; + outputFile << "Mozart\n"; + outputFile << "Schubert\n"; + + // Close the file + outputFile.close(); + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-16.cpp b/SourceCode/Chapter 05/Pr5-16.cpp new file mode 100755 index 0000000..a047327 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-16.cpp @@ -0,0 +1,23 @@ +// This program writes data to a single line in a file. +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + outputFile.open("demofile.txt"); + + cout << "Now writing data to the file.\n"; + + // Write four names to the file. + outputFile << "Bach"; + outputFile << "Beethoven"; + outputFile << "Mozart"; + outputFile << "Schubert"; + + // Close the file + outputFile.close(); + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-17.cpp b/SourceCode/Chapter 05/Pr5-17.cpp new file mode 100755 index 0000000..2e3ac79 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-17.cpp @@ -0,0 +1,32 @@ +// This program writes user input to a file. +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + int number1, number2, number3; + + // Open an output file. + outputFile.open("Numbers.txt"); + + // Get three numbers from the user. + cout << "Enter a number: "; + cin >> number1; + cout << "Enter another number: "; + cin >> number2; + cout << "One more time. Enter a number: "; + cin >> number3; + + // Write the numbers to the file. + outputFile << number1 << endl; + outputFile << number2 << endl; + outputFile << number3 << endl; + cout << "The numbers were saved to a file.\n"; + + // Close the file. + outputFile.close(); + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-18.cpp b/SourceCode/Chapter 05/Pr5-18.cpp new file mode 100755 index 0000000..da20e05 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-18.cpp @@ -0,0 +1,33 @@ +// This program writes user input to a file. +#include +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + string name1, name2, name3; + + // Open an output file. + outputFile.open("Friends.txt"); + + // Get the names of three friends. + cout << "Enter the names of three friends.\n"; + cout << "Friend #1: "; + cin >> name1; + cout << "Friend #2: "; + cin >> name2; + cout << "Friend #3: "; + cin >> name3; + + // Write the names to the file. + outputFile << name1 << endl; + outputFile << name2 << endl; + outputFile << name3 << endl; + cout << "The names were saved to a file.\n"; + + // Close the file + outputFile.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-19.cpp b/SourceCode/Chapter 05/Pr5-19.cpp new file mode 100755 index 0000000..8786eb5 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-19.cpp @@ -0,0 +1,26 @@ +// This program reads data from a file. +#include +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + string name; + + inputFile.open("Friends.txt"); + cout << "Reading data from the file.\n"; + + inputFile >> name; // Read name 1 from the file + cout << name << endl; // Display name 1 + + inputFile >> name; // Read name 2 from the file + cout << name << endl; // Display name 2 + + inputFile >> name; // Read name 3 from the file + cout << name << endl; // Display name 3 + + inputFile.close(); // Close the file + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-2.cpp b/SourceCode/Chapter 05/Pr5-2.cpp new file mode 100755 index 0000000..d69d6c1 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-2.cpp @@ -0,0 +1,22 @@ +// This program demonstrates the prefix and postfix +// modes of the increment and decrement operators. +#include +using namespace std; + +int main() +{ + int num = 4; + + cout << num << endl; // Displays 4 + cout << num++ << endl; // Displays 4, then adds 1 to num + cout << num << endl; // Displays 5 + cout << ++num << endl; // Adds 1 to num, then displays 6 + cout << endl; // Displays a blank line + + cout << num << endl; // Displays 6 + cout << num-- << endl; // Displays 6, then subtracts 1 from num + cout << num << endl; // Displays 5 + cout << --num << endl; // Subtracts 1 from num, then displays 4 + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-20.cpp b/SourceCode/Chapter 05/Pr5-20.cpp new file mode 100755 index 0000000..c9d5fc8 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-20.cpp @@ -0,0 +1,33 @@ +// This program reads numbers from a file. +#include +#include +using namespace std; + +int main() +{ + ifstream inFile; + int value1, value2, value3, sum; + + // Open the file. + inFile.open("NumericData.txt"); + + // Read the three numbers from the file. + inFile >> value1; + inFile >> value2; + inFile >> value3; + + // Close the file. + inFile.close(); + + // Calculate the sum of the numbers. + sum = value1 + value2 + value3; + + // Display the three numbers. + cout << "Here are the numbers:\n" + << value1 << " " << value2 + << " " << value3 << endl; + + // Display the sum of the numbers. + cout << "Their sum is: " << sum << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-21.cpp b/SourceCode/Chapter 05/Pr5-21.cpp new file mode 100755 index 0000000..59a08a1 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-21.cpp @@ -0,0 +1,36 @@ +// This program writes user input to a file. +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; // File stream object + int numberOfDays; // Number of days of sales + double sales; // Sales amount for a day + + // Get the number of days. + cout << "For how many days do you have sales? "; + cin >> numberOfDays; + + // Open a file named Sales.txt. + outputFile.open("Sales.txt"); + + // Get the sales for each day and write it + // to the file. + for (int count = 1; count <= numberOfDays; count++) + { + // Get the sales for a day. + cout << "Enter the sales for day " + << count << ": "; + cin >> sales; + + // Write the sales to the file. + outputFile << sales << endl; + } + + // Close the file. + outputFile.close(); + cout << "Data written to Sales.txt\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-22.cpp b/SourceCode/Chapter 05/Pr5-22.cpp new file mode 100755 index 0000000..df80593 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-22.cpp @@ -0,0 +1,24 @@ +// This program reads data from a file. +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int number; + + // Open the file. + inputFile.open("ListOfNumbers.txt"); + + // Read the numbers from the file and + // display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close the file. + inputFile.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-23.cpp b/SourceCode/Chapter 05/Pr5-23.cpp new file mode 100755 index 0000000..f34c7dc --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-23.cpp @@ -0,0 +1,33 @@ +// This program tests for file open errors. +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int number; + + // Open the file. + inputFile.open("BadListOfNumbers.txt"); + + // If the file successfully opened, process it. + if (inputFile) + { + // Read the numbers from the file and + // display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close the file. + inputFile.close(); + } + else + { + // Display an error message. + cout << "Error opening the file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-24.cpp b/SourceCode/Chapter 05/Pr5-24.cpp new file mode 100755 index 0000000..24470bf --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-24.cpp @@ -0,0 +1,39 @@ +// This program lets the user enter a filename. +#include +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + string filename; + int number; + + // Get the filename from the user. + cout << "Enter the filename: "; + cin >> filename; + + // Open the file. + inputFile.open(filename); + + // If the file successfully opened, process it. + if (inputFile) + { + // Read the numbers from the file and + // display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close the file. + inputFile.close(); + } + else + { + // Display an error message. + cout << "Error opening the file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-25.cpp b/SourceCode/Chapter 05/Pr5-25.cpp new file mode 100755 index 0000000..f91ef0b --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-25.cpp @@ -0,0 +1,27 @@ +// This program raises the user's number to the powers +// of 0 through 10. +#include +#include +using namespace std; + +int main() +{ + int value; + char choice; + + cout << "Enter a number: "; + cin >> value; + cout << "This program will raise " << value; + cout << " to the powers of 0 through 10.\n"; + for (int count = 0; count <= 10; count++) + { + cout << value << " raised to the power of "; + cout << count << " is " << pow(value, count); + cout << "\nEnter Q to quit or any other key "; + cout << "to continue. "; + cin >> choice; + if (choice == 'Q' || choice == 'q') + break; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-26.cpp b/SourceCode/Chapter 05/Pr5-26.cpp new file mode 100755 index 0000000..19a5ee9 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-26.cpp @@ -0,0 +1,39 @@ +// This program calculates the charges for DVD rentals. +// Every third DVD is free. +#include +#include +using namespace std; + +int main() +{ + int dvdCount = 1; // DVD counter + int numDVDs; // Number of DVDs rented + double total = 0.0; // Accumulator + char current; // Current release, Y or N + + // Get the number of DVDs. + cout << "How many DVDs are being rented? "; + cin >> numDVDs; + + // Determine the charges. + do + { + if ((dvdCount % 3) == 0) + { + cout << "DVD #" << dvdCount << " is free!\n"; + continue; // Immediately start the next iteration + } + cout << "Is DVD #" << dvdCount; + cout << " a current release? (Y/N) "; + cin >> current; + if (current == 'Y' || current == 'y') + total += 3.50; + else + total += 2.50; + } while (dvdCount++ < numDVDs); + + // Display the total. + cout << fixed << showpoint << setprecision(2); + cout << "The total is $" << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-3.cpp b/SourceCode/Chapter 05/Pr5-3.cpp new file mode 100755 index 0000000..c16e526 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-3.cpp @@ -0,0 +1,16 @@ +// This program demonstrates a simple while loop. +#include +using namespace std; + +int main() +{ + int number = 0; + + while (number < 5) + { + cout << "Hello\n"; + number++; + } + cout << "That's all!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-4.cpp b/SourceCode/Chapter 05/Pr5-4.cpp new file mode 100755 index 0000000..b2acfcf --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-4.cpp @@ -0,0 +1,32 @@ +// This program assists a technician in the process +// of checking a substance's temperature. +#include +using namespace std; + +int main() +{ + const double MAX_TEMP = 102.5; // Maximum temperature + double temperature; // To hold the temperature + + // Get the current temperature. + cout << "Enter the substance's Celsius temperature: "; + cin >> temperature; + + // As long as necessary, instruct the technician + // to adjust the thermostat. + while (temperature > MAX_TEMP) + { + cout << "The temperature is too high. Turn the\n"; + cout << "thermostat down and wait 5 minutes.\n"; + cout << "Then take the Celsius temperature again\n"; + cout << "and enter it here: "; + cin >> temperature; + } + + // Remind the technician to check the temperature + // again in 15 minutes. + cout << "The temperature is acceptable.\n"; + cout << "Chek it again in 15 minutes.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-5.cpp b/SourceCode/Chapter 05/Pr5-5.cpp new file mode 100755 index 0000000..b572311 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-5.cpp @@ -0,0 +1,58 @@ +// This program calculates the number of soccer teams +// that a youth league may create from the number of +// available players. Input validation is demonstrated +// with while loops. +#include +using namespace std; + +int main() +{ + // Constants for minimum and maximum players + const int MIN_PLAYERS = 9, + MAX_PLAYERS = 15; + + // Variables + int players, // Number of available players + teamPlayers, // Number of desired players per team + numTeams, // Number of teams + leftOver; // Number of players left over + + // Get the number of players per team. + cout << "How many players do you wish per team? "; + cin >> teamPlayers; + + // Validate the input. + while (teamPlayers < MIN_PLAYERS || teamPlayers > MAX_PLAYERS) + { + // Explain the error. + cout << "You should have at least " << MIN_PLAYERS + << " but no more than " << MAX_PLAYERS << " per team.\n"; + + // Get the input again. + cout << "How many players do you wish per team? "; + cin >> teamPlayers; + } + + // Get the number of players available. + cout << "How many players are available? "; + cin >> players; + + // Validate the input. + while (players <= 0) + { + // Get the input again. + cout << "Please enter 0 or greater: "; + cin >> players; + } + + // Calculate the number of teams. + numTeams = players / teamPlayers; + + // Calculate the number of leftover players. + leftOver = players % teamPlayers; + + // Display the results. + cout << "There will be " << numTeams << " teams with " + << leftOver << " players left over.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-6.cpp b/SourceCode/Chapter 05/Pr5-6.cpp new file mode 100755 index 0000000..d2e7c30 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-6.cpp @@ -0,0 +1,21 @@ +// This program displays a list of numbers and +// their squares. +#include +using namespace std; + +int main() +{ + const int MIN_NUMBER = 1, // Starting number to square + MAX_NUMBER = 10; // Maximum number to square + + int num = MIN_NUMBER; // Counter + + cout << "Number Number Squared\n"; + cout << "-------------------------\n"; + while (num <= MAX_NUMBER) + { + cout << num << "\t\t" << (num * num) << endl; + num++; //Increment the counter. + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-7.cpp b/SourceCode/Chapter 05/Pr5-7.cpp new file mode 100755 index 0000000..e0a8aeb --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-7.cpp @@ -0,0 +1,27 @@ +// This program averages 3 test scores. It repeats as +// many times as the user wishes. +#include +using namespace std; + +int main() +{ + int score1, score2, score3; // Three scores + double average; // Average score + char again; // To hold Y or N input + + do + { + // Get three scores. + cout << "Enter 3 scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average. + average = (score1 + score2 + score3) / 3.0; + cout << "The average is " << average << ".\n"; + + // Does the user want to average another set? + cout << "Do you want to average another set? (Y/N) "; + cin >> again; + } while (again == 'Y' || again == 'y'); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-8.cpp b/SourceCode/Chapter 05/Pr5-8.cpp new file mode 100755 index 0000000..8636ac3 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-8.cpp @@ -0,0 +1,73 @@ +// This program displays a menu and asks the user to make a +// selection. A do-while loop repeats the program until the +// user selects item 4 from the menu. +#include +#include +using namespace std; + +int main() +{ + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Constants for membership rates + const double ADULT = 40.0, + CHILD = 20.0, + SENIOR = 30.0; + + // Variables + int choice; // Menu choice + int months; // Number of months + double charges; // Monthly charges + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu. + cout << "\n\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; + cin >> choice; + + // Validate the menu selection. + while (choice < ADULT_CHOICE || choice > QUIT_CHOICE) + { + cout << "Please enter a valid menu choice: "; + cin >> choice; + } + + // Validate and process the user's choice. + if (choice != QUIT_CHOICE) + { + // Get the number of months. + cout << "For how many months? "; + cin >> months; + + // Respond to the user's menu selection. + switch (choice) + { + case ADULT_CHOICE: + charges = months * ADULT; + break; + case CHILD_CHOICE: + charges = months * CHILD; + break; + case SENIOR_CHOICE: + charges = months * SENIOR; + } + + // Display the monthly charges. + cout << "The total charges are $" + << charges << endl; + } + } while (choice != QUIT_CHOICE); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-9.cpp b/SourceCode/Chapter 05/Pr5-9.cpp new file mode 100755 index 0000000..e10aae0 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-9.cpp @@ -0,0 +1,19 @@ +// This program displays the numbers 1 through 10 and +// their squares. +#include +using namespace std; + +int main() +{ + const int MIN_NUMBER = 1, // Starting value + MAX_NUMBER = 10; // Ending value + int num; + + cout << "Number Number Squared\n"; + cout << "-------------------------\n"; + + for (num = MIN_NUMBER; num <= MAX_NUMBER; num++) + cout << num << "\t\t" << (num * num) << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Sales.txt b/SourceCode/Chapter 05/Sales.txt new file mode 100755 index 0000000..0742e38 --- /dev/null +++ b/SourceCode/Chapter 05/Sales.txt @@ -0,0 +1,5 @@ +1000 +2000 +3000 +4000 +5000 diff --git a/SourceCode/Chapter 06/Pr6-1.cpp b/SourceCode/Chapter 06/Pr6-1.cpp new file mode 100755 index 0000000..2072fee --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-1.cpp @@ -0,0 +1,25 @@ +// This program has two functions: main and displayMessage +#include +using namespace std; + +//***************************************** +// Definition of function displayMessage * +// This function displays a greeting. * +//***************************************** + +void displayMessage() +{ + cout << "Hello from the function displayMessage.\n"; +} + +//***************************************** +// Function main * +//***************************************** + +int main() +{ + cout << "Hello from main.\n"; + displayMessage(); + cout << "Back in function main again.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-10.cpp b/SourceCode/Chapter 06/Pr6-10.cpp new file mode 100755 index 0000000..d9b5adf --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-10.cpp @@ -0,0 +1,91 @@ +// This is a menu-driven program that makes a function call +// for each selection the user makes. +#include +#include +using namespace std; + +// Function prototypes +void showMenu(); +void showFees(double, int); + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold a number of months + + // Constants for the menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Constants for membership rates + const double ADULT = 40.0, + SENIOR = 30.0, + CHILD = 20.0; + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu and get the user's choice. + showMenu(); + cin >> choice; + + // Validate the menu selection. + while (choice < ADULT_CHOICE || choice > QUIT_CHOICE) + { + cout << "Please enter a valid menu choice: "; + cin >> choice; + } + + // If the user does not want to quit, proceed. + if (choice != QUIT_CHOICE) + { + // Get the number of months. + cout << "For how many months? "; + cin >> months; + + // Display the membership fees. + switch (choice) + { + case ADULT_CHOICE: + showFees(ADULT, months); + break; + case CHILD_CHOICE: + showFees(CHILD, months); + break; + case SENIOR_CHOICE: + showFees(SENIOR, months); + } + } + } while (choice != QUIT_CHOICE); + return 0; +} + +//***************************************************************** +// Definition of function showMenu which displays the menu. * +//***************************************************************** + +void showMenu() +{ + cout << "\n\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; +} + +//***************************************************************** +// Definition of function showFees. The memberRate parameter * +// the monthly membership rate and the months parameter holds the * +// number of months. The function displays the total charges. * +//***************************************************************** + +void showFees(double memberRate, int months) +{ + cout << "The total charges are $" + << (memberRate * months) << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-11.cpp b/SourceCode/Chapter 06/Pr6-11.cpp new file mode 100755 index 0000000..3f3a19f --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-11.cpp @@ -0,0 +1,35 @@ +// This program uses a function to perform division. If division +// by zero is detected, the function returns. +#include +using namespace std; + +// Function prototype. +void divide(double, double); + +int main() +{ + double num1, num2; + + cout << "Enter two numbers and I will divide the first\n"; + cout << "number by the second number: "; + cin >> num1 >> num2; + divide(num1, num2); + return 0; +} + +//*************************************************************** +// Definition of function divide. * +// Uses two parameters: arg1 and arg2. The function divides arg1* +// by arg2 and shows the result. If arg2 is zero, however, the * +// function returns. * +//*************************************************************** + +void divide(double arg1, double arg2) +{ + if (arg2 == 0.0) + { + cout << "Sorry, I cannot divide by zero.\n"; + return; + } + cout << "The quotient is " << (arg1 / arg2) << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-12.cpp b/SourceCode/Chapter 06/Pr6-12.cpp new file mode 100755 index 0000000..ed6efa4 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-12.cpp @@ -0,0 +1,33 @@ +// This program uses a function that returns a value. +#include +using namespace std; + +// Function prototype +int sum(int, int); + +int main() +{ + int value1 = 20, // The first value + value2 = 40, // The second value + total; // To hold the total + + // Call the sum function, passing the contents of + // value1 and value2 as arguments. Assign the return + // value to the total variable. + total = sum(value1, value2); + + // Display the sum of the values. + cout << "The sum of " << value1 << " and " + << value2 << " is " << total << endl; + return 0; +} + +//***************************************************** +// Definition of function sum. This function returns * +// the sum of its two parameters. * +//***************************************************** + +int sum(int num1, int num2) +{ + return num1 + num2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-13.cpp b/SourceCode/Chapter 06/Pr6-13.cpp new file mode 100755 index 0000000..5c10e21 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-13.cpp @@ -0,0 +1,57 @@ +// This program demonstrates two value-returning functions. +// The square function is called in a mathematical statement. +#include +#include +using namespace std; + +//Function prototypes +double getRadius(); +double square(double); + +int main() +{ + const double PI = 3.14159; // Constant for pi + double radius; // To hold the circle's radius + double area; // To hold the circle's area + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Get the radius of the circle. + cout << "This program calculates the area of "; + cout << "a circle.\n"; + radius = getRadius(); + + // Caclulate the area of the circle. + area = PI * square(radius); + + // Display the area. + cout << "The area is " << area << endl; + return 0; +} + +//****************************************************** +// Definition of function getRadius. * +// This function asks the user to enter the radius of * +// the circle and then returns that number as a double.* +//****************************************************** + +double getRadius() +{ + double rad; + + cout << "Enter the radius of the circle: "; + cin >> rad; + return rad; +} + +//****************************************************** +// Definition of function square. * +// This function accepts a double argument and returns * +// the square of the argument as a double. * +//****************************************************** + +double square(double number) +{ + return number * number; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-14.cpp b/SourceCode/Chapter 06/Pr6-14.cpp new file mode 100755 index 0000000..d5e626a --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-14.cpp @@ -0,0 +1,73 @@ +// This program converts cups to fluid ounces. +#include +#include +using namespace std; + +// Function prototypes +void showIntro(); +double getCups(); +double cupsToOunces(double); + +int main() +{ + // Variables for the cups and ounces. + double cups, ounces; + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Display an intro screen. + showIntro(); + + // Get the number of cups. + cups = getCups(); + + // Convert cups to fluid ounces. + ounces = cupsToOunces(cups); + + // Display the number of ounces. + cout << cups << " cups equals " + << ounces << " ounces.\n"; + + return 0; +} + +//****************************************** +// The showIntro function displays an * +// introductory screen. * +//****************************************** + +void showIntro() +{ + cout << "This program converts measurements\n" + << "in cups to fluid ounces. For your\n" + << "reference the formula is:\n" + << " 1 cup = 8 fluid ounces\n\n"; +} + +//****************************************** +// The getCups function prompts the user * +// to enter the number of cups and then * +// returns that value as a double. * +//****************************************** + +double getCups() +{ + double numCups; + + cout << "Enter the number of cups: "; + cin >> numCups; + return numCups; +} + +//****************************************** +// The cupsToOunces function accepts a * +// number of cups as an argument and * +// returns the equivalent number of fluid * +// ounces as a double. * +//****************************************** + +double cupsToOunces(double numCups) +{ + return numCups * 8.0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-15.cpp b/SourceCode/Chapter 06/Pr6-15.cpp new file mode 100755 index 0000000..3c5949c --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-15.cpp @@ -0,0 +1,41 @@ +// This program uses a function that returns true or false. +#include +using namespace std; + +// Function prototype +bool isEven(int); + +int main() +{ + int val; + + // Get a number from the user. + cout << "Enter an integer and I will tell you "; + cout << "if it is even or odd: "; + cin >> val; + + // Indicate whether it is even or odd. + if (isEven(val)) + cout << val << " is even.\n"; + else + cout << val << " is odd.\n"; + return 0; +} + +//***************************************************************** +// Definition of function isEven. This function accepts an * +// integer argument and tests it to be even or odd. The function * +// returns true if the argument is even or false if the argument * +// is odd. The return value is an bool. * +//***************************************************************** + +bool isEven(int number) +{ + bool status; + + if (number % 2 == 0) + status = true; // number is even if there is no remainder. + else + status = false; // Otherwise, the number is odd. + return status; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-16.cpp b/SourceCode/Chapter 06/Pr6-16.cpp new file mode 100755 index 0000000..fa793d3 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-16.cpp @@ -0,0 +1,29 @@ +// This program shows that variables defined in a function +// are hidden from other functions. +#include +using namespace std; + +void anotherFunction(); // Function prototype + +int main() +{ + int num = 1; // Local variable + + cout << "In main, num is " << num << endl; + anotherFunction(); + cout << "Back in main, num is " << num << endl; + return 0; +} + +//***************************************************** +// Definition of anotherFunction * +// It has a local variable, num, whose initial value * +// is displayed. * +//***************************************************** + +void anotherFunction() +{ + int num = 20; // Local variable + + cout << "In anotherFunction, num is " << num << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-17.cpp b/SourceCode/Chapter 06/Pr6-17.cpp new file mode 100755 index 0000000..000817d --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-17.cpp @@ -0,0 +1,29 @@ +// This program shows that a global variable is visible +// to all the functions that appear in a program after +// the variable's declaration. +#include +using namespace std; + +void anotherFunction(); // Function prototype +int num = 2; // Global variable + +int main() +{ + cout << "In main, num is " << num << endl; + anotherFunction(); + cout << "Back in main, num is " << num << endl; + return 0; +} + +//***************************************************** +// Definition of anotherFunction * +// This function changes the value of the * +// global variable num. * +//***************************************************** + +void anotherFunction() +{ + cout << "In anotherFunction, num is " << num << endl; + num = 50; + cout << "But, it is now changed to " << num << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-18.cpp b/SourceCode/Chapter 06/Pr6-18.cpp new file mode 100755 index 0000000..a99966a --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-18.cpp @@ -0,0 +1,11 @@ +// This program has an uninitialized global variable. +#include +using namespace std; + +int globalNum; // Global variable, automatically set to zero + +int main() +{ + cout << "globalNum is " << globalNum << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-19.cpp b/SourceCode/Chapter 06/Pr6-19.cpp new file mode 100755 index 0000000..bf0b9b8 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-19.cpp @@ -0,0 +1,85 @@ +// This program calculates gross pay. +#include +#include +using namespace std; + +// Global constants +const double PAY_RATE = 22.55; // Hourly pay rate +const double BASE_HOURS = 40.0; // Max non-overtime hours +const double OT_MULTIPLIER = 1.5; // Overtime multiplier + +// Function prototypes +double getBasePay(double); +double getOvertimePay(double); + +int main() +{ + double hours, // Hours worked + basePay, // Base pay + overtime = 0.0, // Overtime pay + totalPay; // Total pay + + // Get the number of hours worked. + cout << "How many hours did you work? "; + cin >> hours; + + // Get the amount of base pay. + basePay = getBasePay(hours); + + // Get overtime pay, if any. + if (hours > BASE_HOURS) + overtime = getOvertimePay(hours); + + // Calculate the total pay. + totalPay = basePay + overtime; + + // Set up numeric output formatting. + cout << setprecision(2) << fixed << showpoint; + + // Display the pay. + cout << "Base pay: $" << basePay << endl + << "Overtime pay $" << overtime << endl + << "Total pay $" << totalPay << endl; + return 0; +} + +//************************************************ +// The getBasePay function accepts the number of * +// hours worked as an argument and returns the * +// employee's pay for non-overtime hours. * +//************************************************ + +double getBasePay(double hoursWorked) +{ + double basePay; // To hold base pay + + // Determine base pay. + if (hoursWorked > BASE_HOURS) + basePay = BASE_HOURS * PAY_RATE; + else + basePay = hoursWorked * PAY_RATE; + + return basePay; +} + +//************************************************* +// The getOvertimePay function accepts the number * +// of hours worked as an argument and returns the * +// employee's overtime pay. * +//************************************************* + +double getOvertimePay(double hoursWorked) +{ + double overtimePay; // To hold overtime pay + + // Determine overtime pay. + if (hoursWorked > BASE_HOURS) + { + overtimePay = (hoursWorked - BASE_HOURS) * + PAY_RATE * OT_MULTIPLIER; + } + else + overtimePay = 0.0; + + return overtimePay; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-2.cpp b/SourceCode/Chapter 06/Pr6-2.cpp new file mode 100755 index 0000000..ea3eb61 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-2.cpp @@ -0,0 +1,26 @@ +// The function displayMessage is repeatedly called from a loop. +#include +using namespace std; + +//***************************************** +// Definition of function displayMessage * +// This function displays a greeting. * +//***************************************** + +void displayMessage() +{ + cout << "Hello from the function displayMessage.\n"; +} + +//***************************************** +// Function main * +//***************************************** + +int main() +{ + cout << "Hello from main.\n"; + for (int count = 0; count < 5; count++) + displayMessage(); // Call displayMessage + cout << "Back in function main again.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-20.cpp b/SourceCode/Chapter 06/Pr6-20.cpp new file mode 100755 index 0000000..3cb4f2b --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-20.cpp @@ -0,0 +1,29 @@ +// This program demonstrates how a local variable +// can shadow the name of a global constant. +#include +using namespace std; + +// Gobal constant. +const int BIRDS = 500; + +// Function prototype +void california(); + +int main() +{ + cout << "In main there are " << BIRDS + << " birds.\n"; + california(); + return 0; +} + +//******************************************** +// california function * +//******************************************** + +void california() +{ + const int BIRDS = 10000; + cout << "In california there are " << BIRDS + << " birds.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-21.cpp b/SourceCode/Chapter 06/Pr6-21.cpp new file mode 100755 index 0000000..20c61df --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-21.cpp @@ -0,0 +1,29 @@ +// This program shows that local variables do not retain +// their values between function calls. +#include +using namespace std; + +// Function prototype +void showLocal(); + +int main() +{ + showLocal(); + showLocal(); + return 0; +} + +//*********************************************************** +// Definition of function showLocal. * +// The initial value of localNum, which is 5, is displayed. * +// The value of localNum is then changed to 99 before the * +// function returns. * +//*********************************************************** + +void showLocal() +{ + int localNum = 5; // Local variable + + cout << "localNum is " << localNum << endl; + localNum = 99; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-22.cpp b/SourceCode/Chapter 06/Pr6-22.cpp new file mode 100755 index 0000000..c84d43c --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-22.cpp @@ -0,0 +1,27 @@ +// This program uses a static local variable. +#include +using namespace std; + +void showStatic(); // Function prototype + +int main() +{ + // Call the showStatic function five times. + for (int count = 0; count < 5; count++) + showStatic(); + return 0; +} + +//************************************************************** +// Definition of function showStatic. * +// statNum is a static local variable. Its value is displayed * +// and then incremented just before the function returns. * +//************************************************************** + +void showStatic() +{ + static int statNum; + + cout << "statNum is " << statNum << endl; + statNum++; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-23.cpp b/SourceCode/Chapter 06/Pr6-23.cpp new file mode 100755 index 0000000..f1aae8b --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-23.cpp @@ -0,0 +1,28 @@ +// This program shows that a static local variable is only +// initialized once. +#include +using namespace std; + +void showStatic(); // Function prototype + +int main() +{ + // Call the showStatic function five times. + for (int count = 0; count < 5; count++) + showStatic(); + return 0; +} + +//************************************************************** +// Definition of function showStatic. * +// statNum is a static local variable. Its value is displayed * +// and then incremented just before the function returns. * +//************************************************************** + +void showStatic() +{ + static int statNum = 5; + + cout << "statNum is " << statNum << endl; + statNum++; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-24.cpp b/SourceCode/Chapter 06/Pr6-24.cpp new file mode 100755 index 0000000..241ea38 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-24.cpp @@ -0,0 +1,34 @@ +// This program demonstrates default function arguments. +#include +using namespace std; + +// Function prototype with default arguments +void displayStars(int = 10, int = 1); + +int main() +{ + displayStars(); // Use default values for cols and rows. + cout << endl; + displayStars(5); // Use default value for rows. + cout << endl; + displayStars(7, 3); // Use 7 for cols and 3 for rows. + return 0; +} + +//******************************************************** +// Definition of function displayStars. * +// The default argument for cols is 10 and for rows is 1.* +// This function displays a square made of asterisks. * +//******************************************************** + +void displayStars(int cols, int rows) +{ + // Nested loop. The outer loop controls the rows + // and the inner loop controls the columns. + for (int down = 0; down < rows; down++) + { + for (int across = 0; across < cols; across++) + cout << "*"; + cout << endl; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-25.cpp b/SourceCode/Chapter 06/Pr6-25.cpp new file mode 100755 index 0000000..e2e722c --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-25.cpp @@ -0,0 +1,29 @@ +// This program uses a reference variable as a function +// parameter. +#include +using namespace std; + +// Function prototype. The parameter is a reference variable. +void doubleNum(int &); + +int main() +{ + int value = 4; + + cout << "In main, value is " << value << endl; + cout << "Now calling doubleNum..." << endl; + doubleNum(value); + cout << "Now back in main. value is " << value << endl; + return 0; +} + +//********************************************************** +// Definition of doubleNum. * +// The parameter refVar is a reference variable. The value * +// in refVar is doubled. * +//********************************************************** + +void doubleNum (int &refVar) +{ + refVar *= 2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-26.cpp b/SourceCode/Chapter 06/Pr6-26.cpp new file mode 100755 index 0000000..88aeff8 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-26.cpp @@ -0,0 +1,46 @@ +// This program uses reference variables as function parameters. +#include +using namespace std; + +// Function prototypes. Both functions use reference variables +// as parameters. +void doubleNum(int &); +void getNum(int &); + +int main() +{ + int value; + + // Get a number and store it in value. + getNum(value); + + // Double the number stored in value. + doubleNum(value); + + // Display the resulting number. + cout << "That value doubled is " << value << endl; + return 0; +} + +//************************************************************* +// Definition of getNum. * +// The parameter userNum is a reference variable. The user is * +// asked to enter a number, which is stored in userNum. * +//************************************************************* + +void getNum(int &userNum) +{ + cout << "Enter a number: "; + cin >> userNum; +} + +//********************************************************** +// Definition of doubleNum. * +// The parameter refVar is a reference variable. The value * +// in refVar is doubled. * +//********************************************************** + +void doubleNum (int &refVar) +{ + refVar *= 2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-27.cpp b/SourceCode/Chapter 06/Pr6-27.cpp new file mode 100755 index 0000000..7f209cb --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-27.cpp @@ -0,0 +1,46 @@ +// This program uses overloaded functions. +#include +#include +using namespace std; + +// Function prototypes +int square(int); +double square(double); + +int main() +{ + int userInt; + double userFloat; + + // Get an int and a double. + cout << fixed << showpoint << setprecision(2); + cout << "Enter an integer and a floating-point value: "; + cin >> userInt >> userFloat; + + // Display their squares. + cout << "Here are their squares: "; + cout << square(userInt) << " and " << square(userFloat); + return 0; +} + +//************************************************************** +// Definition of overloaded function square. * +// This function uses an int parameter, number. It returns the * +// square of number as an int. * +//************************************************************** + +int square(int number) +{ + return number * number; +} + +//*************************************************************** +// Definition of overloaded function square. * +// This function uses a double parameter, number. It returns * +// the square of number as a double. * +//*************************************************************** + +double square(double number) +{ + return number * number; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-28.cpp b/SourceCode/Chapter 06/Pr6-28.cpp new file mode 100755 index 0000000..4dc5d8d --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-28.cpp @@ -0,0 +1,97 @@ +// This program demonstrates overloaded functions to calculate +// the gross weekly pay of hourly-paid or salaried employees. +#include +#include +using namespace std; + +// Function prototypes +void getChoice(char &); +double calcWeeklyPay(int, double); +double calcWeeklyPay(double); + +int main() +{ + char selection; // Menu selection + int worked; // Hours worked + double rate; // Hourly pay rate + double yearly; // Yearly salary + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the menu and get a selection. + cout << "Do you want to calculate the weekly pay of\n"; + cout << "(H) an hourly-paid employee, or \n"; + cout << "(S) a salaried employee?\n"; + getChoice(selection); + + // Process the menu selection. + switch (selection) + { + // Hourly-paid employee + case 'H' : + case 'h' : cout << "How many hours were worked? "; + cin >> worked; + cout << "What is the hour pay rate? "; + cin >> rate; + cout << "The gross weekly pay is $"; + cout << calcWeeklyPay(worked, rate) << endl; + break; + + // Salaried employee + case 'S' : + case 's' : cout << "What is the annual salary? "; + cin >> yearly; + cout << "The gross weekly pay is $"; + cout << calcWeeklyPay(yearly) << endl; + break; + } + return 0; +} + +//************************************************************* +// Definition of function getChoice. * +// The parameter letter is a reference to a char. * +// This function asks the user for an H or an S and returns * +// the validated input. * +//************************************************************* + +void getChoice(char &letter) +{ + // Get the user's selection. + cout << "Enter your choice (H or S): "; + cin >> letter; + + // Validate the selection. + while (letter != 'H' && letter != 'h' && + letter != 'S' && letter != 's') + { + cout << "Please enter H or S: "; + cin >> letter; + } +} + +//*********************************************************** +// Definition of overloaded function calcWeeklyPay. * +// This function calculates the gross weekly pay of * +// an hourly-paid employee. The parameter hours holds the * +// number of hours worked. The parameter payRate holds the * +// hourly pay rate. The function returns the weekly salary. * +//*********************************************************** + +double calcWeeklyPay(int hours, double payRate) +{ + return hours * payRate; +} + +//*********************************************************** +// Definition of overloaded function calcWeeklyPay. * +// This function calculates the gross weekly pay of * +// a salaried employee. The parameter holds the employee's * +// annual salary. The function returns the weekly salary. * +//*********************************************************** + +double calcWeeklyPay(double annSalary) +{ + return annSalary / 52; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-29.cpp b/SourceCode/Chapter 06/Pr6-29.cpp new file mode 100755 index 0000000..231cff7 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-29.cpp @@ -0,0 +1,27 @@ +// This program shows how the exit function causes a program +// to stop executing. +#include +#include // Needed for the exit function +using namespace std; + +void function(); // Function prototype + +int main() +{ + function(); + return 0; +} + +//*********************************************************** +// This function simply demonstrates that exit can be used * +// to terminate a program from a function other than main. * +//*********************************************************** + +void function() +{ + cout << "This program terminates with the exit function.\n"; + cout << "Bye!\n"; + exit(0); + cout << "This message will never be displayed\n"; + cout << "because the program has already terminated.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-3.cpp b/SourceCode/Chapter 06/Pr6-3.cpp new file mode 100755 index 0000000..466c742 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-3.cpp @@ -0,0 +1,36 @@ +// This program has three functions: main, first, and second. +#include +using namespace std; + +//***************************************** +// Definition of function first * +// This function displays a message. * +//***************************************** + +void first() +{ + cout << "I am now inside the function first.\n"; +} + +//***************************************** +// Definition of function second * +// This function displays a message. * +//***************************************** + +void second() +{ + cout << "I am now inside the function second.\n"; +} + +//***************************************** +// Function main * +//***************************************** + +int main() +{ + cout << "I am starting in function main.\n"; + first(); // Call function first + second(); // Call function second + cout << "Back in function main again.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-30.cpp b/SourceCode/Chapter 06/Pr6-30.cpp new file mode 100755 index 0000000..99a7a61 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-30.cpp @@ -0,0 +1,45 @@ +// This program is a driver for testing the showFees function. +#include +using namespace std; + +// Prototype +void showFees(double, int); + +int main() +{ + // Constants for membership rates + const double ADULT = 40.0; + const double SENIOR = 30.0; + const double CHILD = 20.0; + + // Perform a test for adult membership. + cout << "Testing an adult membership...\n" + << "Calling the showFees function with arguments " + << ADULT << " and 10.\n"; + showFees(ADULT, 10); + + // Perform a test for senior citizen membership. + cout << "\nTesting a senior citizen membership...\n" + << "Calling the showFees function with arguments " + << SENIOR << " and 10.\n"; + showFees(SENIOR, 10); + + // Perform a test for child membership. + cout << "\nTesting a child membership...\n" + << "\nCalling the showFees function with arguments " + << CHILD << " and 10.\n"; + showFees(CHILD, 10); + return 0; +} + +//***************************************************************** +// Definition of function showFees. The memberRate parameter * +// the monthly membership rate and the months parameter holds the * +// number of months. The function displays the total charges. * +//***************************************************************** + +void showFees(double memberRate, int months) +{ + cout << "The total charges are $" + << (memberRate * months) << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-4.cpp b/SourceCode/Chapter 06/Pr6-4.cpp new file mode 100755 index 0000000..210d371 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-4.cpp @@ -0,0 +1,37 @@ +// This program has three functions: main, deep, and deeper +#include +using namespace std; + +//***************************************** +// Definition of function deeper * +// This function displays a message. * +//***************************************** + +void deeper() +{ + cout << "I am now inside the function deeper.\n"; +} + +//***************************************** +// Definition of function deep * +// This function displays a message. * +//***************************************** + +void deep() +{ + cout << "I am now inside the function deep.\n"; + deeper(); // Call function deeper + cout << "Now I am back in deep.\n"; +} + +//***************************************** +// Function main * +//***************************************** + +int main() +{ + cout << "I am starting in function main.\n"; + deep(); // Call function deep + cout << "Back in function main again.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-5.cpp b/SourceCode/Chapter 06/Pr6-5.cpp new file mode 100755 index 0000000..352c6b4 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-5.cpp @@ -0,0 +1,36 @@ +// This program has three functions: main, first, and second. +#include +using namespace std; + +// Function Prototypes +void first(); +void second(); + +int main() +{ + cout << "I am starting in function main.\n"; + first(); // Call function first + second(); // Call function second + cout << "Back in function main again.\n"; + return 0; +} + +//************************************* +// Definition of function first. * +// This function displays a message. * +//************************************* + +void first() +{ + cout << "I am now inside the function first.\n"; +} + +//************************************* +// Definition of function second. * +// This function displays a message. * +//************************************* + +void second() +{ + cout << "I am now inside the function second.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-6.cpp b/SourceCode/Chapter 06/Pr6-6.cpp new file mode 100755 index 0000000..33013c3 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-6.cpp @@ -0,0 +1,24 @@ +// This program demonstrates a function with a parameter. +#include +using namespace std; + +// Function Prototype +void displayValue(int); + +int main() +{ + cout << "I am passing 5 to displayValue.\n"; + displayValue(5); // Call displayValue with argument 5 + cout << "Now I am back in main.\n"; + return 0; +} + +//********************************************************* +// Definition of function displayValue. * +// It uses an integer parameter whose value is displayed. * +//********************************************************* + +void displayValue(int num) +{ + cout << "The value is " << num << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-7.cpp b/SourceCode/Chapter 06/Pr6-7.cpp new file mode 100755 index 0000000..e0ba586 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-7.cpp @@ -0,0 +1,27 @@ +// This program demonstrates a function with a parameter. +#include +using namespace std; + +// Function Prototype +void displayValue(int); + +int main() +{ + cout << "I am passing several values to displayValue.\n"; + displayValue(5); // Call displayValue with argument 5 + displayValue(10); // Call displayValue with argument 10 + displayValue(2); // Call displayValue with argument 2 + displayValue(16); // Call displayValue with argument 16 + cout << "Now I am back in main.\n"; + return 0; +} + +//********************************************************* +// Definition of function displayValue. * +// It uses an integer parameter whose value is displayed. * +//********************************************************* + +void displayValue(int num) +{ + cout << "The value is " << num << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-8.cpp b/SourceCode/Chapter 06/Pr6-8.cpp new file mode 100755 index 0000000..4015496 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-8.cpp @@ -0,0 +1,30 @@ +// This program demonstrates a function with three parameters. +#include +using namespace std; + +// Function Prototype +void showSum(int, int, int); + +int main() +{ + int value1, value2, value3; + + // Get three integers. + cout << "Enter three integers and I will display "; + cout << "their sum: "; + cin >> value1 >> value2 >> value3; + + // Call showSum passing three arguments. + showSum(value1, value2, value3); + return 0; +} + +//************************************************************ +// Definition of function showSum. * +// It uses three integer parameters. Their sum is displayed. * +//************************************************************ + +void showSum(int num1, int num2, int num3) +{ + cout << (num1 + num2 + num3) << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-9.cpp b/SourceCode/Chapter 06/Pr6-9.cpp new file mode 100755 index 0000000..02eeb99 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-9.cpp @@ -0,0 +1,38 @@ +// This program demonstrates that changes to a function parameter +// have no affect on the original argument. +#include +using namespace std; + +// Function Prototype +void changeMe(int); + +int main() +{ + int number = 12; + + // Display the value in number. + cout << "number is " << number << endl; + + // Call changeMe, passing the value in number + // as an argument. + changeMe(number); + + // Display the value in number again. + cout << "Now back in main again, the value of "; + cout << "number is " << number << endl; + return 0; +} + +//************************************************************** +// Definition of function changeMe. * +// This function changes the value of the parameter myValue. * +//************************************************************** + +void changeMe(int myValue) +{ + // Change the value of myValue to 0. + myValue = 0; + + // Display the value in myValue. + cout << "Now the value is " << myValue << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-1.cpp b/SourceCode/Chapter 07/Pr7-1.cpp new file mode 100755 index 0000000..da32ef6 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-1.cpp @@ -0,0 +1,30 @@ +// This program asks for the number of hours worked +// by six employees. It stores the values in an array. +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 6; + int hours[NUM_EMPLOYEES]; + + // Get the hours worked by each employee. + cout << "Enter the hours worked by " + << NUM_EMPLOYEES << " employees: "; + cin >> hours[0]; + cin >> hours[1]; + cin >> hours[2]; + cin >> hours[3]; + cin >> hours[4]; + cin >> hours[5]; + + // Display the values in the array. + cout << "The hours you entered are:"; + cout << " " << hours[0]; + cout << " " << hours[1]; + cout << " " << hours[2]; + cout << " " << hours[3]; + cout << " " << hours[4]; + cout << " " << hours[5] << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-10.cpp b/SourceCode/Chapter 07/Pr7-10.cpp new file mode 100755 index 0000000..bd1274d --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-10.cpp @@ -0,0 +1,15 @@ +// This program demonstrates the range-based for loop. +#include +using namespace std; + +int main() +{ + // Define an array of integers. + int numbers[] = { 10, 20, 30, 40, 50 }; + + // Display the values in the array. + for (auto val : numbers) + cout << val << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-11.cpp b/SourceCode/Chapter 07/Pr7-11.cpp new file mode 100755 index 0000000..5b4056f --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-11.cpp @@ -0,0 +1,19 @@ +// This program demonstrates the range-based for loop. +#include +#include +using namespace std; + +int main() +{ + string planets[] = { "Mercury", "Venus", "Earth", "Mars", + "Jupiter", "Saturn", "Uranus", + "Neptune", "Pluto (a dwarf planet)" }; + + cout << "Here are the planets:\n"; + + // Display the values in the array. + for (auto val : planets) + cout << val << endl; + + return 0; +} diff --git a/SourceCode/Chapter 07/Pr7-12.cpp b/SourceCode/Chapter 07/Pr7-12.cpp new file mode 100755 index 0000000..da966e5 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-12.cpp @@ -0,0 +1,24 @@ +// This program uses a range-based for loop to +// modify the contents of an array. +#include +using namespace std; + +int main() +{ + const int SIZE = 5; + int numbers[5]; + + // Get values for the array. + for (auto &val : numbers) + { + cout << "Enter an integer value: "; + cin >> val; + } + + // Display the values in the array. + cout << "Here are the values you entered:\n"; + for (auto val : numbers) + cout << val << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-13.cpp b/SourceCode/Chapter 07/Pr7-13.cpp new file mode 100755 index 0000000..8a4c946 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-13.cpp @@ -0,0 +1,38 @@ +// This program stores, in an array, the hours worked by +// employees who all make the same hourly wage. +#include +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 5; // Number of employees + int hours[NUM_EMPLOYEES]; // Array to hold hours + double payrate; // Hourly pay rate + double grossPay; // To hold the gross pay + + // Input the hours worked. + cout << "Enter the hours worked by "; + cout << NUM_EMPLOYEES << " employees who all\n"; + cout << "earn the same hourly rate.\n"; + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Employee #" << (index + 1) << ": "; + cin >> hours[index]; + } + + // Input the hourly rate for all employees. + cout << "Enter the hourly pay rate for all the employees: "; + cin >> payrate; + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + grossPay = hours[index] * payrate; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-14.cpp b/SourceCode/Chapter 07/Pr7-14.cpp new file mode 100755 index 0000000..de39237 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-14.cpp @@ -0,0 +1,30 @@ +// This program reads data from a file into an array. +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 100; // Array size + int numbers[ARRAY_SIZE]; // Array with 100 elements + int count = 0; // Loop counter variable + ifstream inputFile; // Input file stream object + + inputFile.open("numbers.txt"); // Open the file. + + // Read the numbers from the file into the array. + // After this loop executes, the count variable will hold + // the number of values that were stored in the array. + while (count < ARRAY_SIZE && inputFile >> numbers[count]) + count++; + + // Close the file. + inputFile.close(); + + // Display the numbers read. + cout << "The numbers are: "; + for (int index = 0; index < count; index++) + cout << numbers[index] << " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-15.cpp b/SourceCode/Chapter 07/Pr7-15.cpp new file mode 100755 index 0000000..42f4176 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-15.cpp @@ -0,0 +1,35 @@ +// This program uses two parallel arrays: one for hours +// worked and one for pay rate. +#include +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 5; // Number of employees + int hours[NUM_EMPLOYEES]; // Holds hours worked + double payRate[NUM_EMPLOYEES]; // Holds pay rates + + // Input the hours worked and the hourly pay rate. + cout << "Enter the hours worked by " << NUM_EMPLOYEES + << " employees and their\n" + << "hourly pay rates.\n"; + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Hours worked by employee #" << (index+1) << ": "; + cin >> hours[index]; + cout << "Hourly pay rate for employee #" << (index+1) << ": "; + cin >> payRate[index]; + } + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-16.cpp b/SourceCode/Chapter 07/Pr7-16.cpp new file mode 100755 index 0000000..586e091 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-16.cpp @@ -0,0 +1,27 @@ +// This program demonstrates that an array element is passed +// to a function like any other variable. +#include +using namespace std; + +void showValue(int); // Function prototype + +int main() +{ + const int SIZE = 8; + int numbers[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; + + for (int index = 0; index < SIZE; index++) + showValue(numbers[index]); + return 0; +} + +//********************************************** +// Definition of function showValue. * +// This function accepts an integer argument. * +// The value of the argument is displayed. * +//********************************************** + +void showValue(int num) +{ + cout << num << " "; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-17.cpp b/SourceCode/Chapter 07/Pr7-17.cpp new file mode 100755 index 0000000..aba9e1b --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-17.cpp @@ -0,0 +1,28 @@ +// This program demonstrates an array being passed to a function. +#include +using namespace std; + +void showValues(int [], int); // Function prototype + +int main() +{ + const int ARRAY_SIZE = 8; + int numbers[ARRAY_SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; + + showValues(numbers, ARRAY_SIZE); + return 0; +} + +//************************************************** +// Definition of function showValue. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array are displayed. * +//************************************************** + +void showValues(int nums[], int size) +{ + for (int index = 0; index < size; index++) + cout << nums[index] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-18.cpp b/SourceCode/Chapter 07/Pr7-18.cpp new file mode 100755 index 0000000..c82b29d --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-18.cpp @@ -0,0 +1,35 @@ +// This program demonstrates the showValues function being +// used to display the contents of two arrays. +#include +using namespace std; + +void showValues(int [], int); // Function prototype + +int main() +{ + const int SIZE1 = 8; // Size of set1 array + const int SIZE2 = 5; // Size of set2 array + int set1[SIZE1] = {5, 10, 15, 20, 25, 30, 35, 40}; + int set2[SIZE2] = {2, 4, 6, 8, 10}; + + // Pass set1 to showValues. + showValues(set1, SIZE1); + + // Pass set2 to showValues. + showValues(set2, SIZE2); + return 0; +} + +//************************************************** +// Definition of function showValues. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array are displayed. * +//************************************************** + +void showValues(int nums[], int size) +{ + for (int index = 0; index < size; index++) + cout << nums[index] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-19.cpp b/SourceCode/Chapter 07/Pr7-19.cpp new file mode 100755 index 0000000..c19bfc6 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-19.cpp @@ -0,0 +1,54 @@ +// This program uses a function to double the value of +// each element of an array. +#include +using namespace std; + +// Function prototypes +void doubleArray(int [], int); +void showValues(int [], int); + +int main() +{ + const int ARRAY_SIZE = 7; + int set[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7}; + + // Display the initial values. + cout << "The arrays values are:\n"; + showValues(set, ARRAY_SIZE); + + // Double the values in the array. + doubleArray(set, ARRAY_SIZE); + + // Display the resulting values. + cout << "After calling doubleArray the values are:\n"; + showValues(set, ARRAY_SIZE); + + return 0; +} + +//***************************************************** +// Definition of function doubleArray * +// This function doubles the value of each element * +// in the array passed into nums. The value passed * +// into size is the number of elements in the array. * +//***************************************************** + +void doubleArray(int nums[], int size) +{ + for (int index = 0; index < size; index++) + nums[index] *= 2; +} + +//************************************************** +// Definition of function showValues. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array are displayed. * +//************************************************** + +void showValues(int nums[], int size) +{ + for (int index = 0; index < size; index++) + cout << nums[index] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-2.cpp b/SourceCode/Chapter 07/Pr7-2.cpp new file mode 100755 index 0000000..b39da6e --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-2.cpp @@ -0,0 +1,26 @@ +// This program asks for the number of hours worked +// by six employees. It stores the values in an array. +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 6; // Number of employees + int hours[NUM_EMPLOYEES]; // Each employee's hours + int count; // Loop counter + + // Input the hours worked. + for (count = 0; count < NUM_EMPLOYEES; count++) + { + cout << "Enter the hours worked by employee " + << (count + 1) << ": "; + cin >> hours[count]; + } + + // Display the contents of the array. + cout << "The hours you entered are:"; + for (count = 0; count < NUM_EMPLOYEES; count++) + cout << " " << hours[count]; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-20.cpp b/SourceCode/Chapter 07/Pr7-20.cpp new file mode 100755 index 0000000..0906879 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-20.cpp @@ -0,0 +1,109 @@ +// This program gets a series of test scores and +// calculates the average of the scores with the +// lowest score dropped. +#include +#include +using namespace std; + +// Function prototypes +void getTestScores(double[], int); +double getTotal(const double[], int); +double getLowest(const double[], int); + +int main() +{ + const int SIZE = 4; // Array size + double testScores[SIZE], // Array of test scores + total, // Total of the scores + lowestScore, // Lowest test score + average; // Average test score + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Get the test scores from the user. + getTestScores(testScores, SIZE); + + // Get the total of the test scores. + total = getTotal(testScores, SIZE); + + // Get the lowest test score. + lowestScore = getLowest(testScores, SIZE); + + // Subtract the lowest score from the total. + total -= lowestScore; + + // Calculate the average. Divide by 3 because + // the lowest test score was dropped. + average = total / (SIZE - 1); + + // Display the average. + cout << "The average with the lowest score " + << "dropped is " << average << ".\n"; + + return 0; +} + +//************************************************************ +// The getTestScores function accepts an array and its size * +// as arguments. It prompts the user to enter test scores, * +// which are stored in the array. * +//************************************************************ + +void getTestScores(double scores[], int size) +{ + // Loop counter + int index; + + // Get each test score. + for(index = 0; index <= size - 1; index++) + { + cout << "Enter test score number " + << (index + 1) << ": "; + cin >> scores[index]; + } +} + +//**************************************************** +// The getTotal function accepts a double array * +// and its size as arguments. The sum of the array's * +// elements is returned as a double. * +//**************************************************** + +double getTotal(const double array[], int size) +{ + double total = 0; // Accumulator + + // Add each element to total. + for (int count = 0; count < size; count++) + total += array[count]; + + // Return the total. + return total; +} + +//**************************************************** +// The getLowest function accepts a double array and * +// its size as arguments. The lowest value in the * +// array is returned as a double. * +//**************************************************** + +double getLowest(const double array[], int size) +{ + double lowest; // To hold the lowest value + + // Get the first array's first element. + lowest = array[0]; + + // Step through the rest of the array. When a + // value less than lowest is found, assign it + // to lowest. + for (int count = 1; count < size; count++) + { + if (array[count] < lowest) + lowest = array[count]; + } + + // Return the lowest value. + return lowest; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-21.cpp b/SourceCode/Chapter 07/Pr7-21.cpp new file mode 100755 index 0000000..31ecf9d --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-21.cpp @@ -0,0 +1,42 @@ +// This program demonstrates a two-dimensional array. +#include +#include +using namespace std; + +int main() +{ + const int NUM_DIVS = 3; // Number of divisions + const int NUM_QTRS = 4; // Number of quarters + double sales[NUM_DIVS][NUM_QTRS]; // Array with 3 rows and 4 columns. + double totalSales = 0; // To hold the total sales. + int div, qtr; // Loop counters. + + cout << "This program will calculate the total sales of\n"; + cout << "all the company's divisions.\n"; + cout << "Enter the following sales information:\n\n"; + + // Nested loops to fill the array with quarterly + // sales figures for each division. + for (div = 0; div < NUM_DIVS; div++) + { + for (qtr = 0; qtr < NUM_QTRS; qtr++) + { + cout << "Division " << (div + 1); + cout << ", Quarter " << (qtr + 1) << ": $"; + cin >> sales[div][qtr]; + } + cout << endl; // Print blank line. + } + + // Nested loops used to add all the elements. + for (div = 0; div < NUM_DIVS; div++) + { + for (qtr = 0; qtr < NUM_QTRS; qtr++) + totalSales += sales[div][qtr]; + } + + cout << fixed << showpoint << setprecision(2); + cout << "The total sales for the company are: $"; + cout << totalSales << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-22.cpp b/SourceCode/Chapter 07/Pr7-22.cpp new file mode 100755 index 0000000..baee1c3 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-22.cpp @@ -0,0 +1,47 @@ +// This program demonstrates accepting a 2D array argument. +#include +#include +using namespace std; + +// Global constants +const int COLS = 4; // Number of columns in each array +const int TBL1_ROWS = 3; // Number of rows in table1 +const int TBL2_ROWS = 4; // Number of rows in table2 + +void showArray(const int [][COLS], int); // Function prototype + +int main() +{ + int table1[TBL1_ROWS][COLS] = {{1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}}; + int table2[TBL2_ROWS][COLS] = {{10, 20, 30, 40}, + {50, 60, 70, 80}, + {90, 100, 110, 120}, + {130, 140, 150, 160}}; + + cout << "The contents of table1 are:\n"; + showArray(table1, TBL1_ROWS); + cout << "The contents of table2 are:\n"; + showArray(table2, TBL2_ROWS); + return 0; +} + +//***************************************************************** +// Function Definition for showArray * +// The first argument is a two-dimensional int array with COLS * +// columns. The second argument, rows, specifies the number of * +// rows in the array. The function displays the array's contents. * +//***************************************************************** + +void showArray(const int array[][COLS], int rows) +{ + for (int x = 0; x < rows; x++) + { + for (int y = 0; y < COLS; y++) + { + cout << setw(4) << array[x][y] << " "; + } + cout << endl; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-23.cpp b/SourceCode/Chapter 07/Pr7-23.cpp new file mode 100755 index 0000000..579340b --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-23.cpp @@ -0,0 +1,48 @@ +// This program is a driver that tests a function comparing the +// contents of two int arrays. +#include +using namespace std; + +// Function Prototype +bool testPIN(const int [], const int [], int); + +int main () +{ + const int NUM_DIGITS = 7; // Number of digits in a PIN + int pin1[NUM_DIGITS] = {2, 4, 1, 8, 7, 9, 0}; // Base set of values. + int pin2[NUM_DIGITS] = {2, 4, 6, 8, 7, 9, 0}; // Only 1 element is + // different from pin1. + int pin3[NUM_DIGITS] = {1, 2, 3, 4, 5, 6, 7}; // All elements are + // different from pin1. + if (testPIN(pin1, pin2, NUM_DIGITS)) + cout << "ERROR: pin1 and pin2 report to be the same.\n"; + else + cout << "SUCCESS: pin1 and pin2 are different.\n"; + + if (testPIN(pin1, pin3, NUM_DIGITS)) + cout << "ERROR: pin1 and pin3 report to be the same.\n"; + else + cout << "SUCCESS: pin1 and pin3 are different.\n"; + + if (testPIN(pin1, pin1, NUM_DIGITS)) + cout << "SUCCESS: pin1 and pin1 report to be the same.\n"; + else + cout << "ERROR: pin1 and pin1 report to be different.\n"; + return 0; +} + +//****************************************************************** +// The following function accepts two int arrays. The arrays are * +// compared. If they contain the same values, true is returned. * +// If the contain different values, false is returned. * +//****************************************************************** + +bool testPIN(const int custPIN[], const int databasePIN[], int size) +{ + for (int index = 0; index < size; index++) + { + if (custPIN[index] != databasePIN[index]) + return false; // We've found two different values. + } + return true; // If we make it this far, the values are the same. +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-24.cpp b/SourceCode/Chapter 07/Pr7-24.cpp new file mode 100755 index 0000000..66461b9 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-24.cpp @@ -0,0 +1,38 @@ +// This program stores, in two vectors, the hours worked by 5 +// employees, and their hourly pay rates. +#include +#include +#include // Needed to define vectors +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 5; // Number of employees + vector hours(NUM_EMPLOYEES); // A vector of integers + vector payRate(NUM_EMPLOYEES); // A vector of doubles + int index; // Loop counter + + // Input the data. + cout << "Enter the hours worked by " << NUM_EMPLOYEES; + cout << " employees and their hourly rates.\n"; + for (index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Hours worked by employee #" << (index + 1); + cout << ": "; + cin >> hours[index]; + cout << "Hourly pay rate for employee #"; + cout << (index + 1) << ": "; + cin >> payRate[index]; + } + + // Display each employee's gross pay. + cout << "\nHere is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (index = 0; index < NUM_EMPLOYEES; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-25.cpp b/SourceCode/Chapter 07/Pr7-25.cpp new file mode 100755 index 0000000..d37bfba --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-25.cpp @@ -0,0 +1,16 @@ +// This program demonstrates the range-based for loop with a vector. +#include +#include + using namespace std; + +int main() +{ + // Define and initialize a vector. + vector numbers { 10, 20, 30, 40, 50 }; + + // Display the vector elements. + for (int val : numbers) + cout << val << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-26.cpp b/SourceCode/Chapter 07/Pr7-26.cpp new file mode 100755 index 0000000..a6d5126 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-26.cpp @@ -0,0 +1,24 @@ +// This program demonstrates the range-based for loop with a vector. +#include +#include + using namespace std; + +int main() +{ + // Define and initialize a vector. + vector numbers(5); + + // Get values for the vector elements. + for (int &val : numbers) + { + cout << "Enter an integer value: "; + cin >> val; + } + + // Display the vector elements. + cout << "Here are the values that you entered:\n"; + for (int val : numbers) + cout << val << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-27.cpp b/SourceCode/Chapter 07/Pr7-27.cpp new file mode 100755 index 0000000..973a3a5 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-27.cpp @@ -0,0 +1,47 @@ +// This program stores, in two arrays, the hours worked by 5 +// employees, and their hourly pay rates. +#include +#include +#include // Needed to define vectors +using namespace std; + +int main() +{ + vector hours; // hours is an empty vector + vector payRate; // payRate is an empty vector + int numEmployees; // The number of employees + int index; // Loop counter + + // Get the number of employees. + cout << "How many employees do you have? "; + cin >> numEmployees; + + // Input the payroll data. + cout << "Enter the hours worked by " << numEmployees; + cout << " employees and their hourly rates.\n"; + for (index = 0; index < numEmployees; index++) + { + int tempHours; // To hold the number of hours entered + double tempRate; // To hold the payrate entered + + cout << "Hours worked by employee #" << (index + 1); + cout << ": "; + cin >> tempHours; + hours.push_back(tempHours); // Add an element to hours + cout << "Hourly pay rate for employee #"; + cout << (index + 1) << ": "; + cin >> tempRate; + payRate.push_back(tempRate); // Add an element to payRate + } + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (index = 0; index < numEmployees; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-28.cpp b/SourceCode/Chapter 07/Pr7-28.cpp new file mode 100755 index 0000000..fb3b181 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-28.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the vector size +// member function. +#include +#include +using namespace std; + +// Function prototype +void showValues(vector); + +int main() +{ + vector values; + + // Put a series of numbers in the vector. + for (int count = 0; count < 7; count++) + values.push_back(count * 2); + + // Display the numbers. + showValues(values); + return 0; +} + +//************************************************** +// Definition of function showValues. * +// This function accepts an int vector as its * +// argument. The value of each of the vector's * +// elements is displayed. * +//************************************************** + +void showValues(vector vect) +{ + for (int count = 0; count < vect.size(); count++) + cout << vect[count] << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-29.cpp b/SourceCode/Chapter 07/Pr7-29.cpp new file mode 100755 index 0000000..882d03c --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-29.cpp @@ -0,0 +1,31 @@ +// This program demonstrates the vector pop_back member function. +#include +#include +using namespace std; + +int main() +{ + vector values; + + // Store values in the vector. + values.push_back(1); + values.push_back(2); + values.push_back(3); + cout << "The size of values is " << values.size() << endl; + + // Remove a value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now " << values.size() << endl; + + // Now remove another value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now " << values.size() << endl; + + // Remove the last value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now " << values.size() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-3.cpp b/SourceCode/Chapter 07/Pr7-3.cpp new file mode 100755 index 0000000..a0b7533 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-3.cpp @@ -0,0 +1,29 @@ +// This program reads data from a file into an array. +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 10; // Array size + int numbers[ARRAY_SIZE]; // Array with 10 elements + int count = 0; // Loop counter variable + ifstream inputFile; // Input file stream object + + // Open the file. + inputFile.open("TenNumbers.txt"); + + // Read the numbers from the file into the array. + while (count < ARRAY_SIZE && inputFile >> numbers[count]) + count++; + + // Close the file. + inputFile.close(); + + // Display the numbers read: + cout << "The numbers are: "; + for (count = 0; count < ARRAY_SIZE; count++) + cout << numbers[count] << " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-30.cpp b/SourceCode/Chapter 07/Pr7-30.cpp new file mode 100755 index 0000000..1e9c2c9 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-30.cpp @@ -0,0 +1,17 @@ +// This program demonstrates the vector clear member function. +#include +#include +using namespace std; + +int main() +{ + vector values(100); + + cout << "The values vector has " + << values.size() << " elements.\n"; + cout << "I will call the clear member function...\n"; + values.clear(); + cout << "Now, the values vector has " + << values.size() << " elements.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-31.cpp b/SourceCode/Chapter 07/Pr7-31.cpp new file mode 100755 index 0000000..f556757 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-31.cpp @@ -0,0 +1,59 @@ +// This program demonstrates the vector's empty member function. +#include +#include +using namespace std; + +// Function prototype +double avgVector(vector); + +int main() +{ + vector values; // A vector to hold values + int numValues; // The number of values + double average; // To hold the average + + // Get the number of values to averge. + cout << "How many values do you wish to average? "; + cin >> numValues; + + // Get the values and store them in the vector. + for (int count = 0; count < numValues; count++) + { + int tempValue; + cout << "Enter a value: "; + cin >> tempValue; + values.push_back(tempValue); + } + + // Get the average of the values and display it. + average = avgVector(values); + cout << "Average: " << average << endl; + return 0; +} + +//************************************************************* +// Definition of function avgVector. * +// This function accepts an int vector as its argument. If * +// the vector contains values, the function returns the * +// average of those values. Otherwise, an error message is * +// displayed and the function returns 0.0. * +//************************************************************* + +double avgVector(vector vect) +{ + int total = 0; // accumulator + double avg; // average + + if (vect.empty()) // Determine if the vector is empty + { + cout << "No values to average.\n"; + avg = 0.0; + } + else + { + for (int count = 0; count < vect.size(); count++) + total += vect[count]; + avg = total / vect.size(); + } + return avg; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-4.cpp b/SourceCode/Chapter 07/Pr7-4.cpp new file mode 100755 index 0000000..6019e5a --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-4.cpp @@ -0,0 +1,30 @@ +// This program writes the contents of an array to a file. +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 10; // Array size + int numbers[ARRAY_SIZE]; // Array with 10 elements + int count; // Loop counter variable + ofstream outputFile; // Output file stream object + + // Store values in the array. + for (count = 0; count < ARRAY_SIZE; count++) + numbers[count] = count; + + // Open a file for output. + outputFile.open("SavedNumbers.txt"); + + // Write the array contents to the file. + for (count = 0; count < ARRAY_SIZE; count++) + outputFile << numbers[count] << endl; + + // Close the file. + outputFile.close(); + + // That's it! + cout << "The numbers were saved to the file.\n "; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-5.cpp b/SourceCode/Chapter 07/Pr7-5.cpp new file mode 100755 index 0000000..9361353 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-5.cpp @@ -0,0 +1,24 @@ +// This program unsafely accesses an area of memory by writing +// values beyond an array's boundary. +// WARNING: If you compile and run this program, it could crash. +#include +using namespace std; + +int main() +{ + const int SIZE = 3; // Constant for the array size + int values[SIZE]; // An array of 3 integers + int count; // Loop counter variable + + // Attempt to store five numbers in the three-element array. + cout << "I will store 5 numbers in a 3 element array!\n"; + for (count = 0; count < 5; count++) + values[count] = 100; + + // If the program is still running, display the numbers. + cout << "If you see this message, it means the program\n"; + cout << "has not crashed! Here are the numbers:\n"; + for (count = 0; count < 5; count++) + cout << values[count] << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-6.cpp b/SourceCode/Chapter 07/Pr7-6.cpp new file mode 100755 index 0000000..f44a7f0 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-6.cpp @@ -0,0 +1,18 @@ +// This program displays the number of days in each month. +#include +using namespace std; + +int main() +{ + const int MONTHS = 12; + int days[MONTHS] = { 31, 28, 31, 30, + 31, 30, 31, 31, + 30, 31, 30, 31}; + + for (int count = 0; count < MONTHS; count++) + { + cout << "Month " << (count + 1) << " has "; + cout << days[count] << " days.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-7.cpp b/SourceCode/Chapter 07/Pr7-7.cpp new file mode 100755 index 0000000..70e2d8b --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-7.cpp @@ -0,0 +1,18 @@ +// This program initializes a string array. +#include +#include +using namespace std; + +int main() +{ + const int SIZE = 9; + string planets[SIZE] = { "Mercury", "Venus", "Earth", "Mars", + "Jupiter", "Saturn", "Uranus", + "Neptune", "Pluto (a dwarf planet)" }; + + cout << "Here are the planets:\n"; + + for (int count = 0; count < SIZE; count++) + cout << planets[count] << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-8.cpp b/SourceCode/Chapter 07/Pr7-8.cpp new file mode 100755 index 0000000..00a77ef --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-8.cpp @@ -0,0 +1,21 @@ +// This program uses an array of ten characters to store the +// first ten Letters of the alphabet. The ASCII codes of the +// characters are displayed. +#include +using namespace std; + +int main() +{ + const int NUM_LETTERS = 10; + char letters[NUM_LETTERS] = {'A', 'B', 'C', 'D', 'E', + 'F', 'G', 'H', 'I', 'J'}; + + cout << "Character" << "\t" << "ASCII Code\n"; + cout << "---------" << "\t" << "----------\n"; + for (int count = 0; count < NUM_LETTERS; count++) + { + cout << letters[count] << "\t\t"; + cout << static_cast(letters[count]) << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-9.cpp b/SourceCode/Chapter 07/Pr7-9.cpp new file mode 100755 index 0000000..d6eed98 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-9.cpp @@ -0,0 +1,16 @@ +// This program has a partially initialized array. +#include +using namespace std; + +int main() +{ + const int SIZE = 7; + int numbers[SIZE] = {1, 2, 4, 8}; // Initialize first 4 elements + + cout << "Here are the contents of the array:\n"; + for (int index = 0; index < SIZE; index++) + cout << numbers[index] << " "; + + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/SavedNumbers.txt b/SourceCode/Chapter 07/SavedNumbers.txt new file mode 100755 index 0000000..127f666 --- /dev/null +++ b/SourceCode/Chapter 07/SavedNumbers.txt @@ -0,0 +1,10 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 diff --git a/SourceCode/Chapter 07/TenNumbers.txt b/SourceCode/Chapter 07/TenNumbers.txt new file mode 100755 index 0000000..9a13b6b --- /dev/null +++ b/SourceCode/Chapter 07/TenNumbers.txt @@ -0,0 +1,10 @@ +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 diff --git a/SourceCode/Chapter 07/numbers.txt b/SourceCode/Chapter 07/numbers.txt new file mode 100755 index 0000000..7d2cdb3 --- /dev/null +++ b/SourceCode/Chapter 07/numbers.txt @@ -0,0 +1,12 @@ +47 +89 +65 +36 +12 +25 +17 +8 +62 +10 +87 +62 diff --git a/SourceCode/Chapter 08/Pr8-1.cpp b/SourceCode/Chapter 08/Pr8-1.cpp new file mode 100755 index 0000000..c7ccf93 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-1.cpp @@ -0,0 +1,55 @@ +// This program demonstrates the searchList function, which +// performs a linear search on an integer array. +#include +using namespace std; + +// Function prototype +int searchList(const int [], int, int); +const int SIZE = 5; + +int main() +{ + int tests[SIZE] = {87, 75, 98, 100, 82}; + int results; + + // Search the array for 100. + results = searchList(tests, SIZE, 100); + + // If searchList returned -1, then 100 was not found. + if (results == -1) + cout << "You did not earn 100 points on any test\n"; + else + { + // Otherwise results contains the subscript of + // the first 100 in the array. + cout << "You earned 100 points on test "; + cout << (results + 1) << endl; + } + return 0; +} + +//***************************************************************** +// The searchList function performs a linear search on an * +// integer array. The array list, which has a maximum of numElems * +// elements, is searched for the number stored in value. If the * +// number is found, its array subscript is returned. Otherwise, * +// -1 is returned indicating the value was not in the array. * +//***************************************************************** + +int searchList(const int list[], int numElems, int value) +{ + int index = 0; // Used as a subscript to search array + int position = -1; // To record position of search value + bool found = false; // Flag to indicate if the value was found + + while (index < numElems && !found) + { + if (list[index] == value) // If the value is found + { + found = true; // Set the flag + position = index; // Record the value's subscript + } + index++; // Go to the next element + } + return position; // Return the position, or -1 +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-2.cpp b/SourceCode/Chapter 08/Pr8-2.cpp new file mode 100755 index 0000000..cac29e6 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-2.cpp @@ -0,0 +1,69 @@ +// This program demonstrates the binarySearch function, which +// performs a binary search on an integer array. +#include +using namespace std; + +// Function prototype +int binarySearch(const int [], int, int); +const int SIZE = 20; + +int main() +{ + // Array with employee IDs sorted in ascending order. + int idNums[SIZE] = {101, 142, 147, 189, 199, 207, 222, + 234, 289, 296, 310, 319, 388, 394, + 417, 429, 447, 521, 536, 600}; + int results; // To hold the search results + int empID; // To hold an employee ID + + // Get an employee ID to search for. + cout << "Enter the employee ID you wish to search for: "; + cin >> empID; + + // Search for the ID. + results = binarySearch(idNums, SIZE, empID); + + // If results contains -1 the ID was not found. + if (results == -1) + cout << "That number does not exist in the array.\n"; + else + { + // Otherwise results contains the subscript of + // the specified employee ID in the array. + cout << "That ID is found at element " << results; + cout << " in the array.\n"; + } + return 0; +} + +//*************************************************************** +// The binarySearch function performs a binary search on an * +// integer array. array, which has a maximum of size elements, * +// is searched for the number stored in value. If the number is * +// found, its array subscript is returned. Otherwise, -1 is * +// returned indicating the value was not in the array. * +//*************************************************************** + +int binarySearch(const int array[], int size, int value) +{ + int first = 0, // First array element + last = size - 1, // Last array element + middle, // Mid point of search + position = -1; // Position of search value + bool found = false; // Flag + + while (!found && first <= last) + { + middle = (first + last) / 2; // Calculate mid point + if (array[middle] == value) // If value is found at mid + { + found = true; + position = middle; + } + else if (array[middle] > value) // If value is in lower half + last = middle - 1; + else + first = middle + 1; // If value is in upper half + } + return position; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-3.cpp b/SourceCode/Chapter 08/Pr8-3.cpp new file mode 100755 index 0000000..9491f08 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-3.cpp @@ -0,0 +1,143 @@ +// Demetris Leadership Center (DLC) product lookup program +// This program allows the user to enter a product number +// and then displays the title, description, and price of +// that product. +#include +#include +using namespace std; + +const int NUM_PRODS = 9; // The number of products produced +const int MIN_PRODNUM = 914; // The lowest product number +const int MAX_PRODNUM = 922; // The highest product number + +// Function prototypes +int getProdNum(); +int binarySearch (const int [], int, int); +void displayProd(const string [], const string [], const double [], int); + +int main() +{ + // Array of product IDs + int id[NUM_PRODS] = {914, 915, 916, 917, 918, 919, 920, + 921, 922}; + + // Array of product titles + string title[NUM_PRODS] = + { "Six Steps to Leadership", + "Six Steps to Leadership", + "The Road to Excellence", + "Seven Lessons of Quality", + "Seven Lessons of Quality", + "Seven Lessons of Quality", + "Teams Are Made, Not Born", + "Leadership for the Future", + "Leadership for the Future" + }; + + // Array of product descriptions + string description[NUM_PRODS] = + { "Book", "Audio CD", "DVD", + "Book", "Audio CD", "DVD", + "Book", "Book", "Audio CD" + }; + + // Array of product prices + double prices[NUM_PRODS] = {12.95, 14.95, 18.95, 16.95, 21.95, + 31.95, 14.95, 14.95, 16.95}; + + int prodNum; // To hold a product number + int index; // To hold search results + char again; // To hold a Y or N answer + + do + { + // Get the desired product number. + prodNum = getProdNum(); + + // Search for the product number. + index = binarySearch(id, NUM_PRODS, prodNum); + + // Display the results of the search. + if (index == -1) + cout << "That product number was not found.\n"; + else + displayProd(title, description, prices, index); + + // Does the user want to do this again? + cout << "Would you like to look up another product? (y/n) "; + cin >> again; + } while (again == 'y' || again == 'Y'); + return 0; +} + +//*************************************************** +// Definition of getProdNum function * +// The getProdNum function asks the user to enter a * +// product number. The input is validated, and when * +// a valid number is entered, it is returned. * +//*************************************************** + +int getProdNum() +{ + int prodNum; // Product number + + cout << "Enter the item's product number: "; + cin >> prodNum; + // Validate input + while (prodNum < MIN_PRODNUM || prodNum > MAX_PRODNUM) + { + cout << "Enter a number in the range of " << MIN_PRODNUM; + cout <<" through " << MAX_PRODNUM << ".\n"; + cin >> prodNum; + } + return prodNum; +} + +//*************************************************************** +// Definition of binarySearch function * +// The binarySearch function performs a binary search on an * +// integer array. array, which has a maximum of numElems * +// elements, is searched for the number stored in value. If the * +// number is found, its array subscript is returned. Otherwise, * +// -1 is returned indicating the value was not in the array. * +//*************************************************************** + +int binarySearch(const int array[], int numElems, int value) +{ + int first = 0, // First array element + last = numElems - 1, // Last array element + middle, // Midpoint of search + position = -1; // Position of search value + bool found = false; // Flag + + while (!found && first <= last) + { + middle = (first + last) / 2; // Calculate midpoint + if (array[middle] == value) // If value is found at mid + { + found = true; + position = middle; + } + else if (array[middle] > value) // If value is in lower half + last = middle - 1; + else + first = middle + 1; // If value is in upper half + } + return position; +} + +//************************************************************ +// The displayProd function accepts three arrays and an int. * +// The arrays parameters are expected to hold the title, * +// description, and prices arrays defined in main. The index * +// parameter holds a subscript. This function displays the * +// information in each array contained at the subscript. * +//************************************************************ + +void displayProd(const string title[], const string desc[], + const double price[], int index) +{ + cout << "Title: " << title[index] << endl; + cout << "Description: " << desc[index] << endl; + cout << "Price: $" << price[index] << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-4.cpp b/SourceCode/Chapter 08/Pr8-4.cpp new file mode 100755 index 0000000..9140c73 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-4.cpp @@ -0,0 +1,66 @@ +// This program uses the bubble sort algorithm to sort an +// array in ascending order. +#include +using namespace std; + +// Function prototypes +void sortArray(int [], int); +void showArray(const int [], int); + +int main() +{ + // Array of unsorted values + int values[6] = {7, 2, 3, 8, 9, 1}; + + // Display the values. + cout << "The unsorted values are:\n"; + showArray(values, 6); + + // Sort the values. + sortArray(values, 6); + + // Display them again. + cout << "The sorted values are:\n"; + showArray(values, 6); + return 0; +} + +//*********************************************************** +// Definition of function sortArray * +// This function performs an ascending order bubble sort on * +// array. size is the number of elements in the array. * +//*********************************************************** + +void sortArray(int array[], int size) +{ + bool swap; + int temp; + + do + { + swap = false; + for (int count = 0; count < (size - 1); count++) + { + if (array[count] > array[count + 1]) + { + temp = array[count]; + array[count] = array[count + 1]; + array[count + 1] = temp; + swap = true; + } + } + } while (swap); +} + +//************************************************************* +// Definition of function showArray. * +// This function displays the contents of array. size is the * +// number of elements. * +//************************************************************* + +void showArray(const int array[], int size) +{ + for (int count = 0; count < size; count++) + cout << array[count] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-5.cpp b/SourceCode/Chapter 08/Pr8-5.cpp new file mode 100755 index 0000000..4b586de --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-5.cpp @@ -0,0 +1,67 @@ +// This program uses the selection sort algorithm to sort an +// array in ascending order. +#include +using namespace std; + +// Function prototypes +void selectionSort(int [], int); +void showArray(int [], int); + +int main() +{ + // Define an array with unsorted values + const int SIZE = 6; + int values[SIZE] = {5, 7, 2, 8, 9, 1}; + + // Display the values. + cout << "The unsorted values are\n"; + showArray(values, SIZE); + + // Sort the values. + selectionSort(values, SIZE); + + // Display the values again. + cout << "The sorted values are\n"; + showArray(values, SIZE); + return 0; +} + +//************************************************************** +// Definition of function selectionSort. * +// This function performs an ascending order selection sort on * +// array. size is the number of elements in the array. * +//************************************************************** + +void selectionSort(int array[], int size) +{ + int startScan, minIndex, minValue; + + for (startScan = 0; startScan < (size - 1); startScan++) + { + minIndex = startScan; + minValue = array[startScan]; + for(int index = startScan + 1; index < size; index++) + { + if (array[index] < minValue) + { + minValue = array[index]; + minIndex = index; + } + } + array[minIndex] = array[startScan]; + array[startScan] = minValue; + } +} + +//************************************************************** +// Definition of function showArray. * +// This function displays the contents of array. size is the * +// number of elements. * +//************************************************************** + +void showArray(int array[], int size) +{ + for (int count = 0; count < size; count++) + cout << array[count] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-6.cpp b/SourceCode/Chapter 08/Pr8-6.cpp new file mode 100755 index 0000000..eb0fe03 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-6.cpp @@ -0,0 +1,139 @@ +// This program produces a sales report for DLC, Inc. +#include +#include +using namespace std; + +// Function prototypes +void calcSales(const int [], const double [], double [], int); +void showOrder(const double [], const int [], int); +void dualSort(int [], double [], int); +void showTotals(const double [], const int [], int); + +// NUM_PRODS is the number of products produced. +const int NUM_PRODS = 9; + +int main() +{ + // Array with product ID numbers + int id[NUM_PRODS] = {914, 915, 916, 917, 918, 919, 920, + 921, 922}; + + // Array with number of units sold for each product + int units[NUM_PRODS] = {842, 416, 127, 514, 437, 269, 97, + 492, 212}; + + // Array with product prices + double prices[NUM_PRODS] = {12.95, 14.95, 18.95, 16.95, 21.95, + 31.95, 14.95, 14.95, 16.95}; + + // Array to hold the computed sales amounts + double sales[NUM_PRODS]; + + // Calculate each product's sales. + calcSales(units, prices, sales, NUM_PRODS); + + // Sort the elements in the sales array in descending + // order and shuffle the ID numbers in the id array to + // keep them in parallel. + dualSort(id, sales, NUM_PRODS); + + // Set the numeric output formatting. + cout << setprecision(2) << fixed << showpoint; + + // Display the products and sales amounts. + showOrder(sales, id, NUM_PRODS); + + // Display total units sold and total sales. + showTotals(sales, units, NUM_PRODS); + return 0; +} + +//**************************************************************** +// Definition of calcSales. Accepts units, prices, and sales * +// arrays as arguments. The size of these arrays is passed * +// into the num parameter. This function calculates each * +// product's sales by multiplying its units sold by each unit's * +// price. The result is stored in the sales array. * +//**************************************************************** + +void calcSales(const int units[], const double prices[], double sales[], int num) +{ + for (int index = 0; index < num; index++) + sales[index] = units[index] * prices[index]; +} + +//*************************************************************** +// Definition of function dualSort. Accepts id and sales arrays * +// as arguments. The size of these arrays is passed into size. * +// This function performs a descending order selection sort on * +// the sales array. The elements of the id array are exchanged * +// identically as those of the sales array. size is the number * +// of elements in each array. * +//*************************************************************** + +void dualSort(int id[], double sales[], int size) +{ + int startScan, maxIndex, tempid; + double maxValue; + + for (startScan = 0; startScan < (size - 1); startScan++) + { + maxIndex = startScan; + maxValue = sales[startScan]; + tempid = id[startScan]; + for(int index = startScan + 1; index < size; index++) + { + if (sales[index] > maxValue) + { + maxValue = sales[index]; + tempid = id[index]; + maxIndex = index; + } + } + sales[maxIndex] = sales[startScan]; + id[maxIndex] = id[startScan]; + sales[startScan] = maxValue; + id[startScan] = tempid; + } +} + +//**************************************************************** +// Definition of showOrder function. Accepts sales and id arrays * +// as arguments. The size of these arrays is passed into num. * +// The function first displays a heading, then the sorted list * +// of product numbers and sales. * +//**************************************************************** + +void showOrder(const double sales[], const int id[], int num) +{ + cout << "Product Number\tSales\n"; + cout << "----------------------------------\n"; + for (int index = 0; index < num; index++) + { + cout << id[index] << "\t\t$"; + cout << setw(8) << sales[index] << endl; + } + cout << endl; +} + +//***************************************************************** +// Definition of showTotals function. Accepts sales and id arrays * +// as arguments. The size of these arrays is passed into num. * +// The function first calculates the total units (of all * +// products) sold and the total sales. It then displays these * +// amounts. * +//***************************************************************** + +void showTotals(const double sales[], const int units[], int num) +{ + int totalUnits = 0; + double totalSales = 0.0; + + for (int index = 0; index < num; index++) + { + totalUnits += units[index]; + totalSales += sales[index]; + } + cout << "Total units Sold: " << totalUnits << endl; + cout << "Total sales: $" << totalSales << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-7.cpp b/SourceCode/Chapter 08/Pr8-7.cpp new file mode 100755 index 0000000..0952815 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-7.cpp @@ -0,0 +1,169 @@ +// This program produces a sales report for DLC, Inc. +// This version of the program uses STL vectors instead of arrays. +#include +#include +#include +using namespace std; + +// Function prototypes +void initVectors(vector &, vector &, vector &); +void calcSales(vector, vector, vector &); +void showOrder(vector, vector); +void dualSort(vector &, vector &); +void showTotals(vector, vector); + +int main() +{ + vector id; // Product ID numbers + vector units; // Units sold + vector prices; // Product prices + vector sales; // To hold product sales + + // Must provide an initialization routine. + initVectors(id, units, prices); + + // Calculate each product's sales. + calcSales(units, prices, sales); + + // Sort the elements in the sales array in descending + // order and shuffle the ID numbers in the id array to + // keep them in parallel. + dualSort(id, sales); + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the products and sales amounts. + showOrder(sales, id); + + // Display total units sold and total sales. + showTotals(sales, units); + return 0; +} + +//****************************************************************** +// Definition of initVectors. Accepts id, units, and prices * +// vectors as reference arguments. This function initializes each * +// vector to a set of starting values. * +//****************************************************************** + +void initVectors(vector &id, vector &units, + vector &prices) +{ + // Initialize the id vector with the ID numbers + // 914 through 922. + for (int value = 914; value <= 922; value++) + id.push_back(value); + + // Initialize the units vector with data. + units.push_back(842); + units.push_back(416); + units.push_back(127); + units.push_back(514); + units.push_back(437); + units.push_back(269); + units.push_back(97); + units.push_back(492); + units.push_back(212); + + // Initialize the prices vector. + prices.push_back(12.95); + prices.push_back(14.95); + prices.push_back(18.95); + prices.push_back(16.95); + prices.push_back(21.95); + prices.push_back(31.95); + prices.push_back(14.95); + prices.push_back(14.95); + prices.push_back(16.95); +} + + +//**************************************************************** +// Definition of calcSales. Accepts units, prices, and sales * +// vectors as arguments. The sales vector is passed into a * +// reference parameter. This function calculates each product's * +// sales by multiplying its units sold by each unit's price. The * +// result is stored in the sales vector. * +//**************************************************************** + +void calcSales(vector units, vector prices, + vector &sales) +{ + for (int index = 0; index < units.size(); index++) + sales.push_back(units[index] * prices[index]); +} + +//**************************************************************** +// Definition of function dualSort. Accepts id and sales vectors * +// as reference arguments. This function performs a descending * +// order selection sort on the sales vector. The elements of the * +// id vector are exchanged identically as those of the sales * +// vector. * +//**************************************************************** + +void dualSort(vector &id, vector &sales) +{ + int startScan, maxIndex, tempid, size; + double maxValue; + + size = id.size(); + for (startScan = 0; startScan < (size - 1); startScan++) + { + maxIndex = startScan; + maxValue = sales[startScan]; + tempid = id[startScan]; + for(int index = startScan + 1; index < size; index++) + { + if (sales[index] > maxValue) + { + maxValue = sales[index]; + tempid = id[index]; + maxIndex = index; + } + } + sales[maxIndex] = sales[startScan]; + id[maxIndex] = id[startScan]; + sales[startScan] = maxValue; + id[startScan] = tempid; + } +} + +//***************************************************************** +// Definition of showOrder function. Accepts sales and id vectors * +// as arguments. The function first displays a heading, then the * +// sorted list of product numbers and sales. * +//***************************************************************** + +void showOrder(vector sales, vector id) +{ + cout << "Product Number\tSales\n"; + cout << "----------------------------------\n"; + for (int index = 0; index < id.size(); index++) + { + cout << id[index] << "\t\t$"; + cout << setw(8) << sales[index] << endl; + } + cout << endl; +} + +//******************************************************************* +// Definition of showTotals function. Accepts sales and id vectors * +// as arguments. The function first calculates the total units (of * +// all products) sold and the total sales. It then displays these * +// amounts. * +//******************************************************************* + +void showTotals(vector sales, vector units) +{ + int totalUnits = 0; + double totalSales = 0.0; + + for (int index = 0; index < units.size(); index++) + { + totalUnits += units[index]; + totalSales += sales[index]; + } + cout << "Total Units Sold: " << totalUnits << endl; + cout << "Total Sales: $" << totalSales << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-8.cpp b/SourceCode/Chapter 08/Pr8-8.cpp new file mode 100755 index 0000000..6092192 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-8.cpp @@ -0,0 +1,19 @@ +#include +#include +using namespace std; + +int main() +{ + const int NUM_NAMES = 20; + string names[NUM_NAMES] = {"Collins, Bill", "Smith, Bart", "Allen, Jim", + "Griffin, Jim", "Stamey, Marty", "Rose, Geri", + "Taylor, Terri", "Johnson, Jill", "Allison, Jeff", + "Looney, Joe", "Wolfe, Bill", "James, Jean", + "Weaver, Jim", "Pore, Bob", "Rutherford, Greg", + "Javens, Renee", "Harrison, Rose", "Setzer, Cathy", + "Pike, Gordon", "Holland, Beth" }; + + // Insert your code to complete this program + + return 0; +} diff --git a/SourceCode/Chapter 09/Pr9-1.cpp b/SourceCode/Chapter 09/Pr9-1.cpp new file mode 100755 index 0000000..500c1a1 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-1.cpp @@ -0,0 +1,14 @@ +// This program uses the & operator to determine a variable’s +// address and the sizeof operator to determine its size. +#include +using namespace std; + +int main() +{ + int x = 25; + + cout << "The address of x is " << &x << endl; + cout << "The size of x is " << sizeof(x) << " bytes\n"; + cout << "The value in x is " << x << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-10.cpp b/SourceCode/Chapter 09/Pr9-10.cpp new file mode 100755 index 0000000..c98beb6 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-10.cpp @@ -0,0 +1,33 @@ +// This program uses a pointer to display the contents +// of an integer array. +#include +using namespace std; + +int main() +{ + int set[8] = {5, 10, 15, 20, 25, 30, 35, 40}; + int *nums = set; // Make nums point to set + + // Display the numbers in the array. + cout << "The numbers in set are:\n"; + cout << *nums << " "; // Display first element + while (nums < &set[7]) + { + // Advance nums to point to the next element. + nums++; + // Display the value pointed to by nums. + cout << *nums << " "; + } + + // Display the numbers in reverse order. + cout << "\nThe numbers in set backward are:\n"; + cout << *nums << " "; // Display first element + while (nums > set) + { + // Move backward to the previous element. + nums--; + // Display the value pointed to by nums. + cout << *nums << " "; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-11.cpp b/SourceCode/Chapter 09/Pr9-11.cpp new file mode 100755 index 0000000..f11fa6e --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-11.cpp @@ -0,0 +1,46 @@ +// This program uses two functions that accept addresses of +// variables as arguments. +#include +using namespace std; + +// Function prototypes +void getNumber(int *); +void doubleValue(int *); + +int main() +{ + int number; + + // Call getNumber and pass the address of number. + getNumber(&number); + + // Call doubleValue and pass the address of number. + doubleValue(&number); + + // Display the value in number. + cout << "That value doubled is " << number << endl; + return 0; +} + +//*************************************************************** +// Definition of getNumber. The parameter, input, is a pointer. * +// This function asks the user for a number. The value entered * +// is stored in the variable pointed to by input. * +//*************************************************************** + +void getNumber(int *input) +{ + cout << "Enter an integer number: "; + cin >> *input; +} + +//*************************************************************** +// Definition of doubleValue. The parameter, val, is a pointer. * +// This function multiplies the variable pointed to by val by * +// two. * +//*************************************************************** + +void doubleValue(int *val) +{ + *val *= 2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-12.cpp b/SourceCode/Chapter 09/Pr9-12.cpp new file mode 100755 index 0000000..6e98eb6 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-12.cpp @@ -0,0 +1,58 @@ +// This program demonstrates that a pointer may be used as a +// parameter to accept the address of an array. +#include +#include +using namespace std; + +// Function prototypes +void getSales(double *, int); +double totalSales(double *, int); + +int main() +{ + const int QTRS = 4; + double sales[QTRS]; + + // Get the sales data for all quarters. + getSales(sales, QTRS); + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the total sales for the year. + cout << "The total sales for the year are $"; + cout << totalSales(sales, QTRS) << endl; + return 0; +} + +//***************************************************************** +// Definition of getSales. This function uses a pointer to accept * +// the address of an array of doubles. The function asks the user * +// user to enter sales figures and stores them in the array. * +//***************************************************************** +void getSales(double *arr, int size) +{ + for (int count = 0; count < size; count++) + { + cout << "Enter the sales figure for quarter "; + cout << (count + 1) << ": "; + cin >> arr[count]; + } +} + +//***************************************************************** +// Definition of totalSales. This function uses a pointer to * +// accept the address of an array. The function returns the total * +// of the elements in the array. * +//***************************************************************** +double totalSales(double *arr, int size) +{ + double sum = 0.0; + + for (int count = 0; count < size; count++) + { + sum += *arr; + arr++; + } + return sum; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-13.cpp b/SourceCode/Chapter 09/Pr9-13.cpp new file mode 100755 index 0000000..a065302 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-13.cpp @@ -0,0 +1,39 @@ +// This program demonstrates a pointer to const parameter +#include +using namespace std; + +void displayValues(const int *, int); + +int main() +{ + // Array sizes + const int SIZE = 6; + + // Define an array of const ints. + const int array1[SIZE] = { 1, 2, 3, 4, 5, 6 }; + + // Define an array of non-const ints. + int array2[SIZE] = { 2, 4, 6, 8, 10, 12 }; + + // Display the contents of the const array. + displayValues(array1, SIZE); + + // Display the contents of the non-const array. + displayValues(array2, SIZE); + return 0; +} + +//*************************************************** +// The displayValues function uses a pointer to * +// parameter to display the contents of an array. * +//*************************************************** + +void displayValues(const int *numbers, int size) +{ + // Display all the values. + for (int count = 0; count < size; count++) + { + cout << *(numbers + count) << " "; + } + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-14.cpp b/SourceCode/Chapter 09/Pr9-14.cpp new file mode 100755 index 0000000..7508414 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-14.cpp @@ -0,0 +1,52 @@ +// This program totals and averages the sales figures for any +// number of days. The figures are stored in a dynamically +// allocated array. +#include +#include +using namespace std; + +int main() +{ + double *sales = nullptr, // To dynamically allocate an array + total = 0.0, // Accumulator + average; // To hold average sales + int numDays, // To hold the number of days of sales + count; // Counter variable + + // Get the number of days of sales. + cout << "How many days of sales figures do you wish "; + cout << "to process? "; + cin >> numDays; + + // Dynamically allocate an array large enough to hold + // that many days of sales amounts. + sales = new double[numDays]; + + // Get the sales figures for each day. + cout << "Enter the sales figures below.\n"; + for (count = 0; count < numDays; count++) + { + cout << "Day " << (count + 1) << ": "; + cin >> sales[count]; + } + + // Calculate the total sales + for (count = 0; count < numDays; count++) + { + total += sales[count]; + } + + // Calculate the average sales per day + average = total / numDays; + + // Display the results + cout << fixed << showpoint << setprecision(2); + cout << "\n\nTotal Sales: $" << total << endl; + cout << "Average Sales: $" << average << endl; + + // Free dynamically allocated memory + delete [] sales; + sales = nullptr; // Make sales a nullptr. + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-15.cpp b/SourceCode/Chapter 09/Pr9-15.cpp new file mode 100755 index 0000000..0fb770a --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-15.cpp @@ -0,0 +1,55 @@ +// This program demonstrates a function that returns +// a pointer. +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +// Function prototype +int *getRandomNumbers(int); + +int main() +{ + int *numbers; // To point to the numbers + + // Get an array of five random numbers. + numbers = getRandomNumbers(5); + + // Display the numbers. + for (int count = 0; count < 5; count++) + cout << numbers[count] << endl; + + // Free the memory. + delete [] numbers; + numbers = 0; + return 0; +} + +//************************************************** +// The getRandomNumbers function returns a pointer * +// to an array of random integers. The parameter * +// indicates the number of numbers requested. * +//************************************************** + +int *getRandomNumbers(int num) +{ + int *arr = nullptr; // Array to hold the numbers + + // Return null if num is zero or negative. + if (num <= 0) + return NULL; + + // Dynamically allocate the array. + arr = new int[num]; + + // Seed the random number generator by passing + // the return value of time(0) to srand. + srand( time(0) ); + + // Populate the array with random numbers. + for (int count = 0; count < num; count++) + arr[count] = rand(); + + // Return a pointer to the array. + return arr; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-16.cpp b/SourceCode/Chapter 09/Pr9-16.cpp new file mode 100755 index 0000000..4b514c9 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-16.cpp @@ -0,0 +1,91 @@ +// This program uses a function to duplicate +// an int array of any size. +#include +using namespace std; + +// Function prototype +int *duplicateArray(const int *, int); +void displayArray(const int[], int); + +int main() +{ + // Define constants for the array sizes. + const int SIZE1 = 5, SIZE2 = 7, SIZE3 = 10; + + // Define three arrays of different sizes. + int array1[SIZE1] = { 100, 200, 300, 400, 500 }; + int array2[SIZE2] = { 10, 20, 30, 40, 50, 60, 70 }; + int array3[SIZE3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + + // Define three pointers for the duplicate arrays. + int *dup1 = nullptr, *dup2 = nullptr, *dup3 = nullptr; + + // Duplicate the arrays. + dup1 = duplicateArray(array1, SIZE1); + dup2 = duplicateArray(array2, SIZE2); + dup3 = duplicateArray(array3, SIZE3); + + // Display the original arrays. + cout << "Here are the original array contents:\n"; + displayArray(array1, SIZE1); + displayArray(array2, SIZE2); + displayArray(array3, SIZE3); + + // Display the new arrays. + cout << "\nHere are the duplicate arrays:\n"; + displayArray(dup1, SIZE1); + displayArray(dup2, SIZE2); + displayArray(dup3, SIZE3); + + // Free the dynamically allocated memory and + // set the pointers to 0. + delete [] dup1; + delete [] dup2; + delete [] dup3; + dup1 = nullptr; + dup2 = nullptr; + dup3 = nullptr; + return 0; +} +//***************************************************** +// The duplicateArray function accepts an int array * +// and an int that indicates the array's size. The * +// function creates a new array that is a duplicate * +// of the argument array and returns a pointer to the * +// new array. If an invalid size is passed the * +// function returns null. * +//***************************************************** + +int *duplicateArray(const int *arr, int size) +{ + int *newArray = nullptr; + + // Validate the size. If 0 or a negative + // number was passed, return a null pointer. + if (size <= 0) + return nullptr; + + // Allocate a new array. + newArray = new int[size]; + + // Copy the array's contents to the + // new array. + for (int index = 0; index < size; index++) + newArray[index] = arr[index]; + + // Return a pointer to the new array. + return newArray; +} + +//************************************************** +// The displayArray function accepts an int array * +// and its size as arguments and displays the * +// contents of the array. * +//************************************************** + +void displayArray(const int arr[], int size) +{ + for (int index = 0; index < size; index++) + cout << arr[index] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-17.cpp b/SourceCode/Chapter 09/Pr9-17.cpp new file mode 100755 index 0000000..8e71e3d --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-17.cpp @@ -0,0 +1,18 @@ +// This program demonstrates a unique_ptr. +#include +#include +using namespace std; + +int main() +{ + // Define a unique_ptr smart pointer, pointing + // to a dynamically allocated int. + unique_ptr ptr( new int ); + + // Assign 99 to the dynamically allocated int. + *ptr = 99; + + // Display the value of the dynamically allocated int. + cout << *ptr << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-18.cpp b/SourceCode/Chapter 09/Pr9-18.cpp new file mode 100755 index 0000000..61f9fe1 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-18.cpp @@ -0,0 +1,32 @@ +// This program demonstrates a unique_ptr pointing +// to a dynamically allocated array of integers. +#include +#include +using namespace std; + +int main() +{ + int max; // Max size of the array + + // Get the number of values to store. + cout << "How many numbers do you want to enter? "; + cin >> max; + + // Define a unique_ptr smart pointer, pointing + // to a dynamically allocated array of ints. + unique_ptr ptr( new int[max]); + + // Get values for the array. + for (int index = 0; index < max; index++) + { + cout << "Enter an integer number: "; + cin >> ptr[index]; + } + + // Display the values in the array. + cout << "Here are the values you entered:\n"; + for (int index = 0; index < max; index++) + cout << ptr[index] << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-19.cpp b/SourceCode/Chapter 09/Pr9-19.cpp new file mode 100755 index 0000000..2e8f0f1 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-19.cpp @@ -0,0 +1,101 @@ +// This program shows the donations made to the United Cause +// by the employees of CK Graphics, Inc. It displays +// the donations in order from lowest to highest +// and in the original order they were received. +#include +using namespace std; + +// Function prototypes +void arrSelectSort(int *[], int); +void showArray(const int [], int); +void showArrPtr(int *[], int); + +int main() +{ + const int NUM_DONATIONS = 15; // Number of donations + + // An array containing the donation amounts. + int donations[NUM_DONATIONS] = { 5, 100, 5, 25, 10, + 5, 25, 5, 5, 100, + 10, 15, 10, 5, 10 }; + + // An array of pointers to int. + int *arrPtr[NUM_DONATIONS] = { nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr }; + + // Each element of arrPtr is a pointer to int. Make each + // element point to an element in the donations array. + for (int count = 0; count < NUM_DONATIONS; count++) + arrPtr[count] = &donations[count]; + + // Sort the elements of the array of pointers. + arrSelectSort(arrPtr, NUM_DONATIONS); + + // Display the donations using the array of pointers. This + // will display them in sorted order. + cout << "The donations, sorted in ascending order are: \n"; + showArrPtr(arrPtr, NUM_DONATIONS); + + // Display the donations in their original order. + cout << "The donations, in their original order are: \n"; + showArray(donations, NUM_DONATIONS); + return 0; +} + +//**************************************************************** +// Definition of function arrSelectSort. * +// This function performs an ascending order selection sort on * +// arr, which is an array of pointers. Each element of array * +// points to an element of a second array. After the sort, * +// arr will point to the elements of the second array in * +// ascending order. * +//**************************************************************** + +void arrSelectSort(int *arr[], int size) +{ + int startScan, minIndex; + int *minElem; + + for (startScan = 0; startScan < (size - 1); startScan++) + { + minIndex = startScan; + minElem = arr[startScan]; + for(int index = startScan + 1; index < size; index++) + { + if (*(arr[index]) < *minElem) + { + minElem = arr[index]; + minIndex = index; + } + } + arr[minIndex] = arr[startScan]; + arr[startScan] = minElem; + } +} + +//************************************************************* +// Definition of function showArray. * +// This function displays the contents of arr. size is the * +// number of elements. * +//************************************************************* + +void showArray(const int arr[], int size) +{ + for (int count = 0; count < size; count++) + cout << arr[count] << " "; + cout << endl; +} + +//************************************************************** +// Definition of function showArrPtr. * +// This function displays the contents of the array pointed to * +// by arr. size is the number of elements. * +//************************************************************** + +void showArrPtr(int *arr[], int size) +{ + for (int count = 0; count < size; count++) + cout << *(arr[count]) << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-2.cpp b/SourceCode/Chapter 09/Pr9-2.cpp new file mode 100755 index 0000000..91e655f --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-2.cpp @@ -0,0 +1,14 @@ +// This program stores the address of a variable in a pointer. +#include +using namespace std; + +int main() +{ + int x = 25; // int variable + int *ptr = nullptr; // Pointer variable, can point to an int + + ptr = &x; // Store the address of x in ptr + cout << "The value in x is " << x << endl; + cout << "The address of x is " << ptr << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-3.cpp b/SourceCode/Chapter 09/Pr9-3.cpp new file mode 100755 index 0000000..6d31292 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-3.cpp @@ -0,0 +1,26 @@ +// This program demonstrates the use of the indirection operator. +#include +using namespace std; + +int main() +{ + int x = 25; // int variable + int *ptr = nullptr; // Pointer variable, can point to an int + + ptr = &x; // Store the address of x in ptr + + // Use both x and ptr to display the value in x. + cout << "Here is the value in x, printed twice:\n"; + cout << x << endl; // Displays the contents of x + cout << *ptr << endl; // Displays the contents of x + + // Assign 100 to the location pointed to by ptr. This + // will actually assign 100 to x. + *ptr = 100; + + // Use both x and ptr to display the value in x. + cout << "Once again, here is the value in x:\n"; + cout << x << endl; // Displays the contents of x + cout << *ptr << endl; // Displays the contents of x + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-4.cpp b/SourceCode/Chapter 09/Pr9-4.cpp new file mode 100755 index 0000000..b470542 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-4.cpp @@ -0,0 +1,30 @@ +// This program demonstrates a pointer variable referencing +// different variables. +#include +using namespace std; + +int main() +{ + int x = 25, y = 50, z = 75; // Three int variables + int *ptr = nullptr; // Pointer variable + + // Display the contents of x, y, and z. + cout << "Here are the values of x, y, and z:\n"; + cout << x << " " << y << " " << z << endl; + + // Use the pointer to manipulate x, y, and z. + + ptr = &x; // Store the address of x in ptr. + *ptr += 100; // Add 100 to the value in x. + + ptr = &y; // Store the address of y in ptr. + *ptr += 100; // Add 100 to the value in y. + + ptr = &z; // Store the address of z in ptr. + *ptr += 100; // Add 100 to the value in z. + + // Display the contents of x, y, and z. + cout << "Once again, here are the values of x, y, and z:\n"; + cout << x << " " << y << " " << z << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-5.cpp b/SourceCode/Chapter 09/Pr9-5.cpp new file mode 100755 index 0000000..f2acc06 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-5.cpp @@ -0,0 +1,13 @@ +// This program shows an array name being dereferenced with the * +// operator. +#include +using namespace std; + +int main() +{ + short numbers[] = {10, 20, 30, 40, 50}; + + cout << "The first element of the array is "; + cout << *numbers << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-6.cpp b/SourceCode/Chapter 09/Pr9-6.cpp new file mode 100755 index 0000000..77670d4 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-6.cpp @@ -0,0 +1,24 @@ +// This program processes an array using pointer notation. +#include +using namespace std; + +int main() +{ + const int SIZE = 5; // Size of the array + int numbers[SIZE]; // Array of integers + int count; // Counter variable + + // Get values to store in the array. + // Use pointer notation instead of subscripts. + cout << "Enter " << SIZE << " numbers: "; + for (count = 0; count < SIZE; count++) + cin >> *(numbers + count); + + // Display the values in the array. + // Use pointer notation instead of subscripts. + cout << "Here are the numbers you entered:\n"; + for (count = 0; count < SIZE; count++) + cout << *(numbers + count)<< " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-7.cpp b/SourceCode/Chapter 09/Pr9-7.cpp new file mode 100755 index 0000000..77ed0ae --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-7.cpp @@ -0,0 +1,30 @@ +// This program uses subscript notation with a pointer variable and +// pointer notation with an array name. +#include +#include +using namespace std; + +int main() +{ + const int NUM_COINS = 5; + double coins[NUM_COINS] = {0.05, 0.1, 0.25, 0.5, 1.0}; + double *doublePtr; // Pointer to a double + int count; // Array index + + // Assign the address of the coins array to doublePtr. + doublePtr = coins; + + // Display the contents of the coins array. Use subscripts + // with the pointer! + cout << "Here are the values in the coins array:\n"; + for (count = 0; count < NUM_COINS; count++) + cout << doublePtr[count] << " "; + + // Display the contents of the array again, but this time + // use pointer notation with the array name! + cout << "\nAnd here they are again:\n"; + for (count = 0; count < NUM_COINS; count++) + cout << *(coins + count) << " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-8.cpp b/SourceCode/Chapter 09/Pr9-8.cpp new file mode 100755 index 0000000..1f64108 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-8.cpp @@ -0,0 +1,25 @@ +// This program uses the address of each element in the array. +#include +#include +using namespace std; + +int main() +{ + const int NUM_COINS = 5; + double coins[NUM_COINS] = {0.05, 0.1, 0.25, 0.5, 1.0}; + double *doublePtr = nullptr; // Pointer to a double + int count; // Array index + + // Use the pointer to display the values in the array. + cout << "Here are the values in the coins array:\n"; + for (count = 0; count < NUM_COINS; count++) + { + // Get the address of an array element. + doublePtr = &coins[count]; + + // Display the contents of the element. + cout << *doublePtr << " "; + } + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-9.cpp b/SourceCode/Chapter 09/Pr9-9.cpp new file mode 100755 index 0000000..678230d --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-9.cpp @@ -0,0 +1,31 @@ +// This program uses a pointer to display the contents of an array. +#include +using namespace std; + +int main() +{ + const int SIZE = 8; + int set[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; + int *numPtr = nullptr; // Pointer + int count; // Counter variable for loops + + // Make numPtr point to the set array. + numPtr = set; + + // Use the pointer to display the array contents. + cout << "The numbers in set are:\n"; + for (count = 0; count < SIZE; count++) + { + cout << *numPtr << " "; + numPtr++; + } + + // Display the array contents in reverse order. + cout << "\nThe numbers in set backward are:\n"; + for (count = 0; count < SIZE; count++) + { + numPtr--; + cout << *numPtr << " "; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-1.cpp b/SourceCode/Chapter 10/Pr10-1.cpp new file mode 100755 index 0000000..b3fc758 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-1.cpp @@ -0,0 +1,24 @@ +// This program demonstrates some character testing functions. +#include +#include +using namespace std; + +int main() +{ + char input; + + cout << "Enter any character: "; + cin.get(input); + cout << "The character you entered is: " << input << endl; + if (isalpha(input)) + cout << "That's an alphabetic character.\n"; + if (isdigit(input)) + cout << "That's a numeric digit.\n"; + if (islower(input)) + cout << "The letter you entered is lowercase.\n"; + if (isupper(input)) + cout << "The letter you entered is uppercase.\n"; + if (isspace(input)) + cout << "That's a whitespace character.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-10.cpp b/SourceCode/Chapter 10/Pr10-10.cpp new file mode 100755 index 0000000..c61d1bc --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-10.cpp @@ -0,0 +1,38 @@ +// This program demonstrates the strcmp and atoi functions. +#include +#include // For tolower +#include // For strcmp +#include // For atoi +using namespace std; + +int main() +{ + const int SIZE = 20; // Array size + char input[SIZE]; // To hold user input + int total = 0; // Accumulator + int count = 0; // Loop counter + double average; // To hold the average of numbers + + // Get the first number. + cout << "This program will average a series of numbers.\n"; + cout << "Enter the first number or Q to quit: "; + cin.getline(input, SIZE); + + // Process the number and subsequent numbers. + while (tolower(input[0]) != 'q') + { + total += atoi(input); // Keep a running total + count++; // Count the numbers entered + // Get the next number. + cout << "Enter the next number or Q to quit: "; + cin.getline(input, SIZE); + } + + // If any numbers were entered, display their average. + if (count != 0) + { + average = static_cast(total) / count; + cout << "Average: " << average << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-11.cpp b/SourceCode/Chapter 10/Pr10-11.cpp new file mode 100755 index 0000000..6ddac50 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-11.cpp @@ -0,0 +1,45 @@ +// This program demonstrates how the getline function can +// be used for all of a program's input. +#include +#include +#include +using namespace std; + +int main() +{ + const int INPUT_SIZE = 81; // Size of input array + const int NAME_SIZE = 30; // Size of name array + char input[INPUT_SIZE]; // To hold a line of input + char name[NAME_SIZE]; // To hold a name + int idNumber; // To hold an ID number. + int age; // To hold an age + double income; // To hold income + + // Get the user's ID number. + cout << "What is your ID number? "; + cin.getline(input, INPUT_SIZE); // Read as a string + idNumber = atoi(input); // Convert to int + + // Get the user's name. No conversion necessary. + cout << "What is your name? "; + cin.getline(name, NAME_SIZE); + + // Get the user's age. + cout << "How old are you? "; + cin.getline(input, INPUT_SIZE); // Read as a string + age = atoi(input); // Convert to int + + // Get the user's income. + cout << "What is your annual income? "; + cin.getline(input, INPUT_SIZE); // Read as a string + income = atof(input); // Convert to double + + // Show the resulting data. + cout << setprecision(2) << fixed << showpoint; + cout << "Your name is " << name + <<", you are " << age + << " years old,\nand you make $" + << income << " per year.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-12.cpp b/SourceCode/Chapter 10/Pr10-12.cpp new file mode 100755 index 0000000..d3849b3 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-12.cpp @@ -0,0 +1,45 @@ +// This program uses a function to copy a C-string into an array. +#include +using namespace std; + +void stringCopy(char [], char []); // Function prototype + +int main() +{ + const int LENGTH = 30; // Size of the arrays + char first[LENGTH]; // To hold the user's input + char second[LENGTH]; // To hold the copy + + // Get a string from the user and store in first. + cout << "Enter a string with no more than " + << (LENGTH - 1) << " characters:\n"; + cin.getline(first, LENGTH); + + // Copy the contents of first to second. + stringCopy(first, second); + + // Display the copy. + cout << "The string you entered is:\n" << second << endl; + return 0; +} + +//*********************************************************** +// Definition of the stringCopy function. * +// This function copies the C-string in string1 to string2. * +//*********************************************************** + +void stringCopy(char string1[], char string2[]) +{ + int index = 0; // Loop counter + + // Step through string1, copying each element to + // string2. Stop when the null character is encountered. + while (string1[index] != '\0') + { + string2[index] = string1[index]; + index++; + } + + // Place a null character in string2. + string2[index] = '\0'; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-13.cpp b/SourceCode/Chapter 10/Pr10-13.cpp new file mode 100755 index 0000000..8037f3a --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-13.cpp @@ -0,0 +1,41 @@ +// This program uses the function nameSlice to cut the last +// name off of a string that contains the user's first and +// last names. +#include +using namespace std; + +void nameSlice(char []); // Function prototype + +int main() +{ + const int SIZE = 41; // Array size + char name[SIZE]; // To hold the user's name + + cout << "Enter your first and last names, separated "; + cout << "by a space:\n"; + cin.getline(name, SIZE); + nameSlice(name); + cout << "Your first name is: " << name << endl; + return 0; +} + +//************************************************************** +// Definition of function nameSlice. This function accepts a * +// character array as its argument. It scans the array looking * +// for a space. When it finds one, it replaces it with a null * +// terminator. * +//************************************************************** + +void nameSlice(char userName[]) +{ + int count = 0; // Loop counter + + // Locate the first space, or the null terminator if there + // are no spaces. + while (userName[count] != ' ' && userName[count] != '\0') + count++; + + // If a space was found, replace it with a null terminator. + if (userName[count] == ' ') + userName[count] = '\0'; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-14.cpp b/SourceCode/Chapter 10/Pr10-14.cpp new file mode 100755 index 0000000..6055629 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-14.cpp @@ -0,0 +1,49 @@ +// This program demonstrates a function, countChars, that counts +// the number of times a specific character appears in a string. +#include +using namespace std; + +int countChars(char *, char); // Function prototype + +int main() +{ + const int SIZE = 51; // Array size + char userString[SIZE]; // To hold a string + char letter; // The character to count + + // Get a string from the user. + cout << "Enter a string (up to 50 characters): "; + cin.getline(userString, SIZE); + + // Get a character to count occurrences of within the string. + cout << "Enter a character and I will tell you how many\n"; + cout << "times it appears in the string: "; + cin >> letter; + + // Display the number of times the character appears. + cout << letter << " appears "; + cout << countChars(userString, letter) << " times.\n"; + return 0; +} + +//**************************************************************** +// Definition of countChars. The parameter strPtr is a pointer * +// that points to a string. The parameter Ch is a character that * +// the function searches for in the string. The function returns * +// the number of times the character appears in the string. * +//**************************************************************** + +int countChars(char *strPtr, char ch) +{ + int times = 0; // Number of times ch appears in the string + + // Step through the string counting occurrences of ch. + while (*strPtr != '\0') + { + if (*strPtr == ch) // If the current character equals ch... + times++; // ... increment the counter + strPtr++; // Go to the next char in the string. + } + + return times; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-15.cpp b/SourceCode/Chapter 10/Pr10-15.cpp new file mode 100755 index 0000000..251c6f2 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-15.cpp @@ -0,0 +1,13 @@ +// This program demonstrates the string class. +#include +#include // Required for the string class. +using namespace std; + +int main() +{ + string movieTitle; + + movieTitle = "Wheels of Fury"; + cout << "My favorite movie is " << movieTitle << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-16.cpp b/SourceCode/Chapter 10/Pr10-16.cpp new file mode 100755 index 0000000..2993f43 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-16.cpp @@ -0,0 +1,15 @@ +// This program demonstrates how cin can read a string into +// a string class object. +#include +#include +using namespace std; + +int main() +{ + string name; + + cout << "What is your name? "; + cin >> name; + cout << "Good morning " << name << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-17.cpp b/SourceCode/Chapter 10/Pr10-17.cpp new file mode 100755 index 0000000..0007c7d --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-17.cpp @@ -0,0 +1,29 @@ +// This program uses the == operator to compare the string entered +// by the user with the valid stereo part numbers. +#include +#include +#include +using namespace std; + +int main() +{ + const double APRICE = 249.0; // Price for part A + const double BPRICE = 299.0; // Price for part B + string partNum; // Part mumber + + cout << "The stereo part numbers are:\n"; + cout << "\tBoom Box, part number S147-29A\n"; + cout << "\tShelf Model, part number S147-29B\n"; + cout << "Enter the part number of the stereo you\n"; + cout << "wish to purchase: "; + cin >> partNum; + cout << fixed << showpoint << setprecision(2); + + if (partNum == "S147-29A") + cout << "The price is $" << APRICE << endl; + else if (partNum == "S147-29B") + cout << "The price is $" << BPRICE << endl; + else + cout << partNum << " is not a valid part number.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-18.cpp b/SourceCode/Chapter 10/Pr10-18.cpp new file mode 100755 index 0000000..0889678 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-18.cpp @@ -0,0 +1,28 @@ +// This program uses relational operators to alphabetically +// sort two strings entered by the user. +#include +#include +using namespace std; + +int main () +{ + string name1, name2; + + // Get a name. + cout << "Enter a name (last name first): "; + getline(cin, name1); + + // Get another name. + cout << "Enter another name: "; + getline(cin, name2); + + // Display them in alphabetical order. + cout << "Here are the names sorted alphabetically:\n"; + if (name1 < name2) + cout << name1 << endl << name2 << endl; + else if (name1 > name2) + cout << name2 << endl << name1 << endl; + else + cout << "You entered the same name twice!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-19.cpp b/SourceCode/Chapter 10/Pr10-19.cpp new file mode 100755 index 0000000..43b056a --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-19.cpp @@ -0,0 +1,14 @@ +// This program initializes a string object. +#include +#include +using namespace std; + +int main() +{ + string greeting; + string name("William Smith"); + + greeting = "Hello "; + cout << greeting << name << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-2.cpp b/SourceCode/Chapter 10/Pr10-2.cpp new file mode 100755 index 0000000..136121b --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-2.cpp @@ -0,0 +1,58 @@ +// This program tests a customer number to determine whether +// it is in the proper format. +#include +#include +using namespace std; + +// Function prototype +bool testNum(char [], int); + +int main() +{ + const int SIZE = 8; // Array size + char customer[SIZE]; // To hold a customer number + + // Get the customer number. + cout << "Enter a customer number in the form "; + cout << "LLLNNNN\n"; + cout << "(LLL = letters and NNNN = numbers): "; + cin.getline(customer, SIZE); + + // Determine whether it is valid. + if (testNum(customer, SIZE)) + cout << "That's a valid customer number.\n"; + else + { + cout << "That is not the proper format of the "; + cout << "customer number.\nHere is an example:\n"; + cout << " ABC1234\n"; + } + return 0; +} + +//********************************************************** +// Definition of function testNum. * +// This function determines whether the custNum parameter * +// holds a valid customer number. The size parameter is * +// the size of the custNum array. * +//********************************************************** + +bool testNum(char custNum[], int size) +{ + int count; // Loop counter + + // Test the first three characters for alphabetic letters. + for (count = 0; count < 3; count++) + { + if (!isalpha(custNum[count])) + return false; + } + + // Test the remaining characters for numeric digits. + for (count = 3; count < size - 1; count++) + { + if (!isdigit(custNum[count])) + return false; + } + return true; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-20.cpp b/SourceCode/Chapter 10/Pr10-20.cpp new file mode 100755 index 0000000..7c4b819 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-20.cpp @@ -0,0 +1,25 @@ +// This program demonstrates the C++ string class. +#include +#include +using namespace std; + +int main () +{ + // Define three string objects. + string str1, str2, str3; + + // Assign values to all three. + str1 = "ABC"; + str2 = "DEF"; + str3 = str1 + str2; + + // Display all three. + cout << str1 << endl; + cout << str2 << endl; + cout << str3 << endl; + + // Concatenate a string onto str3 and display it. + str3 += "GHI"; + cout << str3 << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-21.cpp b/SourceCode/Chapter 10/Pr10-21.cpp new file mode 100755 index 0000000..3f4044a --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-21.cpp @@ -0,0 +1,16 @@ +// This program demonstrates a string +// object's length member function. +#include +#include +using namespace std; + +int main () +{ + string town; + + cout << "Where do you live? "; + cin >> town; + cout << "Your town's name has " << town.length() ; + cout << " characters\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-22.cpp b/SourceCode/Chapter 10/Pr10-22.cpp new file mode 100755 index 0000000..a26bb93 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-22.cpp @@ -0,0 +1,28 @@ +// This program demonstrates the C++ string class. +#include +#include +using namespace std; + +int main() +{ + // Define three string objects. + string str1, str2, str3; + + // Assign values to all three. + str1 = "ABC"; + str2 = "DEF"; + str3 = str1 + str2; + + // Use subscripts to display str3 one character + // at a time. + for (int x = 0; x < str3.size(); x++) + cout << str3[x]; + cout << endl; + + // Compare str1 with str2. + if (str1 < str2) + cout << "str1 is less than str2\n"; + else + cout << "str1 is not less than str2\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-23.cpp b/SourceCode/Chapter 10/Pr10-23.cpp new file mode 100755 index 0000000..396186f --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-23.cpp @@ -0,0 +1,43 @@ +// This program lets the user enter a number. The +// dollarFormat function formats the number as +// a dollar amount. +#include +#include +using namespace std; + +// Function prototype +void dollarFormat(string &); + +int main () +{ + string input; + + // Get the dollar amount from the user. + cout << "Enter a dollar amount in the form nnnnn.nn : "; + cin >> input; + dollarFormat(input); + cout << "Here is the amount formatted:\n"; + cout << input << endl; + return 0; +} + +//************************************************************ +// Definition of the dollarFormat function. This function * +// accepts a string reference object, which is assumed to * +// to hold a number with a decimal point. The function * +// formats the number as a dollar amount with commas and * +// a $ symbol. * +//************************************************************ + +void dollarFormat(string ¤cy) +{ + int dp; + + dp = currency.find('.'); // Find decimal point + if (dp > 3) // Insert commas + { + for (int x = dp - 3; x > 0; x -= 3) + currency.insert(x, ","); + } + currency.insert(0, "$"); // Insert dollar sign +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-3.cpp b/SourceCode/Chapter 10/Pr10-3.cpp new file mode 100755 index 0000000..64f9a3a --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-3.cpp @@ -0,0 +1,40 @@ +// This program calculates the area of a circle. It asks the user +// if he or she wishes to continue. A loop that demonstrates the +// toupper function repeats until the user enters 'y', 'Y', +// 'n', or 'N'. +#include +#include +#include +using namespace std; + +int main() +{ + const double PI = 3.14159; // Constant for Pi + double radius; // The circle's radius + char goAgain; // To hold Y or N + + cout << "This program calculates the area of a circle.\n"; + cout << fixed << setprecision(2); + + do + { + // Get the radius and display the area. + cout << "Enter the circle's radius: "; + cin >> radius; + cout << "The area is " << (PI * radius * radius); + cout << endl; + + // Does the user want to do this again? + cout << "Calculate another? (Y or N) "; + cin >> goAgain; + + // Validate the input. + while (toupper(goAgain) != 'Y' && toupper(goAgain) != 'N') + { + cout << "Please enter Y or N: "; + cin >> goAgain; + } + + } while (toupper(goAgain) == 'Y'); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-4.cpp b/SourceCode/Chapter 10/Pr10-4.cpp new file mode 100755 index 0000000..40da4ef --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-4.cpp @@ -0,0 +1,16 @@ +// This program contains string literals. +#include +using namespace std; + +int main() +{ + char again; + + do + { + cout << "C++ programming is great fun!" << endl; + cout << "Do you want to see the message again? "; + cin >> again; + } while (again == 'Y' || again == 'y'); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-5.cpp b/SourceCode/Chapter 10/Pr10-5.cpp new file mode 100755 index 0000000..a317b00 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-5.cpp @@ -0,0 +1,24 @@ +// This program displays a string stored in a char array. +#include +using namespace std; + +int main() +{ + const int SIZE = 80; // Array size + char line[SIZE]; // To hold a line of input + int count = 0; // Loop counter variable + + // Get a line of input. + cout << "Enter a sentence of no more than " + << (SIZE - 1) << " characters:\n"; + cin.getline(line, SIZE); + + // Display the input one character at a time. + cout << "The sentence you entered is:\n"; + while (line[count] != '\0') + { + cout << line[count]; + count++; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-6.cpp b/SourceCode/Chapter 10/Pr10-6.cpp new file mode 100755 index 0000000..ec53374 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-6.cpp @@ -0,0 +1,44 @@ +// This program uses the strstr function to search an array. +#include +#include // For strstr +using namespace std; + +int main() +{ + // Constants for array lengths + const int NUM_PRODS = 5; // Number of products + const int LENGTH = 27; // String length + + // Array of products + char products[NUM_PRODS][LENGTH] = + { "TV327 31 inch Television", + "CD257 CD Player", + "TA677 Answering Machine", + "CS109 Car Stereo", + "PC955 Personal Computer" }; + + char lookUp[LENGTH]; // To hold user's input + char *strPtr = nullptr; // To point to the found product + int index; // Loop counter + + // Prompt the usr for a product number. + cout << "\tProduct Database\n\n"; + cout << "Enter a product number to search for: "; + cin.getline(lookUp, LENGTH); + + // Search the array for a matching substring + for (index = 0; index < NUM_PRODS; index++) + { + strPtr = strstr(products[index], lookUp); + if (strPtr != nullptr) + break; + } + + // If a matching substring was found, display the product info. + if (strPtr != nullptr) + cout << products[index] << endl; + else + cout << "No matching product was found.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-7.cpp b/SourceCode/Chapter 10/Pr10-7.cpp new file mode 100755 index 0000000..879f9ba --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-7.cpp @@ -0,0 +1,26 @@ +// This program tests two C-strings for equality +// using the strcmp function. +#include +#include +using namespace std; + +int main() +{ + // Two arrays for two strings. + const int LENGTH = 40; + char firstString[LENGTH], secondString[LENGTH]; + + // Read two strings. + cout << "Enter a string: "; + cin.getline(firstString, LENGTH); + cout << "Enter another string: "; + cin.getline(secondString, LENGTH); + + // Compare the strings for equality with strcmp. + if (strcmp(firstString, secondString) == 0) + cout << "You entered the same string twice.\n"; + else + cout << "The strings are not the same.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-8.cpp b/SourceCode/Chapter 10/Pr10-8.cpp new file mode 100755 index 0000000..2bb9b1c --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-8.cpp @@ -0,0 +1,38 @@ +// This program uses strcmp to compare the string entered +// by the user with the valid stereo part numbers. +#include +#include +#include +using namespace std; + +int main() +{ + // Price of parts. + const double A_PRICE = 249.0, + B_PRICE = 299.0; + + // Character array for part number. + const int PART_LENGTH = 8; + char partNum[PART_LENGTH]; + + // Instruct the user to enter a part number. + cout << "The stereo part numbers are:\n" + << "\tBoom Box, part number S147-29A\n" + << "\tShelf Model, part number S147-29B\n" + << "Enter the part number of the stereo you\n" + << "wish to purchase: "; + + // Read a part number of at most 8 characters. + cin >> partNum; + + // Determine what user entered using strcmp + // and print its price. + cout << showpoint << fixed << setprecision(2); + if (strcmp(partNum, "S147-29A") == 0) + cout << "The price is $" << A_PRICE << endl; + else if (strcmp(partNum, "S147-29B") == 0) + cout << "The price is $" << B_PRICE << endl; + else + cout << partNum << " is not a valid part number.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-9.cpp b/SourceCode/Chapter 10/Pr10-9.cpp new file mode 100755 index 0000000..a38ccd3 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-9.cpp @@ -0,0 +1,29 @@ +// This program uses the return value of strcmp to +// alphabetically sort two strings entered by the user. +#include +#include +using namespace std; + +int main() +{ + // Two arrays to hold two strings. + const int NAME_LENGTH = 30; + char name1[NAME_LENGTH], name2[NAME_LENGTH]; + + // Read two strings. + cout << "Enter a name (last name first): "; + cin.getline(name1, NAME_LENGTH); + cout << "Enter another name: "; + cin.getline(name2, NAME_LENGTH); + + // Print the two strings in alphabetical order. + cout << "Here are the names sorted alphabetically:\n"; + if (strcmp(name1, name2) < 0) + cout << name1 << endl << name2 << endl; + else if (strcmp(name1, name2) > 0) + cout << name2 << endl << name1 << endl; + else + cout << "You entered the same name twice!\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-1.cpp b/SourceCode/Chapter 11/Pr11-1.cpp new file mode 100755 index 0000000..524fd32 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-1.cpp @@ -0,0 +1,49 @@ +// This program demonstrates the use of structures. +#include +#include +#include +using namespace std; + +struct PayRoll +{ + int empNumber; // Employee number + string name; // Employee's name + double hours; // Hours worked + double payRate; // Hourly payRate + double grossPay; // Gross Pay +}; + +int main() +{ + PayRoll employee; // employee is a PayRoll structure. + + // Get the employee's number. + cout << "Enter the employee's number: "; + cin >> employee.empNumber; + + // Get the employee's name. + cout << "Enter the employee's name: "; + cin.ignore(); // To skip the remaining '\n' character + getline(cin, employee.name); + + // Get the hours worked by the employee. + cout << "How many hours did the employee work? "; + cin >> employee.hours; + + // Get the employee's hourly pay rate. + cout << "What is the employee's hourly payRate? "; + cin >> employee.payRate; + + // Calculate the employee's gross pay. + employee.grossPay = employee.hours * employee.payRate; + + // Display the employee data. + cout << "Here is the employee's payroll data:\n"; + cout << "name: " << employee.name << endl; + cout << "Number: " << employee.empNumber << endl; + cout << "hours worked: " << employee.hours << endl; + cout << "Hourly payRate: " << employee.payRate << endl; + cout << fixed << showpoint << setprecision(2); + cout << "Gross Pay: $" << employee.grossPay << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-10.cpp b/SourceCode/Chapter 11/Pr11-10.cpp new file mode 100755 index 0000000..ce0b6f9 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-10.cpp @@ -0,0 +1,57 @@ +// This program demonstrates an anonymous union. +#include +#include +using namespace std; + +int main() +{ + union // Anonymous union + { + int hours; + float sales; + }; + + char payType; // To hold the pay type + float payRate; // Hourly pay rate + float grossPay; // Gross pay + + cout << fixed << showpoint << setprecision(2); + cout << "This program calculates either hourly wages or\n"; + cout << "sales commission.\n"; + + // Get the pay type, hourly or commission. + cout << "Enter H for hourly wages or C for commission: "; + cin >> payType; + + // Determine the gross pay, depending on the pay type. + if (payType == 'H' || payType == 'h') + { + // This is an hourly paid employee. Get the + // pay rate and hours worked. + cout << "What is the hourly pay rate? "; + cin >> payRate; + cout << "How many hours were worked? "; + cin >> hours; // Anonymous union member + + // Calculate and display the gross pay. + grossPay = hours * payRate; + cout << "Gross pay: $" << grossPay << endl; + } + else if (payType == 'C' || payType == 'c') + { + // This is a commission-paid employee. Get the + // amount of sales. + cout << "What are the total sales for this employee? "; + cin >> sales; // Anonymous union member + + // Calculate and display the gross pay. + grossPay = sales * 0.10; + cout << "Gross pay: $" << grossPay << endl; + } + else + { + // The user made an invalid selection. + cout << payType << " is not a valid selection.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-11.cpp b/SourceCode/Chapter 11/Pr11-11.cpp new file mode 100755 index 0000000..318c85c --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-11.cpp @@ -0,0 +1,32 @@ +// This program demonstrates an enumerated data type. +#include +#include +using namespace std; + +enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; + +int main() +{ + const int NUM_DAYS = 5; // The number of days + double sales[NUM_DAYS]; // To hold sales for each day + double total = 0.0; // Accumulator + int index; // Loop counter + + // Get the sales for each day. + for (index = MONDAY; index <= FRIDAY; index++) + { + cout << "Enter the sales for day " + << index << ": "; + cin >> sales[index]; + } + + // Calculate the total sales. + for (index = MONDAY; index <= FRIDAY; index++) + total += sales[index]; + + // Display the total. + cout << "The total sales are $" << setprecision(2) + << fixed << total << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-12.cpp b/SourceCode/Chapter 11/Pr11-12.cpp new file mode 100755 index 0000000..0c5b2e9 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-12.cpp @@ -0,0 +1,34 @@ +// This program demonstrates an enumerated data type. +#include +#include +using namespace std; + +enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; + +int main() +{ + const int NUM_DAYS = 5; // The number of days + double sales[NUM_DAYS]; // To hold sales for each day + double total = 0.0; // Accumulator + Day workDay; // Loop counter + + // Get the sales for each day. + for (workDay = MONDAY; workDay <= FRIDAY; + workDay = static_cast(workDay + 1)) + { + cout << "Enter the sales for day " + << workDay << ": "; + cin >> sales[workDay]; + } + + // Calcualte the total sales. + for (workDay = MONDAY; workDay <= FRIDAY; + workDay = static_cast(workDay + 1)) + total += sales[workDay]; + + // Display the total. + cout << "The total sales are $" << setprecision(2) + << fixed << total << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-13.cpp b/SourceCode/Chapter 11/Pr11-13.cpp new file mode 100755 index 0000000..90490c0 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-13.cpp @@ -0,0 +1,60 @@ +// This program demonstrates an enumerated data type. +#include +#include +using namespace std; + +enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; + +// Function prototype +void displayDayName(Day); + +int main() +{ + const int NUM_DAYS = 5; // The number of days + double sales[NUM_DAYS]; // To hold sales for each day + double total = 0.0; // Accumulator + Day workDay; // Loop counter + + // Get the sales for each day. + for (workDay = MONDAY; workDay <= FRIDAY; + workDay = static_cast(workDay + 1)) + { + cout << "Enter the sales for day "; + displayDayName(workDay); + cout << ": "; + cin >> sales[workDay]; + } + + // Calcualte the total sales. + for (workDay = MONDAY; workDay <= FRIDAY; + workDay = static_cast(workDay + 1)) + total += sales[workDay]; + + // Display the total. + cout << "The total sales are $" << setprecision(2) + << fixed << total << endl; + + return 0; +} + +//********************************************************** +// Definition of the displayDayName function * +// This function accepts an argumet of the Day type and * +// displays the corresponding name of the day. * +//********************************************************** + +void displayDayName(Day d) +{ + switch(d) + { + case MONDAY : cout << "Monday"; + break; + case TUESDAY : cout << "Tuesday"; + break; + case WEDNESDAY : cout << "Wednesday"; + break; + case THURSDAY : cout << "Thursday"; + break; + case FRIDAY : cout << "Friday"; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-14.cpp b/SourceCode/Chapter 11/Pr11-14.cpp new file mode 100755 index 0000000..c12965b --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-14.cpp @@ -0,0 +1,21 @@ +// This program demonstrates an enumerated data type. +#include +#include +using namespace std; + +int main() +{ + enum Water { FREEZING = 32, BOILING = 212 }; + int waterTemp; // To hold the water temperature + + cout << "Enter the current water temperature: "; + cin >> waterTemp; + if (waterTemp <= FREEZING) + cout << "The water is frozen.\n"; + else if (waterTemp >= BOILING) + cout << "The water is boiling.\n"; + else + cout << "The water is not frozen or boiling.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-2.cpp b/SourceCode/Chapter 11/Pr11-2.cpp new file mode 100755 index 0000000..f13f557 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-2.cpp @@ -0,0 +1,38 @@ +// This program stores data about a circle in a structure. +#include +#include // For the pow function +#include +using namespace std; + +// Constant for Pi. +const double PI = 3.14159; + +// Structure declaration +struct Circle +{ + double radius; // A circle's radius + double diameter; // A circle's diameter + double area; // A circle's area +}; + +int main() +{ + Circle c; // Define a structure variable + + // Get the circle's diameter. + cout << "Enter the diameter of a circle: "; + cin >> c.diameter; + + // Calculate the circle's radius. + c.radius = c.diameter / 2; + + // Calculate the circle's area. + c.area = PI * pow(c.radius, 2.0); + + // Display the circle data. + cout << fixed << showpoint << setprecision(2); + cout << "The radius and area of the circle are:\n"; + cout << "Radius: " << c.radius << endl; + cout << "Area: " << c.area << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-3.cpp b/SourceCode/Chapter 11/Pr11-3.cpp new file mode 100755 index 0000000..ee4fe65 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-3.cpp @@ -0,0 +1,40 @@ +// This program demonstrates partially initialized +// structure variables. +#include +#include +#include +using namespace std; + +struct EmployeePay +{ + string name; // Employee name + int empNum; // Employee number + double payRate; // Hourly pay rate + double hours; // Hours worked + double grossPay; // Gross pay +}; + +int main() +{ + EmployeePay employee1 = {"Betty Ross", 141, 18.75}; + EmployeePay employee2 = {"Jill Sandburg", 142, 17.50}; + + cout << fixed << showpoint << setprecision(2); + + // Calculate pay for employee1 + cout << "Name: " << employee1.name << endl; + cout << "Employee Number: " << employee1.empNum << endl; + cout << "Enter the hours worked by this employee: "; + cin >> employee1.hours; + employee1.grossPay = employee1.hours * employee1.payRate; + cout << "Gross Pay: " << employee1.grossPay << endl << endl; + + // Calculate pay for employee2 + cout << "Name: " << employee2.name << endl; + cout << "Employee Number: " << employee2.empNum << endl; + cout << "Enter the hours worked by this employee: "; + cin >> employee2.hours; + employee2.grossPay = employee2.hours * employee2.payRate; + cout << "Gross Pay: " << employee2.grossPay << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-4.cpp b/SourceCode/Chapter 11/Pr11-4.cpp new file mode 100755 index 0000000..c54a6af --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-4.cpp @@ -0,0 +1,47 @@ +// This program uses an array of structures. +#include +#include +using namespace std; + +struct PayInfo +{ + int hours; // Hours Worked + double payRate; // Hourly Pay Rate +}; + +int main() +{ + const int NUM_WORKERS = 3; // Number of workers + PayInfo workers[NUM_WORKERS]; // Array of structures + int index; // Loop counter + + // Get employee pay data. + cout << "Enter the hours worked by " << NUM_WORKERS + << " employees and their hourly rates.\n"; + + for (index = 0; index < NUM_WORKERS; index++) + { + // Get the hours worked by an employee. + cout << "Hours worked by employee #" << (index + 1); + cout << ": "; + cin >> workers[index].hours; + + // Get the employee's hourly pay rate. + cout << "Hourly pay rate for employee #"; + cout << (index + 1) << ": "; + cin >> workers[index].payRate; + cout << endl; + } + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (index = 0; index < NUM_WORKERS; index++) + { + double gross; + gross = workers[index].hours * workers[index].payRate; + cout << "Employee #" << (index + 1); + cout << ": $" << gross << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-5.cpp b/SourceCode/Chapter 11/Pr11-5.cpp new file mode 100755 index 0000000..6e98928 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-5.cpp @@ -0,0 +1,77 @@ +// This program uses nested structures. +#include +#include +using namespace std; + +// The Date structure holds data about a date. +struct Date +{ + int month; + int day; + int year; +}; + +// The Place structure holds a physical address. +struct Place +{ + string address; + string city; + string state; + string zip; +}; + +// The EmployeeInfo structure holds an employee's data. +struct EmployeeInfo +{ + string name; + int employeeNumber; + Date birthDate; // Nested structure + Place residence; // Nested structure +}; + +int main() +{ + // Define a structure variable to hold info about the manager. + EmployeeInfo manager; + + // Get the manager's name and employee number + cout << "Enter the manager's name: "; + getline(cin, manager.name); + cout << "Enter the manager's employee number: "; + cin >> manager.employeeNumber; + + // Get the manager's birth date + cout << "Now enter the manager's date of birth.\n"; + cout << "Month (up to 2 digits): "; + cin >> manager.birthDate.month; + cout << "Day (up to 2 digits): "; + cin >> manager.birthDate.day; + cout << "Year: "; + cin >> manager.birthDate.year; + cin.ignore(); // Skip the remaining newline character + + // Get the manager's residence information + cout << "Enter the manager's street address: "; + getline(cin, manager.residence.address); + cout << "City: "; + getline(cin, manager.residence.city); + cout << "State: "; + getline(cin, manager.residence.state); + cout << "ZIP Code: "; + getline(cin, manager.residence.zip); + + // Display the information just entered + cout << "\nHere is the manager's information:\n"; + cout << manager.name << endl; + cout << "Employee number " << manager.employeeNumber << endl; + cout << "Date of birth: "; + cout << manager.birthDate.month << "-"; + cout << manager.birthDate.day << "-"; + cout << manager.birthDate.year << endl; + cout << "Place of residence:\n"; + cout << manager.residence.address << endl; + cout << manager.residence.city << ", "; + cout << manager.residence.state << " "; + cout << manager.residence.zip << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-6.cpp b/SourceCode/Chapter 11/Pr11-6.cpp new file mode 100755 index 0000000..67c40fe --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-6.cpp @@ -0,0 +1,68 @@ +// This program has functions that accept structure variables +// as arguments. +#include +#include +#include +using namespace std; + +struct InventoryItem +{ + int partNum; // Part number + string description; // Item description + int onHand; // Units on hand + double price; // Unit price +}; + +// Function Prototypes +void getItem(InventoryItem&); // Argument passed by reference +void showItem(InventoryItem); // Argument passed by value + +int main() +{ + InventoryItem part; + + getItem(part); + showItem(part); + return 0; +} + +//*********************************************************** +// Definition of function getItem. This function uses * +// a structure reference variable as its parameter. It asks * +// the user for information to store in the structure. * +//*********************************************************** + +void getItem(InventoryItem &p) // Uses a reference parameter +{ + // Get the part number. + cout << "Enter the part number: "; + cin >> p.partNum; + + // Get the part description. + cout << "Enter the part description: "; + cin.ignore(); // Ignore the remaining newline character + getline(cin, p.description); + + // Get the quantity on hand. + cout << "Enter the quantity on hand: "; + cin >> p.onHand; + + // Get the unit price. + cout << "Enter the unit price: "; + cin >> p.price; +} + +//*********************************************************** +// Definition of function showItem. This function accepts * +// an argument of the InventoryItem structure type. The * +// contents of the structure is displayed. * +//*********************************************************** + +void showItem(InventoryItem p) +{ + cout << fixed << showpoint << setprecision(2); + cout << "Part Number: " << p.partNum << endl; + cout << "Description: " << p.description << endl; + cout << "Units On Hand: " << p.onHand << endl; + cout << "Price: $" << p.price << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-7.cpp b/SourceCode/Chapter 11/Pr11-7.cpp new file mode 100755 index 0000000..0b51753 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-7.cpp @@ -0,0 +1,60 @@ +// This program uses a function to return a structure. This +// is a modification of Program 11-2. +#include +#include +#include // For the pow function +using namespace std; + +// Constant for Pi. +const double PI = 3.14159; + +// Structure declaration +struct Circle +{ + double radius; // A circle's radius + double diameter; // A circle's diameter + double area; // A circle's area +}; + +// Function prototype +Circle getInfo(); + +int main() +{ + Circle c; // Define a structure variable + + // Get data about the circle. + c = getInfo(); + + // Calculate the circle's area. + c.area = PI * pow(c.radius, 2.0); + + // Display the circle data. + cout << "The radius and area of the circle are:\n"; + cout << fixed << setprecision(2); + cout << "Radius: " << c.radius << endl; + cout << "Area: " << c.area << endl; + return 0; +} + +//*************************************************************** +// Definition of function getInfo. This function uses a local * +// variable, tempCircle, which is a circle structure. The user * +// enters the diameter of the circle, which is stored in * +// tempCircle.diameter. The function then calculates the radius * +// which is stored in tempCircle.radius. tempCircle is then * +// returned from the function. * +//*************************************************************** + +Circle getInfo() +{ + Circle tempCircle; // Temporary structure variable + + // Store circle data in the temporary variable. + cout << "Enter the diameter of a circle: "; + cin >> tempCircle.diameter; + tempCircle.radius = tempCircle.diameter / 2.0; + + // Return the temporary variable. + return tempCircle; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-8.cpp b/SourceCode/Chapter 11/Pr11-8.cpp new file mode 100755 index 0000000..2cfffbf --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-8.cpp @@ -0,0 +1,59 @@ +// This program demonstrates a function that uses a +// pointer to a structure variable as a parameter. +#include +#include +#include +using namespace std; + +struct Student +{ + string name; // Student's name + int idNum; // Student ID number + int creditHours; // Credit hours enrolled + double gpa; // Current GPA +}; + +void getData(Student *); // Function prototype + +int main() +{ + Student freshman; + + // Get the student data. + cout << "Enter the following student data:\n"; + getData(&freshman); // Pass the address of freshman. + cout << "\nHere is the student data you entered:\n"; + + // Now display the data stored in freshman + cout << setprecision(3); + cout << "Name: " << freshman.name << endl; + cout << "ID Number: " << freshman.idNum << endl; + cout << "Credit Hours: " << freshman.creditHours << endl; + cout << "GPA: " << freshman.gpa << endl; + return 0; +} + +//******************************************************* +// Definition of function getData. Uses a pointer to a * +// Student structure variable. The user enters student * +// information, which is stored in the variable. * +//******************************************************* + +void getData(Student *s) +{ + // Get the student name. + cout << "Student name: "; + getline(cin, s->name); + + // Get the student ID number. + cout << "Student ID Number: "; + cin >> s->idNum; + + // Get the credit hours enrolled. + cout << "Credit Hours Enrolled: "; + cin >> s->creditHours; + + // Get the GPA. + cout << "Current GPA: "; + cin >> s->gpa; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-9.cpp b/SourceCode/Chapter 11/Pr11-9.cpp new file mode 100755 index 0000000..0fa03d7 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-9.cpp @@ -0,0 +1,58 @@ +// This program demonstrates a union. +#include +#include +using namespace std; + +union PaySource +{ + int hours; // Hours worked + float sales; // Amount of sales +}; + +int main() +{ + PaySource employee1; // Define a union variable + char payType; // To hold the pay type + float payRate; // Hourly pay rate + float grossPay; // Gross pay + + cout << fixed << showpoint << setprecision(2); + cout << "This program calculates either hourly wages or\n"; + cout << "sales commission.\n"; + + // Get the pay type, hourly or commission. + cout << "Enter H for hourly wages or C for commission: "; + cin >> payType; + + // Determine the gross pay, depending on the pay type. + if (payType == 'H' || payType == 'h') + { + // This is an hourly paid employee. Get the + // pay rate and hours worked. + cout << "What is the hourly pay rate? "; + cin >> payRate; + cout << "How many hours were worked? "; + cin >> employee1.hours; + + // Calculate and display the gross pay. + grossPay = employee1.hours * payRate; + cout << "Gross pay: $" << grossPay << endl; + } + else if (payType == 'C' || payType == 'c') + { + // This is a commission-paid employee. Get the + // amount of sales. + cout << "What are the total sales for this employee? "; + cin >> employee1.sales; + + // Calculate and display the gross pay. + grossPay = employee1.sales * 0.10; + cout << "Gross pay: $" << grossPay << endl; + } + else + { + // The user made an invalid selection. + cout << payType << " is not a valid selection.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Inventory.dat b/SourceCode/Chapter 12/Inventory.dat new file mode 100755 index 0000000..382ddfd Binary files /dev/null and b/SourceCode/Chapter 12/Inventory.dat differ diff --git a/SourceCode/Chapter 12/Pr12-1.cpp b/SourceCode/Chapter 12/Pr12-1.cpp new file mode 100755 index 0000000..a1cde0c --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-1.cpp @@ -0,0 +1,20 @@ +// This program uses an fstream object to write data to a file. +#include +#include +using namespace std; + +int main() +{ + fstream dataFile; + + cout << "Opening file...\n"; + dataFile.open("demofile.txt", ios::out); // Open for output + cout << "Now writing data to the file.\n"; + dataFile << "Jones\n"; // Write line 1 + dataFile << "Smith\n"; // Write line 2 + dataFile << "Willis\n"; // Write line 3 + dataFile << "Davis\n"; // Write line 4 + dataFile.close(); // Close the file + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-10.cpp b/SourceCode/Chapter 12/Pr12-10.cpp new file mode 100755 index 0000000..f4eab8b --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-10.cpp @@ -0,0 +1,44 @@ +// This program asks the user for a file name. The file is +// opened and its contents are displayed on the screen. +#include +#include +#include +using namespace std; + +int main() +{ + string fileName; // To hold the file name + char ch; // To hold a character + fstream file; // File stream object + + // Get the file name + cout << "Enter a file name: "; + cin >> fileName; + + // Open the file. + file.open(fileName, ios::in); + + // If the file was successfully opened, continue. + if (file) + { + // Get a character from the file. + file.get(ch); + + // While the last read opeation was + // successful, continue. + while (file) + { + // Display the last character read. + cout << ch; + + // Read the next character + file.get(ch); + } + + // Close the file. + file.close(); + } + else + cout << fileName << " could not be opened.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-11.cpp b/SourceCode/Chapter 12/Pr12-11.cpp new file mode 100755 index 0000000..49e3712 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-11.cpp @@ -0,0 +1,29 @@ +// This program demonstrates the put member function. +#include +#include +using namespace std; + +int main() +{ + char ch; // To hold a character + + // Open the file for output. + fstream dataFile("sentence.txt", ios::out); + + cout << "Type the sentence and be sure to end it with a "; + cout << "period.\n"; + + // Get a sentence from the user one character at a time + // and write each character to the file. + cin.get(ch); + while (ch != '.') + { + dataFile.put(ch); + cin.get(ch); + } + dataFile.put(ch); // Write the period. + + // Close the file. + dataFile.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-12.cpp b/SourceCode/Chapter 12/Pr12-12.cpp new file mode 100755 index 0000000..d2e7953 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-12.cpp @@ -0,0 +1,50 @@ +// This program demonstrates reading from one file and writing +// to a second file. +#include +#include +#include +#include // Needed for the toupper function. +using namespace std; + +int main() +{ + string fileName; // To hold the file name + char ch; // To hold a character + ifstream inFile; // Input file + + // Open a file for output. + ofstream outFile("out.txt"); + + // Get the input file name. + cout << "Enter a file name: "; + cin >> fileName; + + // Open the file for input. + inFile.open(fileName); + + // If the input file opened successfully, continue. + if (inFile) + { + // Read a char from file 1. + inFile.get(ch); + + // While the last read operation was + // successful, continue. + while (inFile) + { + // Write uppercase char to file 2. + outFile.put(toupper(ch)); + + // Read another char from file 1. + inFile.get(ch); + } + + // Close the two files. + inFile.close(); + outFile.close(); + cout << "File conversion done.\n"; + } + else + cout << "Cannot open " << fileName << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-13.cpp b/SourceCode/Chapter 12/Pr12-13.cpp new file mode 100755 index 0000000..9a2ccb8 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-13.cpp @@ -0,0 +1,37 @@ +// This program uses the write and read functions. +#include +#include +using namespace std; + +int main() +{ + const int SIZE = 4; + char data[SIZE] = { 'A', 'B', 'C', 'D' }; + fstream file; + + // Open the file for output in binary mode. + file.open("test.dat", ios::out | ios::binary); + + // Write the contents of the array to the file. + cout << "Writing the characters to the file.\n"; + file.write(data, sizeof(data)); + + // Close the file. + file.close(); + + // Open the file for input in binary mode. + file.open("test.dat", ios::in | ios::binary); + + // Read the contents of the file into the array. + cout << "Now reading the data back into memory.\n"; + file.read(data, sizeof(data)); + + // Display the contents of the array. + for (int count = 0; count < SIZE; count++) + cout << data[count] << " "; + cout << endl; + + // Close the file. + file.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-14.cpp b/SourceCode/Chapter 12/Pr12-14.cpp new file mode 100755 index 0000000..d1a9fa0 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-14.cpp @@ -0,0 +1,37 @@ +// This program uses the write and read functions. +#include +#include +using namespace std; + +int main() +{ + const int SIZE = 10; + fstream file; + int numbers[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + + // Open the file for output in binary mode. + file.open("numbers.dat", ios::out | ios::binary); + + // Write the contents of the array to the file. + cout << "Writing the data to the file.\n"; + file.write(reinterpret_cast(numbers), sizeof(numbers)); + + // Close the file. + file.close(); + + // Open the file for input in binary mode. + file.open("numbers.dat", ios::in | ios::binary); + + // Read the contents of the file into the array. + cout << "Now reading the data back into memory.\n"; + file.read(reinterpret_cast(numbers), sizeof(numbers)); + + // Display the contents of the array. + for (int count = 0; count < SIZE; count++) + cout << numbers[count] << " "; + cout << endl; + + // Close the file. + file.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-15.cpp b/SourceCode/Chapter 12/Pr12-15.cpp new file mode 100755 index 0000000..917d87b --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-15.cpp @@ -0,0 +1,57 @@ +// This program uses a structure variable to store a record to a file. +#include +#include +using namespace std; + +// Array sizes +const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14; + +// Declare a structure for the record. +struct Info +{ + char name[NAME_SIZE]; + int age; + char address1[ADDR_SIZE]; + char address2[ADDR_SIZE]; + char phone[PHONE_SIZE]; +}; + +int main() +{ + Info person; // To hold info about a person + char again; // To hold Y or N + + // Open a file for binary output. + fstream people("people.dat", ios::out | ios::binary); + + do + { + // Get data about a person. + cout << "Enter the following data about a " + << "person:\n"; + cout << "Name: "; + cin.getline(person.name, NAME_SIZE); + cout << "Age: "; + cin >> person.age; + cin.ignore(); // Skip over the remaining newline. + cout << "Address line 1: "; + cin.getline(person.address1, ADDR_SIZE); + cout << "Address line 2: "; + cin.getline(person.address2, ADDR_SIZE); + cout << "Phone: "; + cin.getline(person.phone, PHONE_SIZE); + + // Write the contents of the person structure to the file. + people.write(reinterpret_cast(&person), + sizeof(person)); + + // Determine wheter the user wants to write another record. + cout << "Do you want to enter another record? "; + cin >> again; + cin.ignore(); // Skip over the remaining newline. + } while (again == 'Y' || again == 'y'); + + // Close the file. + people.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-16.cpp b/SourceCode/Chapter 12/Pr12-16.cpp new file mode 100755 index 0000000..8d78b8e --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-16.cpp @@ -0,0 +1,68 @@ +// This program uses a structure variable to read a record from a file. +#include +#include +using namespace std; + +// Array sizes +const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14; + +// Declare a structure for the record. +struct Info +{ + char name[NAME_SIZE]; + int age; + char address1[ADDR_SIZE]; + char address2[ADDR_SIZE]; + char phone[PHONE_SIZE]; +}; + +int main() +{ + Info person; // To hold info about a person + fstream people; // File stream object + + // Open a file for input in binary mode. + people.open("people.dat", ios::in | ios::binary); + + // Test for errors. + if (!people) + { + cout << "Error opening file. Program aborting.\n"; + return 0; + } + + cout << "Here are the people in the file: \n\n"; + // Read the first record from the file. + people.read(reinterpret_cast(&person), + sizeof(person)); + + // While not at the end of the file, + // display the records. + while (!people.eof()) + { + // Display the record. + cout << "Name: "; + cout << person.name << endl; + cout << "Age: "; + cout << person.age << endl; + cout << "Address line 1: "; + cout << person.address1 << endl; + cout << "Address line 2: "; + cout << person.address2 << endl; + cout << "Phone: "; + cout << person.phone << endl; + + // Wait for the user to press the Enter key. + cout << "\nPress the Enter key to see the next record.\n"; + cin.get(); + + // Read the next record from the file. + people.read(reinterpret_cast(&person), + sizeof(person)); + } + + // Close the file. + cout << "That's all the data in the file!\n"; + people.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-17.cpp b/SourceCode/Chapter 12/Pr12-17.cpp new file mode 100755 index 0000000..7e16121 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-17.cpp @@ -0,0 +1,33 @@ +// This program demonstrates the seekg function. +#include +#include +using namespace std; + +int main() +{ + char ch; // To hold a character + + // Open the file for input. + fstream file("letters.txt", ios::in); + + // Move to byte 5 from the beginning of the file + // (the 6th byte) and read the character there. + file.seekg(5L, ios::beg); + file.get(ch); + cout << "Byte 5 from beginning: " << ch << endl; + + // Move to the 10th byte from the end of the file + // and read the character there. + file.seekg(-10L, ios::end); + file.get(ch); + cout << "10th byte from end: " << ch << endl; + + // Move to byte 3 from the current position + // (the 4th byte) and read the character there. + file.seekg(3L, ios::cur); + file.get(ch); + cout << "Byte 3 from current: " << ch << endl; + + file.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-18.cpp b/SourceCode/Chapter 12/Pr12-18.cpp new file mode 100755 index 0000000..4082cd7 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-18.cpp @@ -0,0 +1,82 @@ +// This program randomly reads a record of data from a file. +#include +#include +using namespace std; + +const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14; + +// Declare a structure for the record. +struct Info +{ + char name[NAME_SIZE]; + int age; + char address1[ADDR_SIZE]; + char address2[ADDR_SIZE]; + char phone[PHONE_SIZE]; +}; + +// Function Prototypes +long byteNum(int); +void showRec(Info); + +int main() +{ + Info person; // To hold info about a person + fstream people; // File stream object + + // Open the file for input in binary mode. + people.open("people.dat", ios::in | ios::binary); + + // Test for errors. + if (!people) + { + cout << "Error opening file. Program aborting.\n"; + return 0; + } + + // Read and display record 1 (the second record). + cout << "Here is record 1:\n"; + people.seekg(byteNum(1), ios::beg); + people.read(reinterpret_cast(&person), sizeof(person)); + showRec(person); + + // Read and display record 0 (the first record). + cout << "\nHere is record 0:\n"; + people.seekg(byteNum(0), ios::beg); + people.read(reinterpret_cast(&person), sizeof(person)); + showRec(person); + + // Close the file. + people.close(); + return 0; +} + +//************************************************************ +// Definition of function byteNum. Accepts an integer as * +// its argument. Returns the byte number in the file of the * +// record whose number is passed as the argument. * +//************************************************************ + +long byteNum(int recNum) +{ + return sizeof(Info) * recNum; +} + +//************************************************************ +// Definition of function showRec. Accepts an Info structure * +// as its argument, and displays the structure's contents. * +//************************************************************ + +void showRec(Info record) +{ + cout << "Name: "; + cout << record.name << endl; + cout << "Age: "; + cout << record.age << endl; + cout << "Address line 1: "; + cout << record.address1 << endl; + cout << "Address line 2: "; + cout << record.address2 << endl; + cout << "Phone: "; + cout << record.phone << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-19.cpp b/SourceCode/Chapter 12/Pr12-19.cpp new file mode 100755 index 0000000..5a2fda4 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-19.cpp @@ -0,0 +1,53 @@ +// This program demonstrates the tellg function. +#include +#include +using namespace std; + +int main() +{ + long offset; // To hold an offset amount + long numBytes; // To hold the file size + char ch; // To hold a character + char again; // To hold Y or N + + // Open the file for input. + fstream file("letters.txt", ios::in); + + // Determine the number of bytes in the file. + file.seekg(0L, ios::end); + numBytes = file.tellg(); + cout << "The file has " << numBytes << " bytes.\n"; + + // Go back to the beginning of the file. + file.seekg(0L, ios::beg); + + // Let the user move around within the file. + do + { + // Display the current read position. + cout << "Currently at position " << file.tellg() << endl; + + // Get a byte number from the user. + cout << "Enter an offset from the beginning of the file: "; + cin >> offset; + + // Move the read position to that byte, read the + // character there, and display it. + if (offset >= numBytes) // Past the end of the file? + cout << "Cannot read past the end of the file.\n"; + else + { + file.seekg(offset, ios::beg); + file.get(ch); + cout << "Character read: " << ch << endl; + } + + // Does the user want to try this again? + cout << "Do it again? "; + cin >> again; + } while (again == 'Y' || again == 'y'); + + // Close the file. + file.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-2.cpp b/SourceCode/Chapter 12/Pr12-2.cpp new file mode 100755 index 0000000..5ca5612 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-2.cpp @@ -0,0 +1,31 @@ +// This program writes data to a file, closes the file, +// then reopens the file and appends more data. +#include +#include +using namespace std; + +int main() +{ + ofstream dataFile; + + cout << "Opening file...\n"; + // Open the file in output mode. + dataFile.open("demofile.txt", ios::out); + cout << "Now writing data to the file.\n"; + dataFile << "Jones\n"; // Write line 1 + dataFile << "Smith\n"; // Write line 2 + cout << "Now closing the file.\n"; + dataFile.close(); // Close the file + + cout << "Opening the file again...\n"; + // Open the file in append mode. + dataFile.open("demofile.txt", ios::out | ios::app); + cout << "Writing more data to the file.\n"; + dataFile << "Willis\n"; // Write line 3 + dataFile << "Davis\n"; // Write line 4 + cout << "Now closing the file.\n"; + dataFile.close(); // Close the file + + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-20.cpp b/SourceCode/Chapter 12/Pr12-20.cpp new file mode 100755 index 0000000..55b6025 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-20.cpp @@ -0,0 +1,37 @@ +// This program sets up a file of blank inventory records. +#include +#include +using namespace std; + +// Constants +const int DESC_SIZE = 31; +const int NUM_RECORDS = 5; + +// Declaration of InventoryItem structure +struct InventoryItem +{ + char desc[DESC_SIZE]; + int qty; + double price; +}; + +int main() +{ + // Create an empty InventoryItem structure. + InventoryItem record = { "", 0, 0.0 }; + + // Open the file for binary output. + fstream inventory("Inventory.dat", ios::out | ios::binary); + + // Write the blank records. + for (int count = 0; count < NUM_RECORDS; count++) + { + cout << "Now writing record " << count << endl; + inventory.write(reinterpret_cast(&record), + sizeof(record)); + } + + // Close the file. + inventory.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-21.cpp b/SourceCode/Chapter 12/Pr12-21.cpp new file mode 100755 index 0000000..7594394 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-21.cpp @@ -0,0 +1,41 @@ +// This program displays the contents of the inventory file. +#include +#include +using namespace std; + +const int DESC_SIZE = 31; // Description size + +// Declaration of InventoryItem structure +struct InventoryItem +{ + char desc[DESC_SIZE]; + int qty; + double price; +}; + +int main() +{ + InventoryItem record; // To hold an inventory record + + // Open the file for binary input. + fstream inventory("Inventory.dat", ios::in | ios::binary); + + // Now read and display the records. + inventory.read(reinterpret_cast(&record), + sizeof(record)); + while (!inventory.eof()) + { + cout << "Description: "; + cout << record.desc << endl; + cout << "Quantity: "; + cout << record.qty << endl; + cout << "Price: "; + cout << record.price << endl << endl; + inventory.read(reinterpret_cast(&record), + sizeof(record)); + } + + // Close the file. + inventory.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-22.cpp b/SourceCode/Chapter 12/Pr12-22.cpp new file mode 100755 index 0000000..058619c --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-22.cpp @@ -0,0 +1,62 @@ +// This program allows the user to edit a specific record. +#include +#include +using namespace std; + +const int DESC_SIZE = 31; // Description size + +// Declaration of InventoryItem structure +struct InventoryItem +{ + char desc[DESC_SIZE]; + int qty; + double price; +}; + +int main() +{ + InventoryItem record; // To hold an inventory record + long recNum; // To hold a record number + + // Open the file in binary mode for input and output. + fstream inventory("Inventory.dat", + ios::in | ios::out | ios::binary); + + // Get the record number of the desired record. + cout << "Which record do you want to edit? "; + cin >> recNum; + + // Move to the record and read it. + inventory.seekg(recNum * sizeof(record), ios::beg); + inventory.read(reinterpret_cast(&record), + sizeof(record)); + + // Display the record contents. + cout << "Description: "; + cout << record.desc << endl; + cout << "Quantity: "; + cout << record.qty << endl; + cout << "Price: "; + cout << record.price << endl; + + // Get the new record data. + cout << "Enter the new data:\n"; + cout << "Description: "; + cin.ignore(); + cin.getline(record.desc, DESC_SIZE); + cout << "Quantity: "; + cin >> record.qty; + cout << "Price: "; + cin >> record.price; + + // Move back to the beginning of the this record's position. + inventory.seekp(recNum * sizeof(record), ios::beg); + + // Write the new record over the current record. + inventory.write(reinterpret_cast(&record), + sizeof(record)); + + // Close the file. + inventory.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-3.cpp b/SourceCode/Chapter 12/Pr12-3.cpp new file mode 100755 index 0000000..30b8ffa --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-3.cpp @@ -0,0 +1,33 @@ +// This program uses the setprecision and fixed +// manipulators to format file output. +#include +#include +#include +using namespace std; + +int main() +{ + fstream dataFile; + double num = 17.816392; + + dataFile.open("numfile.txt", ios::out); // Open in output mode + + dataFile << fixed; // Format for fixed-point notation + dataFile << num << endl; // Write the number + + dataFile << setprecision(4); // Format for 4 decimal places + dataFile << num << endl; // Write the number + + dataFile << setprecision(3); // Format for 3 decimal places + dataFile << num << endl; // Write the number + + dataFile << setprecision(2); // Format for 2 decimal places + dataFile << num << endl; // Write the number + + dataFile << setprecision(1); // Format for 1 decimal place + dataFile << num << endl; // Write the number + + cout << "Done.\n"; + dataFile.close(); // Close the file + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-4.cpp b/SourceCode/Chapter 12/Pr12-4.cpp new file mode 100755 index 0000000..7eaf9bf --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-4.cpp @@ -0,0 +1,29 @@ +// This program writes three rows of numbers to a file. +#include +#include +#include +using namespace std; + +int main() +{ + const int ROWS = 3; // Rows to write + const int COLS = 3; // Columns to write + int nums[ROWS][COLS] = { 2897, 5, 837, + 34, 7, 1623, + 390, 3456, 12 }; + fstream outFile("table.txt", ios::out); + + // Write the three rows of numbers with each + // number in a field of 8 character spaces. + for (int row = 0; row < ROWS; row++) + { + for (int col = 0; col < COLS; col++) + { + outFile << setw(8) << nums[row][col]; + } + outFile << endl; + } + outFile.close(); + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-5.cpp b/SourceCode/Chapter 12/Pr12-5.cpp new file mode 100755 index 0000000..c38d8cb --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-5.cpp @@ -0,0 +1,60 @@ +// This program demonstrates how file stream objects may +// be passed by reference to functions. +#include +#include +#include +using namespace std; + +// Function prototypes +bool openFileIn(fstream &, string); +void showContents(fstream &); + +int main() +{ + fstream dataFile; + + if (openFileIn(dataFile, "demofile.txt")) + { + cout << "File opened successfully.\n"; + cout << "Now reading data from the file.\n\n"; + showContents(dataFile); + dataFile.close(); + cout << "\nDone.\n"; + } + else + cout << "File open error!" << endl; + + return 0; +} + +//*********************************************************** +// Definition of function openFileIn. Accepts a reference * +// to an fstream object as an argument. The file is opened * +// for input. The function returns true upon success, false * +// upon failure. * +//*********************************************************** + +bool openFileIn(fstream &file, string name) +{ + file.open(name, ios::in); + if (file.fail()) + return false; + else + return true; +} + +//*********************************************************** +// Definition of function showContents. Accepts an fstream * +// reference as its argument. Uses a loop to read each name * +// from the file and displays it on the screen. * +//*********************************************************** + +void showContents(fstream &file) +{ + string line; + + while (file >> line) + { + cout << line << endl; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-6.cpp b/SourceCode/Chapter 12/Pr12-6.cpp new file mode 100755 index 0000000..7a1dc4e --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-6.cpp @@ -0,0 +1,76 @@ +// This program demonstrates the return value of the stream +// object error testing member functions. +#include +#include +using namespace std; + +// Function prototype +void showState(fstream &); + +int main() +{ + int num = 10; + + // Open the file for output. + fstream testFile("stuff.dat", ios::out); + if (testFile.fail()) + { + cout << "ERROR: cannot open the file.\n"; + return 0; + } + + // Write a value to the file. + cout << "Writing the value " << num << " to the file.\n"; + testFile << num; + + // Show the bit states. + showState(testFile); + + // Close the file. + testFile.close(); + + // Reopen the file for input. + testFile.open("stuff.dat", ios::in); + if (testFile.fail()) + { + cout << "ERROR: cannot open the file.\n"; + return 0; + } + + // Read the only value from the file. + cout << "Reading from the file.\n"; + testFile >> num; + cout << "The value " << num << " was read.\n"; + + // Show the bit states. + showState(testFile); + + // No more data in the file, but force an invalid read operation. + cout << "Forcing a bad read operation.\n"; + testFile >> num; + + // Show the bit states. + showState(testFile); + + // Close the file. + testFile.close(); + return 0; +} + +//***************************************************************** +// Definition of function showState. This function uses * +// an fstream reference as its parameter. The return values of * +// the eof(), fail(), bad(), and good() member functions are * +// displayed. The clear() function is called before the function * +// reutrns. * +//***************************************************************** + +void showState(fstream &file) +{ + cout << "File Status:\n"; + cout << " eof bit: " << file.eof() << endl; + cout << " fail bit: " << file.fail() << endl; + cout << " bad bit: " << file.bad() << endl; + cout << " good bit: " << file.good() << endl; + file.clear(); // Clear any bad bits +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-7.cpp b/SourceCode/Chapter 12/Pr12-7.cpp new file mode 100755 index 0000000..144ff11 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-7.cpp @@ -0,0 +1,34 @@ +// This program demonstrates how the >> operator should not +// be used to read data that contain whitespace characters +// from a file. +#include +#include +#include +using namespace std; + +int main() +{ + string input; // To hold file input + fstream nameFile; // File stream object + + // Open the file in input mode. + nameFile.open("murphy.txt", ios::in); + + // If the file was successfully opened, continue. + if (nameFile) + { + // Read the file contents. + while (nameFile >> input) + { + cout << input; + } + + // Close the file. + nameFile.close(); + } + else + { + cout << "ERROR: Cannot open file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-8.cpp b/SourceCode/Chapter 12/Pr12-8.cpp new file mode 100755 index 0000000..ea33e41 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-8.cpp @@ -0,0 +1,41 @@ +// This program uses the getline function to read a line of +// data from the file. +#include +#include +#include +using namespace std; + +int main() +{ + string input; // To hold file input + fstream nameFile; // File stream object + + // Open the file in input mode. + nameFile.open("murphy.txt", ios::in); + + // If the file was successfully opened, continue. + if (nameFile) + { + // Read an item from the file. + getline(nameFile, input); + + // While the last read operation + // was successful, continue. + while (nameFile) + { + // Display the last item read. + cout << input << endl; + + // Read the next item. + getline(nameFile, input); + } + + // Close the file. + nameFile.close(); + } + else + { + cout << "ERROR: Cannot open file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-9.cpp b/SourceCode/Chapter 12/Pr12-9.cpp new file mode 100755 index 0000000..7a97991 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-9.cpp @@ -0,0 +1,40 @@ +// This file demonstrates the getline function with +// a specified delimiter. +#include +#include +#include +using namespace std; + +int main() +{ + string input; // To hold file input + + // Open the file for input. + fstream dataFile("names2.txt", ios::in); + + // If the file was successfully opened, continue. + if (dataFile) + { + // Read an item using $ as a delimiter. + getline(dataFile, input, '$'); + + // While the last read operation + // was successful, continue. + while (dataFile) + { + // Display the last item read. + cout << input << endl; + + // Read an item using $ as a delimiter. + getline(dataFile, input, '$'); + } + + // Close the file. + dataFile.close(); + } + else + { + cout << "ERROR: Cannot open file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/demofile.txt b/SourceCode/Chapter 12/demofile.txt new file mode 100755 index 0000000..7a19b32 --- /dev/null +++ b/SourceCode/Chapter 12/demofile.txt @@ -0,0 +1,4 @@ +Jones +Smith +Willis +Davis \ No newline at end of file diff --git a/SourceCode/Chapter 12/hownow.txt b/SourceCode/Chapter 12/hownow.txt new file mode 100755 index 0000000..da77d85 --- /dev/null +++ b/SourceCode/Chapter 12/hownow.txt @@ -0,0 +1,2 @@ +how now brown cow. +How Now? \ No newline at end of file diff --git a/SourceCode/Chapter 12/joke.txt b/SourceCode/Chapter 12/joke.txt new file mode 100755 index 0000000..975ff62 --- /dev/null +++ b/SourceCode/Chapter 12/joke.txt @@ -0,0 +1,12 @@ +Two men who work together in a facory were talking. +"I know how to get some time off," said one. +"How are you going to do that?" asked the other. +"Watch," he said, and climbed a ladder to the ceiling. +The foreman asked what he was doing up there, +and the man replied. "I'm a lightbulb." +"I think you need some time off," the foreman +said, and the first man walked out of the +factory. After a moment, the second man followed +him. "Where do you think you're going?" +the foreman shouted. + diff --git a/SourceCode/Chapter 12/letters.txt b/SourceCode/Chapter 12/letters.txt new file mode 100755 index 0000000..e85d5b4 --- /dev/null +++ b/SourceCode/Chapter 12/letters.txt @@ -0,0 +1 @@ +abcdefghijklmnopqrstuvwxyz \ No newline at end of file diff --git a/SourceCode/Chapter 12/murphy.txt b/SourceCode/Chapter 12/murphy.txt new file mode 100755 index 0000000..80ff865 --- /dev/null +++ b/SourceCode/Chapter 12/murphy.txt @@ -0,0 +1,3 @@ +Jayne Murphy +47 Jones Circle +Almond, NC 28702 diff --git a/SourceCode/Chapter 12/names2.txt b/SourceCode/Chapter 12/names2.txt new file mode 100755 index 0000000..57dd377 --- /dev/null +++ b/SourceCode/Chapter 12/names2.txt @@ -0,0 +1,4 @@ +Jayne Murphy$47 Jones Circle$Almond, NC 28702 +$Bobie Smith$217 Halifax Drive$Canton, NC 28716 +$Bill Hammet$PO Box 121$Springfield, NC 28357 +$ \ No newline at end of file diff --git a/SourceCode/Chapter 12/numbers.dat b/SourceCode/Chapter 12/numbers.dat new file mode 100755 index 0000000..dd67d8d Binary files /dev/null and b/SourceCode/Chapter 12/numbers.dat differ diff --git a/SourceCode/Chapter 12/numfile.txt b/SourceCode/Chapter 12/numfile.txt new file mode 100755 index 0000000..09c6352 --- /dev/null +++ b/SourceCode/Chapter 12/numfile.txt @@ -0,0 +1,5 @@ +17.816392 +17.8164 +17.816 +17.82 +17.8 diff --git a/SourceCode/Chapter 12/out.txt b/SourceCode/Chapter 12/out.txt new file mode 100755 index 0000000..e030c33 --- /dev/null +++ b/SourceCode/Chapter 12/out.txt @@ -0,0 +1,2 @@ +HOW NOW BROWN COW. +HOW NOW? \ No newline at end of file diff --git a/SourceCode/Chapter 12/people.dat b/SourceCode/Chapter 12/people.dat new file mode 100755 index 0000000..5ddda54 Binary files /dev/null and b/SourceCode/Chapter 12/people.dat differ diff --git a/SourceCode/Chapter 12/punchline.txt b/SourceCode/Chapter 12/punchline.txt new file mode 100755 index 0000000..d4662f9 --- /dev/null +++ b/SourceCode/Chapter 12/punchline.txt @@ -0,0 +1,4 @@ +asfasdfasdfasdfsdf +asdfasdfsadfsadfsadf +asdfsadfsdfsdf +"I can't work in the dark," he said. \ No newline at end of file diff --git a/SourceCode/Chapter 12/sentence.txt b/SourceCode/Chapter 12/sentence.txt new file mode 100755 index 0000000..66a6aa4 --- /dev/null +++ b/SourceCode/Chapter 12/sentence.txt @@ -0,0 +1 @@ +I am on my way to becoming a great programmer. \ No newline at end of file diff --git a/SourceCode/Chapter 12/stuff.dat b/SourceCode/Chapter 12/stuff.dat new file mode 100755 index 0000000..9a03714 --- /dev/null +++ b/SourceCode/Chapter 12/stuff.dat @@ -0,0 +1 @@ +10 \ No newline at end of file diff --git a/SourceCode/Chapter 12/table.txt b/SourceCode/Chapter 12/table.txt new file mode 100755 index 0000000..e91f701 --- /dev/null +++ b/SourceCode/Chapter 12/table.txt @@ -0,0 +1,3 @@ + 2897 5 837 + 34 7 1623 + 390 3456 12 \ No newline at end of file diff --git a/SourceCode/Chapter 12/test.dat b/SourceCode/Chapter 12/test.dat new file mode 100755 index 0000000..a6bddc4 --- /dev/null +++ b/SourceCode/Chapter 12/test.dat @@ -0,0 +1 @@ +ABCD \ No newline at end of file diff --git a/SourceCode/Chapter 12/text.txt b/SourceCode/Chapter 12/text.txt new file mode 100755 index 0000000..891c93d --- /dev/null +++ b/SourceCode/Chapter 12/text.txt @@ -0,0 +1,10 @@ +No one is unaware of the name of that famous English shipowner, Cunard. +In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons. +Eight years later, the company's assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage. +In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas. +So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers. +If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management. +No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success. +In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost. +Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents. +Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers. \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-1.cpp b/SourceCode/Chapter 16/Pr16-1.cpp new file mode 100755 index 0000000..9d74810 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-1.cpp @@ -0,0 +1,49 @@ +// This program demonstrates an exception being thrown and caught. +#include +#include +using namespace std; + +// Function prototype +double divide(int, int); + +int main() +{ + int num1, num2; // To hold two numbers + double quotient; // To hold the quotient of the numbers + + // Get two numbers. + cout << "Enter two numbers: "; + cin >> num1 >> num2; + + // Divide num1 by num2 and catch any + // potential exceptions. + try + { + quotient = divide(num1, num2); + cout << "The quotient is " << quotient << endl; + } + catch (string exceptionString) + { + cout << exceptionString; + } + + cout << "End of the program.\n"; + return 0; +} + +//******************************************** +// The divide function divides numerator by * +// denominator. If denominator is zero, the * +// function throws an exception. * +//******************************************** + +double divide(int numerator, int denominator) +{ + if (denominator == 0) + { + string exceptionString = "ERROR: Cannot divide by zero.\n"; + throw exceptionString; + } + + return static_cast(numerator) / denominator; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-10.cpp b/SourceCode/Chapter 16/Pr16-10.cpp new file mode 100755 index 0000000..496b444 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-10.cpp @@ -0,0 +1,31 @@ +// This program demonstrates an overloaded function template. +#include +using namespace std; + +template +T sum(T val1, T val2) +{ + return val1 + val2; +} + +template +T sum(T val1, T val2, T val3) +{ + return val1 + val2 + val3; +} + +int main() +{ + double num1, num2, num3; + + // Get two values and display their sum. + cout << "Enter two values: "; + cin >> num1 >> num2; + cout << "Their sum is " << sum(num1, num2) << endl; + + // Get three values and display their sum. + cout << "Enter three values: "; + cin >> num1 >> num2 >> num3; + cout << "Their sum is " << sum(num1, num2, num3) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-11.cpp b/SourceCode/Chapter 16/Pr16-11.cpp new file mode 100755 index 0000000..27fbf49 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-11.cpp @@ -0,0 +1,73 @@ +// This program demonstrates the SimpleVector template. +#include +#include "SimpleVector.h" +using namespace std; + +int main() +{ + const int SIZE = 10; // Number of elements + int count; // Loop counter + + // Create a SimpleVector of ints. + SimpleVector intTable(SIZE); + + // Create a SimpleVector of doubles. + SimpleVector doubleTable(SIZE); + + // Store values in the two SimpleVectors. + for (count = 0; count < SIZE; count++) + { + intTable[count] = (count * 2); + doubleTable[count] = (count * 2.14); + } + + // Display the values in the SimpleVectors. + cout << "These values are in intTable:\n"; + for (count = 0; count < SIZE; count++) + cout << intTable[count] << " "; + cout << endl; + cout << "These values are in doubleTable:\n"; + for (count = 0; count < SIZE; count++) + cout << doubleTable[count] << " "; + cout << endl; + + // Use the standard + operator on the elements. + cout << "\nAdding 5 to each element of intTable" + << " and doubleTable.\n"; + for (count = 0; count < SIZE; count++) + { + intTable[count] = intTable[count] + 5; + doubleTable[count] = doubleTable[count] + 5.0; + } + + // Display the values in the SimpleVectors. + cout << "These values are in intTable:\n"; + for (count = 0; count < SIZE; count++) + cout << intTable[count] << " "; + cout << endl; + cout << "These values are in doubleTable:\n"; + for (count = 0; count < SIZE; count++) + cout << doubleTable[count] << " "; + cout << endl; + + // Use the standard ++ operator on the elements. + cout << "\nIncrementing each element of intTable and" + << " doubleTable.\n"; + for (count = 0; count < SIZE; count++) + { + intTable[count]++; + doubleTable[count]++; + } + + // Display the values in the SimpleVectors. + cout << "These values are in intTable:\n"; + for (count = 0; count < SIZE; count++) + cout << intTable[count] << " "; + cout << endl; + cout << "These values are in doubleTable:\n"; + for (count = 0; count < SIZE; count++) + cout << doubleTable[count] << " "; + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-12.cpp b/SourceCode/Chapter 16/Pr16-12.cpp new file mode 100755 index 0000000..5f48d77 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-12.cpp @@ -0,0 +1,49 @@ +// This program demonstrates the SearchableVector template. +#include +#include "SearchableVector.h" +using namespace std; + +int main() +{ + const int SIZE = 10; // Number of elements + int count; // Loop counter + int result; // To hold search results + + // Create two SearchableVector objects. + SearchableVector intTable(SIZE); + SearchableVector doubleTable(SIZE); + + // Store values in the objects. + for (count = 0; count < SIZE; count++) + { + intTable[count] = (count * 2); + doubleTable[count] = (count * 2.14); + } + + // Display the values in the objects. + cout << "These values are in intTable:\n"; + for (count = 0; count < SIZE; count++) + cout << intTable[count] << " "; + cout << endl << endl; + cout << "These values are in doubleTable:\n"; + for (count = 0; count < SIZE; count++) + cout << doubleTable[count] << " "; + cout << endl; + + // Search for the value 6 in intTable. + cout << "\nSearching for 6 in intTable.\n"; + result = intTable.findItem(6); + if (result == -1) + cout << "6 was not found in intTable.\n"; + else + cout << "6 was found at subscript " << result << endl; + + // Search for the value 12.84 in doubleTable. + cout << "\nSearching for 12.84 in doubleTable.\n"; + result = doubleTable.findItem(12.84); + if (result == -1) + cout << "12.84 was not found in doubleTable.\n"; + else + cout << "12.84 was found at subscript " << result << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-13.cpp b/SourceCode/Chapter 16/Pr16-13.cpp new file mode 100755 index 0000000..d50f009 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-13.cpp @@ -0,0 +1,40 @@ +// This program provides a simple demonstration of the +// vector STL template. +#include +#include // Include the vector header +using namespace std; + +int main() +{ + int count; // Loop counter + + // Define a vector object. + vector vect; + + // Use the size member function to get + // the number of elements in the vector. + cout << "vect starts with " << vect.size() + << " elements.\n"; + + // Use push_back to push values into the vector. + for (count = 0; count < 10; count++) + vect.push_back(count); + + // Display the size of the vector now. + cout << "Now vect has " << vect.size() + << " elements. Here they are:\n"; + + // Use the [] operator to display each element. + for (count = 0; count < vect.size(); count++) + cout << vect[count] << " "; + cout << endl; + + // Use the pop_back member function. + cout << "Popping the values out of vect...\n"; + for (count = 0; count < 10; count++) + vect.pop_back(); + + // Display the size of the vector now. + cout << "Now vect has " << vect.size() << " elements.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-14.cpp b/SourceCode/Chapter 16/Pr16-14.cpp new file mode 100755 index 0000000..856c941 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-14.cpp @@ -0,0 +1,35 @@ +// This program provides a simple iterator demonstration. +#include +#include // Include the vector header +using namespace std; + +int main() +{ + int count; // Loop counter + + // Define a vector object + vector vect; + + // Define an iterator object + vector::iterator iter; + + // Use push_back to push values into the vector. + for (count = 0; count < 10; count++) + vect.push_back(count); + + // Step the iterator through the vector, + // and use it to display the vector's contents. + cout << "Here are the values in vect: "; + for (iter = vect.begin(); iter < vect.end(); iter++) + { + cout << *iter << " "; + } + + // Step the iterator through the vector backwards. + cout << "\nand here they are backwards: "; + for (iter = vect.end() - 1; iter >= vect.begin(); iter--) + { + cout << *iter << " "; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-15.cpp b/SourceCode/Chapter 16/Pr16-15.cpp new file mode 100755 index 0000000..d802f1f --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-15.cpp @@ -0,0 +1,49 @@ +// A simple demonstration of STL algorithms +#include +#include // Required for the vector type +#include // Required for STL algorithms +using namespace std; + +int main() +{ + int count; // Loop counter + + // Define a vector object. + vector vect; + + // Use push_back to push values into the vector. + for (count = 0; count < 10; count++) + vect.push_back(count); + + // Display the vector's elements. + cout << "The vector has " << vect.size() + << " elements. Here they are:\n"; + for (count = 0; count < vect.size(); count++) + cout << vect[count] << " "; + cout << endl; + + // Randomly shuffle the vector's contents. + random_shuffle(vect.begin(), vect.end()); + + // Display the vector's elements. + cout << "The elements have been shuffled:\n"; + for (count = 0; count < vect.size(); count++) + cout << vect[count] << " "; + cout << endl; + + // Now sort the vector's elements. + sort(vect.begin(), vect.end()); + + // Display the vector's elements again. + cout << "The elements have been sorted:\n"; + for (count = 0; count < vect.size(); count++) + cout << vect[count] << " "; + cout << endl; + + // Now search for an element with the value 7. + if (binary_search(vect.begin(), vect.end(), 7)) + cout << "The value 7 was found in the vector.\n"; + else + cout << "The value 7 was not found in the vector.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-16.cpp b/SourceCode/Chapter 16/Pr16-16.cpp new file mode 100755 index 0000000..1222533 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-16.cpp @@ -0,0 +1,37 @@ +// This program demonstrates the STL count algorithm. +#include +#include // Needed to define the vector +#include // Needed for the count algorithm +using namespace std; + +int main() +{ + // Define a vector object. + vector values; + + // Define an iterator for the vector. + vector::iterator iter; + + // Store some values in the vector. + values.push_back(1); + values.push_back(2); + values.push_back(2); + values.push_back(3); + values.push_back(3); + values.push_back(3); + + // Display the values in the vector. + cout << "The values in the vector are:\n"; + for (iter = values.begin(); iter < values.end(); iter++) + cout << *iter << " "; + cout << endl << endl; + + // Display the count of each number. + cout << "The number of 1s in the vector is "; + cout << count(values.begin(), values.end(), 1) << endl; + cout << "The number of 2s in the vector is "; + cout << count(values.begin(), values.end(), 2) << endl; + cout << "The number of 3s in the vector is "; + cout << count(values.begin(), values.end(), 3) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-17.cpp b/SourceCode/Chapter 16/Pr16-17.cpp new file mode 100755 index 0000000..04b19f2 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-17.cpp @@ -0,0 +1,33 @@ +// A demonstration of the max_element and min_element algorithms +#include +#include // Needed to define the vector +#include // Needed for the algorithms +using namespace std; + +int main() +{ + // Define a vector object. + vector numbers; + + // Define an iterator for the vector. + vector::iterator iter; + + // Store some numbers in the vector. + for (int count = 0; count < 10; count++) + numbers.push_back(count); + + // Display the numbers in the vector. + cout << "The numbers in the vector are:\n"; + for (iter = numbers.begin(); iter != numbers.end(); iter++) + cout << *iter << " "; + cout << endl << endl; + + // Find the largest value in the vector. + iter = max_element(numbers.begin(), numbers.end()); + cout << "The largest value in the vector is " << *iter << endl; + + // Find the smallest value in the vector. + iter = min_element(numbers.begin(), numbers.end()); + cout << "The smallest value in the vector is " << *iter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-18.cpp b/SourceCode/Chapter 16/Pr16-18.cpp new file mode 100755 index 0000000..a473e7d --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-18.cpp @@ -0,0 +1,29 @@ +// A demonstration of the STL find algorithm. +#include +#include // Needed to define the vector +#include // Needed for the find algorithm +using namespace std; + +int main() +{ + // Define a vector object. + vector numbers; + + // Define an iterator for the vector. + vector::iterator iter; + + // Store some numbers in the vector. + for (int x = 0; x < 10; x++) + numbers.push_back(x); + + // Display the numbers in the vector. + cout << "The numbers in the vector are:\n"; + for (iter = numbers.begin(); iter != numbers.end(); iter++) + cout << *iter << " "; + cout << endl << endl; + + // Find the number 7 in the vector. + iter = find(numbers.begin(), numbers.end(), 7); + cout << *iter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-19.cpp b/SourceCode/Chapter 16/Pr16-19.cpp new file mode 100755 index 0000000..96cceb6 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-19.cpp @@ -0,0 +1,48 @@ +// A demonstration of the for_each find algorithm. +#include +#include // Needed to define the vector +#include // Needed for the for_each algorithm +using namespace std; + +// Function prototype +void doubleValue(int &); + +int main() +{ + // Define a vector object. + vector numbers; + + // Define an iterator for the vector. + vector::iterator iter; + + // Store some numbers in the vector. + for (int x = 0; x < 10; x++) + numbers.push_back(x); + + // Display the numbers in the vector. + cout << "The numbers in the vector are:\n"; + for (iter = numbers.begin(); iter != numbers.end(); iter++) + cout << *iter << " "; + cout << endl << endl; + + // Double the values in the vector. + for_each(numbers.begin(), numbers.end(), doubleValue); + + // Display the numbers in the vector again + cout << "Now the numbers in the vector are:\n"; + for (iter = numbers.begin(); iter != numbers.end(); iter++) + cout << *iter << " "; + cout << endl; + return 0; +} + +//******************************************************** +// Function doubleValue. This function accepts an int * +// reference as its argument. The value of the argument * +// is doubled. * +//******************************************************** + +void doubleValue(int &val) +{ + val *= 2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-6.cpp b/SourceCode/Chapter 16/Pr16-6.cpp new file mode 100755 index 0000000..513f355 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-6.cpp @@ -0,0 +1,20 @@ +// This program demonstrates the bad_alloc exception. +#include +#include // Needed for bad_alloc +using namespace std; + +int main() +{ + double *ptr = nullptr; // Pointer to double + + try + { + ptr = new double [10000]; + } + catch (bad_alloc) + { + cout << "Insufficient memory.\n"; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-7.cpp b/SourceCode/Chapter 16/Pr16-7.cpp new file mode 100755 index 0000000..8292ee6 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-7.cpp @@ -0,0 +1,25 @@ +// This program uses a function template. +#include +#include +using namespace std; + +// Template definition for square function. +template +T square(T number) +{ + return number * number; +} + +int main() +{ + int userInt; // To hold integer input + double userDouble; // To hold double input + + cout << setprecision(5); + cout << "Enter an integer and a floating-point value: "; + cin >> userInt >> userDouble; + cout << "Here are their squares: "; + cout << square(userInt) << " and " + << square(userDouble) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-8.cpp b/SourceCode/Chapter 16/Pr16-8.cpp new file mode 100755 index 0000000..6600d7f --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-8.cpp @@ -0,0 +1,39 @@ +// This program demonstrates the swapVars function template. +#include +using namespace std; + +template +void swapVars(T &var1, T &var2) +{ + T temp; + + temp = var1; + var1 = var2; + var2 = temp; +} + +int main() +{ + char firstChar, secondChar; // Two chars + int firstInt, secondInt; // Two ints + double firstDouble, secondDouble; // Two doubles + + // Get and swapVars two chars + cout << "Enter two characters: "; + cin >> firstChar >> secondChar; + swapVars(firstChar, secondChar); + cout << firstChar << " " << secondChar << endl; + + // Get and swapVars two ints + cout << "Enter two integers: "; + cin >> firstInt >> secondInt; + swapVars(firstInt, secondInt); + cout << firstInt << " " << secondInt << endl; + + // Get and swapVars two doubles + cout << "Enter two floating-point numbers: "; + cin >> firstDouble >> secondDouble; + swapVars(firstDouble, secondDouble); + cout << firstDouble << " " << secondDouble << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-9.cpp b/SourceCode/Chapter 16/Pr16-9.cpp new file mode 100755 index 0000000..cb18149 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-9.cpp @@ -0,0 +1,29 @@ +// This program demonstrates a function template +// with two type parameters. +#include +using namespace std; + +template +int largest(const T1 &var1, T2 &var2) +{ + if (sizeof(var1) > sizeof(var2)) + return sizeof(var1); + else + return sizeof(var2); +} + +int main() +{ + int i = 0; + char c = ' '; + float f = 0.0; + double d = 0.0; + + cout << "Comparing an int and a double, the largest\n" + << "of the two is " << largest(i, d) << " bytes.\n"; + + cout << "Comparing an char and a float, the largest\n" + << "of the two is " << largest(c, f) << " bytes.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 1/Pr16-2.cpp b/SourceCode/Chapter 16/Rectangle Version 1/Pr16-2.cpp new file mode 100755 index 0000000..fcc8b11 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 1/Pr16-2.cpp @@ -0,0 +1,35 @@ +// This program demonstrates Rectangle class exceptions. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + int width; + int length; + + // Create a Rectangle object. + Rectangle myRectangle; + + // Get the width and length. + cout << "Enter the rectangle's width: "; + cin >> width; + cout << "Enter the rectangle's length: "; + cin >> length; + + // Store these values in the Rectangle object. + try + { + myRectangle.setWidth(width); + myRectangle.setLength(length); + cout << "The area of the rectangle is " + << myRectangle.getArea() << endl; + } + catch (Rectangle::NegativeSize) + { + cout << "Error: A negative value was entered.\n"; + } + cout << "End of the program.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.cpp b/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.cpp new file mode 100755 index 0000000..18c5a1b --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.cpp @@ -0,0 +1,26 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + throw NegativeSize(); +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + throw NegativeSize(); +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.h b/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.h new file mode 100755 index 0000000..35f695f --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.h @@ -0,0 +1,33 @@ +// Specification file for the Rectangle class +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; // The rectangle's width + double length; // The rectangle's length + public: + // Exception class + class NegativeSize + { }; // Empty class declaration + + // Default constructor + Rectangle() + { width = 0.0; length = 0.0; } + + // Mutator functions, defined in Rectangle.cpp + void setWidth(double); + void setLength(double); + + // Accessor functions + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 2/Pr16-3.cpp b/SourceCode/Chapter 16/Rectangle Version 2/Pr16-3.cpp new file mode 100755 index 0000000..b81a541 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 2/Pr16-3.cpp @@ -0,0 +1,41 @@ +// This program demonstrates Rectangle class exceptions. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + int width; + int length; + + // Create a Rectangle object. + Rectangle myRectangle; + + // Get the width and length. + cout << "Enter the rectangle's width: "; + cin >> width; + cout << "Enter the rectangle's length: "; + cin >> length; + + // Store these values in the Rectangle object. + try + { + myRectangle.setWidth(width); + myRectangle.setLength(length); + cout << "The area of the rectangle is " + << myRectangle.getArea() << endl; + } + catch (Rectangle::NegativeWidth) + { + cout << "Error: A negative value was given " + << "for the rectangle's width.\n"; + } + catch (Rectangle::NegativeLength) + { + cout << "Error: A negative value was given " + << "for the rectangle's length.\n"; + } + + cout << "End of the program.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 2/Pr16-4.cpp b/SourceCode/Chapter 16/Rectangle Version 2/Pr16-4.cpp new file mode 100755 index 0000000..e69d5a1 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 2/Pr16-4.cpp @@ -0,0 +1,62 @@ +// This program handles the Rectangle class exceptions. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + int width; // Rectangle's width + int length; // Rectangle's length + bool tryAgain = true; // Flag to re-read input + + // Create a Rectangle object. + Rectangle myRectangle; + + // Get the rectangle's width. + cout << "Enter the rectangle's width: "; + cin >> width; + + // Store the width in the myRectangle object. + while (tryAgain) + { + try + { + myRectangle.setWidth(width); + // If no exception was thrown, then the + // next statement will execute. + tryAgain = false; + } + catch (Rectangle::NegativeWidth) + { + cout << "Please enter a non-negative value: "; + cin >> width; + } + } + + // Get the rectangle's length. + cout << "Enter the rectangle's length: "; + cin >> length; + + // Store the length in the myRectangle object. + tryAgain = true; + while (tryAgain) + { + try + { + myRectangle.setLength(length); + // If no exception was thrown, then the + // next statement will execute. + tryAgain = false; + } + catch (Rectangle::NegativeLength) + { + cout << "Please enter a non-negative value: "; + cin >> length; + } + } + + // Display the area of the rectangle. + cout << "The rectangle's area is " + << myRectangle.getArea() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.cpp b/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.cpp new file mode 100755 index 0000000..4c0ed1f --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.cpp @@ -0,0 +1,26 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + throw NegativeWidth(); +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + throw NegativeLength(); +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.h b/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.h new file mode 100755 index 0000000..0744be5 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.h @@ -0,0 +1,37 @@ +// Specification file for the Rectangle class +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; // The rectangle's width + double length; // The rectangle's length + public: + // Exception class for a negative width + class NegativeWidth + { }; + + // Exception class for a negative length + class NegativeLength + { }; + + // Default constructor + Rectangle() + { width = 0.0; length = 0.0; } + + // Mutator functions, defined in Rectangle.cpp + void setWidth(double); + void setLength(double); + + // Accessor functions + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 3/Pr16-5.cpp b/SourceCode/Chapter 16/Rectangle Version 3/Pr16-5.cpp new file mode 100755 index 0000000..e14dad2 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 3/Pr16-5.cpp @@ -0,0 +1,43 @@ +// This program demonstrates Rectangle class exceptions. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + int width; + int length; + + // Create a Rectangle object. + Rectangle myRectangle; + + // Get the width and length. + cout << "Enter the rectangle's width: "; + cin >> width; + cout << "Enter the rectangle's length: "; + cin >> length; + + // Store these values in the Rectangle object. + try + { + myRectangle.setWidth(width); + myRectangle.setLength(length); + cout << "The area of the rectangle is " + << myRectangle.getArea() << endl; + } + catch (Rectangle::NegativeWidth e) + { + cout << "Error: " << e.getValue() + << " is an invalid value for the" + << " rectangle's width.\n"; + } + catch (Rectangle::NegativeLength e) + { + cout << "Error: " << e.getValue() + << " is an invalid value for the" + << " rectangle's length.\n"; + } + + cout << "End of the program.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.cpp b/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.cpp new file mode 100755 index 0000000..7e8cbf1 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.cpp @@ -0,0 +1,26 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + throw NegativeWidth(w); +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + throw NegativeLength(len); +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.h b/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.h new file mode 100755 index 0000000..04112d5 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.h @@ -0,0 +1,55 @@ +// Specification file for the Rectangle class +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; // The rectangle's width + double length; // The rectangle's length + public: + // Exception class for a negative width + class NegativeWidth + { + private: + int value; + public: + NegativeWidth(int val) + { value = val; } + + int getValue() const + { return value; } + }; + + // Exception class for a negative length + class NegativeLength + { + private: + int value; + public: + NegativeLength(int val) + { value = val; } + + int getValue() const + { return value; } + }; + + // Default constructor + Rectangle() + { width = 0.0; length = 0.0; } + + // Mutator functions, defined in Rectangle.cpp + void setWidth(double); + void setLength(double); + + // Accessor functions + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 16/SearchableVector.h b/SourceCode/Chapter 16/SearchableVector.h new file mode 100755 index 0000000..a1b604f --- /dev/null +++ b/SourceCode/Chapter 16/SearchableVector.h @@ -0,0 +1,52 @@ +#ifndef SEARCHABLEVECTOR_H +#define SEARCHABLEVECTOR_H +#include "SimpleVector.h" + +template +class SearchableVector : public SimpleVector +{ +public: + // Default constructor + SearchableVector() : SimpleVector() + {} + + // Constructor + SearchableVector(int size) : SimpleVector(size) + { } + + // Copy constructor + SearchableVector(const SearchableVector &); + + // Accessor to find an item + int findItem(const T); +}; + +//******************************************************* +// Copy constructor * +//******************************************************* + +template +SearchableVector::SearchableVector(const SearchableVector &obj) : + SimpleVector(obj.size()) +{ + for(int count = 0; count < this->size(); count++) + this->operator[](count) = obj[count]; +} + +//******************************************************* +// findItem function * +// This function searches for item. If item is found * +// the subscript is returned. Otherwise -1 is returned. * +//******************************************************* + +template +int SearchableVector::findItem(const T item) +{ + for (int count = 0; count <= this->size(); count++) + { + if (getElementAt(count) == item) + return count; + } + return -1; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 16/SimpleVector.h b/SourceCode/Chapter 16/SimpleVector.h new file mode 100755 index 0000000..1dbee2d --- /dev/null +++ b/SourceCode/Chapter 16/SimpleVector.h @@ -0,0 +1,149 @@ +// SimpleVector class template +#ifndef SIMPLEVECTOR_H +#define SIMPLEVECTOR_H +#include +#include // Needed for bad_alloc exception +#include // Needed for the exit function +using namespace std; + +template +class SimpleVector +{ +private: + T *aptr; // To point to the allocated array + int arraySize; // Number of elements in the array + void memError(); // Handles memory allocation errors + void subError(); // Handles subscripts out of range + +public: + // Default constructor + SimpleVector() + { aptr = 0; arraySize = 0;} + + // Constructor declaration + SimpleVector(int); + + // Copy constructor declaration + SimpleVector(const SimpleVector &); + + // Destructor declaration + ~SimpleVector(); + + // Accessor to return the array size + int size() const + { return arraySize; } + + // Accessor to return a specific element + T getElementAt(int position); + + // Overloaded [] operator declaration + T &operator[](const int &); +}; + +//*********************************************************** +// Constructor for SimpleVector class. Sets the size of the * +// array and allocates memory for it. * +//*********************************************************** + +template +SimpleVector::SimpleVector(int s) +{ + arraySize = s; + // Allocate memory for the array. + try + { + aptr = new T [s]; + } + catch (bad_alloc) + { + memError(); + } + + // Initialize the array. + for (int count = 0; count < arraySize; count++) + *(aptr + count) = 0; +} + +//******************************************* +// Copy Constructor for SimpleVector class. * +//******************************************* + +template +SimpleVector::SimpleVector(const SimpleVector &obj) +{ + // Copy the array size. + arraySize = obj.arraySize; + + // Allocate memory for the array. + aptr = new T [arraySize]; + if (aptr == 0) + memError(); + + // Copy the elements of obj's array. + for(int count = 0; count < arraySize; count++) + *(aptr + count) = *(obj.aptr + count); +} + +//************************************** +// Destructor for SimpleVector class. * +//************************************** + +template +SimpleVector::~SimpleVector() +{ + if (arraySize > 0) + delete [] aptr; +} + +//******************************************************* +// memError function. Displays an error message and * +// terminates the program when memory allocation fails. * +//******************************************************* + +template +void SimpleVector::memError() +{ + cout << "ERROR:Cannot allocate memory.\n"; + exit(EXIT_FAILURE); +} + +//*********************************************************** +// subError function. Displays an error message and * +// terminates the program when a subscript is out of range. * +//*********************************************************** + +template +void SimpleVector::subError() +{ + cout << "ERROR: Subscript out of range.\n"; + exit(EXIT_FAILURE); +} + +//******************************************************* +// getElementAt function. The argument is a subscript. * +// This function returns the value stored at the sub- * +// cript in the array. * +//******************************************************* + +template +T SimpleVector::getElementAt(int sub) +{ + if (sub < 0 || sub >= arraySize) + subError(); + return aptr[sub]; +} + +//******************************************************* +// Overloaded [] operator. The argument is a subscript. * +// This function returns a reference to the element * +// in the array indexed by the subscript. * +//******************************************************* + +template +T &SimpleVector::operator[](const int &sub) +{ + if (sub < 0 || sub >= arraySize) + subError(); + return aptr[sub]; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.cpp b/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.cpp new file mode 100755 index 0000000..9f327c1 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.cpp @@ -0,0 +1,210 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded != operator. Returns true if the current object * +// is set to a value NOT equal to that of right. * +//************************************************************* + +bool FeetInches::operator != (const FeetInches &right) +{ + bool status; + + if (!operator==(right)) + status = true; + else + status = false; + + return status; +} + +//******************************************************** +// Overloaded << operator. Gives cout the ability to * +// directly display FeetInches objects. * +//******************************************************** + +ostream &operator<<(ostream &strm, const FeetInches &obj) +{ + strm << obj.feet << " feet, " << obj.inches << " inches"; + return strm; +} + +//******************************************************** +// Overloaded >> operator. Gives cin the ability to * +// store user input directly into FeetInches objects. * +//******************************************************** + +istream &operator >> (istream &strm, FeetInches &obj) +{ + // Prompt the user for the feet. + cout << "Feet: "; + strm >> obj.feet; + + // Prompt the user for the inches. + cout << "Inches: "; + strm >> obj.inches; + + // Normalize the values. + obj.simplify(); + + return strm; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to a double. * +//************************************************************* + +FeetInches::operator double() +{ + double temp = feet; + + temp += (inches / 12.0); + return temp; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to an int. * +//************************************************************* + +FeetInches:: operator int() +{ + return feet; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.h b/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.h new file mode 100755 index 0000000..f18a62a --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.h @@ -0,0 +1,64 @@ +// Specification file for the FeetInches class +#ifndef FEETINCHES_H +#define FEETINCHES_H + +#include +using namespace std; + +class FeetInches; // Forward Declaration + +// Function Prototypes for Overloaded Stream Operators +ostream &operator << (ostream &, const FeetInches &); +istream &operator >> (istream &, FeetInches &); + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == + bool operator != (const FeetInches &); // Overloaded == + + // Conversion functions + operator double(); + operator int(); + + // Friends + friend ostream &operator << (ostream &, const FeetInches &); + friend istream &operator >> (istream &, FeetInches &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 1/LinkedList.h b/SourceCode/Chapter 17/LinkedList Template Version 1/LinkedList.h new file mode 100755 index 0000000..867717f --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 1/LinkedList.h @@ -0,0 +1,223 @@ +// A class template for holding a linked list. +#ifndef LINKEDLIST_H +#define LINKEDLIST_H +#include // For cout +using namespace std; + +template +class LinkedList +{ +private: + // Declare a structure for the list + struct ListNode + { + T value; // The value in this node + struct ListNode *next; // To point to the next node + }; + + ListNode *head; // List head pointer + +public: + // Constructor + LinkedList() + { head = nullptr; } + + // Destructor + ~LinkedList(); + + // Linked list operations + void appendNode(T); + void insertNode(T); + void deleteNode(T); + void displayList() const; +}; + + +//************************************************** +// appendNode appends a node containing the value * +// pased into newValue, to the end of the list. * +//************************************************** + +template +void LinkedList::appendNode(T newValue) +{ + ListNode *newNode; // To point to a new node + ListNode *nodePtr; // To move through the list + + // Allocate a new node and store newValue there. + newNode = new ListNode; + newNode->value = newValue; + newNode->next = nullptr; + + // If there are no nodes in the list + // make newNode the first node. + if (!head) + head = newNode; + else // Otherwise, insert newNode at end. + { + // Initialize nodePtr to head of list. + nodePtr = head; + + // Find the last node in the list. + while (nodePtr->next) + nodePtr = nodePtr->next; + + // Insert newNode as the last node. + nodePtr->next = newNode; + } +} + +//************************************************** +// displayList shows the value * +// stored in each node of the linked list * +// pointed to by head. * +//************************************************** + +template +void LinkedList::displayList() const +{ + ListNode *nodePtr; // To move through the list + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr points to a node, traverse + // the list. + while (nodePtr) + { + // Display the value in this node. + cout << nodePtr->value << endl; + + // Move to the next node. + nodePtr = nodePtr->next; + } +} + +//************************************************** +// The insertNode function inserts a node with * +// newValue copied to its value member. * +//************************************************** + +template +void LinkedList::insertNode(T newValue) +{ + ListNode *newNode; // A new node + ListNode *nodePtr; // To traverse the list + ListNode *previousNode = nullptr; // The previous node + + // Allocate a new node and store newValue there. + newNode = new ListNode; + newNode->value = newValue; + + // If there are no nodes in the list + // make newNode the first node + if (!head) + { + head = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert newNode + { + // Position nodePtr at the head of list. + nodePtr = head; + + // Initialize previousNode to nullptr. + previousNode = nullptr; + + // Skip all nodes whose value is less than newValue. + while (nodePtr != nullptr && nodePtr->value < newValue) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If the new node is to be the 1st in the list, + // insert it before all other nodes. + if (previousNode == nullptr) + { + head = newNode; + newNode->next = nodePtr; + } + else // Otherwise insert after the previous node. + { + previousNode->next = newNode; + newNode->next = nodePtr; + } + } +} + +//***************************************************** +// The deleteNode function searches for a node * +// with searchValue as its value. The node, if found, * +// is deleted from the list and from memory. * +//***************************************************** + +template +void LinkedList::deleteNode(T searchValue) +{ + ListNode *nodePtr; // To traverse the list + ListNode *previousNode; // To point to the previous node + + // If the list is empty, do nothing. + if (!head) + return; + + // Determine if the first node is the one. + if (head->value == searchValue) + { + nodePtr = head->next; + delete head; + head = nodePtr; + } + else + { + // Initialize nodePtr to head of list + nodePtr = head; + + // Skip all nodes whose value member is + // not equal to num. + while (nodePtr != nullptr && nodePtr->value != searchValue) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If nodePtr is not at the end of the list, + // link the previous node to the node after + // nodePtr, then delete nodePtr. + if (nodePtr) + { + previousNode->next = nodePtr->next; + delete nodePtr; + } + } +} + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +template +LinkedList::~LinkedList() +{ + ListNode *nodePtr; // To traverse the list + ListNode *nextNode; // To point to the next node + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr is not at the end of the list... + while (nodePtr != nullptr) + { + // Save a pointer to the next node. + nextNode = nodePtr->next; + + // Delete the current node. + delete nodePtr; + + // Position nodePtr at the next node. + nodePtr = nextNode; + } +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 1/Pr17-5.cpp b/SourceCode/Chapter 17/LinkedList Template Version 1/Pr17-5.cpp new file mode 100755 index 0000000..e955ec7 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 1/Pr17-5.cpp @@ -0,0 +1,46 @@ +// This program demonstrates the linked list template. +#include +#include "LinkedList.h" +#include "FeetInches.h" +using namespace std; + +int main() +{ + // Define a LinkedList object. + LinkedList list; + + // Define some FeetInches objects. + FeetInches distance1(5, 4); // 5 feet 4 inches + FeetInches distance2(6, 8); // 6 feet 8 inches + FeetInches distance3(8, 9); // 8 feet 9 inches + + // Store the FeetInches objects in the list. + list.appendNode(distance1); // 5 feet 4 inches + list.appendNode(distance2); // 6 feet 8 inches + list.appendNode(distance3); // 8 feet 9 inches + + // Display the values in the list. + cout << "Here are the initial values:\n"; + list.displayList(); + cout << endl; + + // Insert another FeetInches object. + cout << "Now inserting the value 7 feet 2 inches.\n"; + FeetInches distance4(7, 2); + list.insertNode(distance4); + + // Display the values in the list. + cout << "Here are the nodes now.\n"; + list.displayList(); + cout << endl; + + // Delete the last node. + cout << "Now deleting the last node.\n"; + FeetInches distance5(8, 9); + list.deleteNode(distance5); + + // Display the values in the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.cpp b/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.cpp new file mode 100755 index 0000000..9f327c1 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.cpp @@ -0,0 +1,210 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded != operator. Returns true if the current object * +// is set to a value NOT equal to that of right. * +//************************************************************* + +bool FeetInches::operator != (const FeetInches &right) +{ + bool status; + + if (!operator==(right)) + status = true; + else + status = false; + + return status; +} + +//******************************************************** +// Overloaded << operator. Gives cout the ability to * +// directly display FeetInches objects. * +//******************************************************** + +ostream &operator<<(ostream &strm, const FeetInches &obj) +{ + strm << obj.feet << " feet, " << obj.inches << " inches"; + return strm; +} + +//******************************************************** +// Overloaded >> operator. Gives cin the ability to * +// store user input directly into FeetInches objects. * +//******************************************************** + +istream &operator >> (istream &strm, FeetInches &obj) +{ + // Prompt the user for the feet. + cout << "Feet: "; + strm >> obj.feet; + + // Prompt the user for the inches. + cout << "Inches: "; + strm >> obj.inches; + + // Normalize the values. + obj.simplify(); + + return strm; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to a double. * +//************************************************************* + +FeetInches::operator double() +{ + double temp = feet; + + temp += (inches / 12.0); + return temp; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to an int. * +//************************************************************* + +FeetInches:: operator int() +{ + return feet; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.h b/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.h new file mode 100755 index 0000000..f18a62a --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.h @@ -0,0 +1,64 @@ +// Specification file for the FeetInches class +#ifndef FEETINCHES_H +#define FEETINCHES_H + +#include +using namespace std; + +class FeetInches; // Forward Declaration + +// Function Prototypes for Overloaded Stream Operators +ostream &operator << (ostream &, const FeetInches &); +istream &operator >> (istream &, FeetInches &); + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == + bool operator != (const FeetInches &); // Overloaded == + + // Conversion functions + operator double(); + operator int(); + + // Friends + friend ostream &operator << (ostream &, const FeetInches &); + friend istream &operator >> (istream &, FeetInches &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 2/LinkedList.h b/SourceCode/Chapter 17/LinkedList Template Version 2/LinkedList.h new file mode 100755 index 0000000..38ed3d9 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 2/LinkedList.h @@ -0,0 +1,233 @@ +// A class template for holding a linked list. +// The node type is also a class template. +#ifndef LINKEDLIST_H +#define LINKEDLIST_H + +//********************************************* +// The ListNode class creates a type used to * +// store a node of the linked list. * +//********************************************* + +template +class ListNode +{ +public: + T value; // Node value + ListNode *next; // Pointer to the next node + + // Constructor + ListNode (T nodeValue) + { value = nodeValue; + next = nullptr;} +}; + +//********************************************* +// LinkedList class * +//********************************************* + +template +class LinkedList +{ +private: + ListNode *head; // List head pointer + +public: + // Constructor + LinkedList() + { head = nullptr; } + + // Destructor + ~LinkedList(); + + // Linked list operations + void appendNode(T); + void insertNode(T); + void deleteNode(T); + void displayList() const; +}; + + +//************************************************** +// appendNode appends a node containing the value * +// pased into newValue, to the end of the list. * +//************************************************** + +template +void LinkedList::appendNode(T newValue) +{ + ListNode *newNode; // To point to a new node + ListNode *nodePtr; // To move through the list + + // Allocate a new node and store newValue there. + newNode = new ListNode(newValue); + + // If there are no nodes in the list + // make newNode the first node. + if (!head) + head = newNode; + else // Otherwise, insert newNode at end. + { + // Initialize nodePtr to head of list. + nodePtr = head; + + // Find the last node in the list. + while (nodePtr->next) + nodePtr = nodePtr->next; + + // Insert newNode as the last node. + nodePtr->next = newNode; + } +} + +//************************************************** +// displayList shows the value stored in each node * +// of the linked list pointed to by head. * +//************************************************** + +template +void LinkedList::displayList() const +{ + ListNode *nodePtr; // To move through the list + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr points to a node, traverse + // the list. + while (nodePtr) + { + // Display the value in this node. + cout << nodePtr->value << endl; + + // Move to the next node. + nodePtr = nodePtr->next; + } +} + +//************************************************** +// The insertNode function inserts a node with * +// newValue copied to its value member. * +//************************************************** + +template +void LinkedList::insertNode(T newValue) +{ + ListNode *newNode; // A new node + ListNode *nodePtr; // To traverse the list + ListNode *previousNode = nullptr; // The previous node + + // Allocate a new node and store newValue there. + newNode = new ListNode(newValue); + + // If there are no nodes in the list + // make newNode the first node + if (!head) + { + head = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert newNode + { + // Position nodePtr at the head of list. + nodePtr = head; + + // Initialize previousNode to nullptr. + previousNode = nullptr; + + // Skip all nodes whose value is less than newValue. + while (nodePtr != nullptr && nodePtr->value < newValue) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If the new node is to be the 1st in the list, + // insert it before all other nodes. + if (previousNode == nullptr) + { + head = newNode; + newNode->next = nodePtr; + } + else // Otherwise insert after the previous node. + { + previousNode->next = newNode; + newNode->next = nodePtr; + } + } +} + +//***************************************************** +// The deleteNode function searches for a node * +// with searchValue as its value. The node, if found, * +// is deleted from the list and from memory. * +//***************************************************** + +template +void LinkedList::deleteNode(T searchValue) +{ + ListNode *nodePtr; // To traverse the list + ListNode *previousNode; // To point to the previous node + + // If the list is empty, do nothing. + if (!head) + return; + + // Determine if the first node is the one. + if (head->value == searchValue) + { + nodePtr = head->next; + delete head; + head = nodePtr; + } + else + { + // Initialize nodePtr to head of list + nodePtr = head; + + // Skip all nodes whose value member is + // not equal to num. + while (nodePtr != nullptr && nodePtr->value != searchValue) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If nodePtr is not at the end of the list, + // link the previous node to the node after + // nodePtr, then delete nodePtr. + if (nodePtr) + { + previousNode->next = nodePtr->next; + delete nodePtr; + } + } +} + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +template +LinkedList::~LinkedList() +{ + ListNode *nodePtr; // To traverse the list + ListNode *nextNode; // To point to the next node + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr is not at the end of the list... + while (nodePtr != nullptr) + { + // Save a pointer to the next node. + nextNode = nodePtr->next; + + // Delete the current node. + delete nodePtr; + + // Position nodePtr at the next node. + nodePtr = nextNode; + } +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 2/Pr17-5.cpp b/SourceCode/Chapter 17/LinkedList Template Version 2/Pr17-5.cpp new file mode 100755 index 0000000..e955ec7 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 2/Pr17-5.cpp @@ -0,0 +1,46 @@ +// This program demonstrates the linked list template. +#include +#include "LinkedList.h" +#include "FeetInches.h" +using namespace std; + +int main() +{ + // Define a LinkedList object. + LinkedList list; + + // Define some FeetInches objects. + FeetInches distance1(5, 4); // 5 feet 4 inches + FeetInches distance2(6, 8); // 6 feet 8 inches + FeetInches distance3(8, 9); // 8 feet 9 inches + + // Store the FeetInches objects in the list. + list.appendNode(distance1); // 5 feet 4 inches + list.appendNode(distance2); // 6 feet 8 inches + list.appendNode(distance3); // 8 feet 9 inches + + // Display the values in the list. + cout << "Here are the initial values:\n"; + list.displayList(); + cout << endl; + + // Insert another FeetInches object. + cout << "Now inserting the value 7 feet 2 inches.\n"; + FeetInches distance4(7, 2); + list.insertNode(distance4); + + // Display the values in the list. + cout << "Here are the nodes now.\n"; + list.displayList(); + cout << endl; + + // Delete the last node. + cout << "Now deleting the last node.\n"; + FeetInches distance5(8, 9); + list.deleteNode(distance5); + + // Display the values in the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/NumberList.cpp b/SourceCode/Chapter 17/NumberList.cpp new file mode 100755 index 0000000..5f3b55f --- /dev/null +++ b/SourceCode/Chapter 17/NumberList.cpp @@ -0,0 +1,187 @@ +// Implementation file for the NumberList class +#include // For cout +#include "NumberList.h" +using namespace std; + +//************************************************** +// appendNode appends a node containing the * +// value pased into num, to the end of the list. * +//************************************************** + +void NumberList::appendNode(double num) +{ + ListNode *newNode; // To point to a new node + ListNode *nodePtr; // To move through the list + + // Allocate a new node and store num there. + newNode = new ListNode; + newNode->value = num; + newNode->next = nullptr; + + // If there are no nodes in the list + // make newNode the first node. + if (!head) + head = newNode; + else // Otherwise, insert newNode at end. + { + // Initialize nodePtr to head of list. + nodePtr = head; + + // Find the last node in the list. + while (nodePtr->next) + nodePtr = nodePtr->next; + + // Insert newNode as the last node. + nodePtr->next = newNode; + } +} + +//************************************************** +// displayList shows the value * +// stored in each node of the linked list * +// pointed to by head. * +//************************************************** + +void NumberList::displayList() const +{ + ListNode *nodePtr; // To move through the list + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr points to a node, traverse + // the list. + while (nodePtr) + { + // Display the value in this node. + cout << nodePtr->value << endl; + + // Move to the next node. + nodePtr = nodePtr->next; + } +} + +//************************************************** +// The insertNode function inserts a node with * +// num copied to its value member. * +//************************************************** + +void NumberList::insertNode(double num) +{ + ListNode *newNode; // A new node + ListNode *nodePtr; // To traverse the list + ListNode *previousNode = nullptr; // The previous node + + // Allocate a new node and store num there. + newNode = new ListNode; + newNode->value = num; + + // If there are no nodes in the list + // make newNode the first node + if (!head) + { + head = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert newNode + { + // Position nodePtr at the head of list. + nodePtr = head; + + // Initialize previousNode to nullptr. + previousNode = nullptr; + + // Skip all nodes whose value is less than num. + while (nodePtr != nullptr && nodePtr->value < num) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If the new node is to be the 1st in the list, + // insert it before all other nodes. + if (previousNode == nullptr) + { + head = newNode; + newNode->next = nodePtr; + } + else // Otherwise insert after the previous node. + { + previousNode->next = newNode; + newNode->next = nodePtr; + } + } +} + +//************************************************** +// The deleteNode function searches for a node * +// with num as its value. The node, if found, is * +// deleted from the list and from memory. * +//************************************************** + +void NumberList::deleteNode(double num) +{ + ListNode *nodePtr; // To traverse the list + ListNode *previousNode; // To point to the previous node + + // If the list is empty, do nothing. + if (!head) + return; + + // Determine if the first node is the one. + if (head->value == num) + { + nodePtr = head->next; + delete head; + head = nodePtr; + } + else + { + // Initialize nodePtr to head of list + nodePtr = head; + + // Skip all nodes whose value member is + // not equal to num. + while (nodePtr != nullptr && nodePtr->value != num) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If nodePtr is not at the end of the list, + // link the previous node to the node after + // nodePtr, then delete nodePtr. + if (nodePtr) + { + previousNode->next = nodePtr->next; + delete nodePtr; + } + } +} + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +NumberList::~NumberList() +{ + ListNode *nodePtr; // To traverse the list + ListNode *nextNode; // To point to the next node + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr is not at the end of the list... + while (nodePtr != nullptr) + { + // Save a pointer to the next node. + nextNode = nodePtr->next; + + // Delete the current node. + delete nodePtr; + + // Position nodePtr at the next node. + nodePtr = nextNode; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/NumberList.h b/SourceCode/Chapter 17/NumberList.h new file mode 100755 index 0000000..c42f50c --- /dev/null +++ b/SourceCode/Chapter 17/NumberList.h @@ -0,0 +1,31 @@ +// Specification file for the NumberList class +#ifndef NUMBERLIST_H +#define NUMBERLIST_H + +class NumberList +{ +private: + // Declare a structure for the list + struct ListNode + { + double value; // The value in this node + struct ListNode *next; // To point to the next node + }; + + ListNode *head; // List head pointer + +public: + // Constructor + NumberList() + { head = nullptr; } + + // Destructor + ~NumberList(); + + // Linked list operations + void appendNode(double); + void insertNode(double); + void deleteNode(double); + void displayList() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-1.cpp b/SourceCode/Chapter 17/Pr17-1.cpp new file mode 100755 index 0000000..fe34be2 --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-1.cpp @@ -0,0 +1,17 @@ +// This program demonstrates a simple append +// operation on a linked list. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + // Define a NumberList object. + NumberList list; + + // Append some values to the list. + list.appendNode(2.5); + list.appendNode(7.9); + list.appendNode(12.6); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-2.cpp b/SourceCode/Chapter 17/Pr17-2.cpp new file mode 100755 index 0000000..95db4c8 --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-2.cpp @@ -0,0 +1,19 @@ +// This program demonstrates the displayList member function. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + // Define a NumberList object. + NumberList list; + + // Append some values to the list. + list.appendNode(2.5); + list.appendNode(7.9); + list.appendNode(12.6); + + // Display the values in the list. + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-3.cpp b/SourceCode/Chapter 17/Pr17-3.cpp new file mode 100755 index 0000000..4e0e957 --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-3.cpp @@ -0,0 +1,22 @@ +// This program demonstrates the insertNode member function. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + // Define a NumberList object. + NumberList list; + + // Build the list with some values. + list.appendNode(2.5); + list.appendNode(7.9); + list.appendNode(12.6); + + // Insert a node in the middle of the list. + list.insertNode(10.5); + + // Dispay the list + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-4.cpp b/SourceCode/Chapter 17/Pr17-4.cpp new file mode 100755 index 0000000..56200aa --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-4.cpp @@ -0,0 +1,47 @@ +// This program demonstrates the deleteNode member function. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + // Define a NumberList object. + NumberList list; + + // Build the list with some values. + list.appendNode(2.5); + list.appendNode(7.9); + list.appendNode(12.6); + + // Display the list. + cout << "Here are the initial values:\n"; + list.displayList(); + cout << endl; + + // Delete the middle node. + cout << "Now deleting the node in the middle.\n"; + list.deleteNode(7.9); + + // Display the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + cout << endl; + + // Delete the last node. + cout << "Now deleting the last node.\n"; + list.deleteNode(12.6); + + // Display the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + cout << endl; + + // Delete the only node left in the list. + cout << "Now deleting the only remaining node.\n"; + list.deleteNode(2.5); + + // Display the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-6.cpp b/SourceCode/Chapter 17/Pr17-6.cpp new file mode 100755 index 0000000..de6904b --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-6.cpp @@ -0,0 +1,31 @@ +// This program demonstrates the STL list container. +#include +#include // Include the list header +using namespace std; + +int main() +{ + // Define a list object. + list myList; + + // Define an iterator for the list. + list::iterator iter; + + // Add values to the list + for (int x = 0; x < 100; x += 10) + myList.push_back(x); + + // Display the values + for (iter = myList.begin(); iter != myList.end(); iter++) + cout << *iter << " "; + cout << endl; + + // Now reverse the order of the elements + myList.reverse(); + + // Display the values again + for (iter = myList.begin(); iter != myList.end(); iter++) + cout << *iter << " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynIntQueue.cpp b/SourceCode/Chapter 18/DynIntQueue.cpp new file mode 100755 index 0000000..c0a08f7 --- /dev/null +++ b/SourceCode/Chapter 18/DynIntQueue.cpp @@ -0,0 +1,110 @@ +#include +#include "DynIntQueue.h" +using namespace std; + +//******************************************** +// The constructor creates an empty queue. * +//******************************************** + +DynIntQueue::DynIntQueue() +{ + front = nullptr; + rear = nullptr; + numItems = 0; +} + +//******************************************** +// Destructor * +//******************************************** + +DynIntQueue::~DynIntQueue() +{ + clear(); +} + +//******************************************** +// Function enqueue inserts the value in num * +// at the rear of the queue. * +//******************************************** + +void DynIntQueue::enqueue(int num) +{ + QueueNode *newNode = nullptr; + + // Create a new node and store num there. + newNode = new QueueNode; + newNode->value = num; + newNode->next = nullptr; + + // Adjust front and rear as necessary. + if (isEmpty()) + { + front = newNode; + rear = newNode; + } + else + { + rear->next = newNode; + rear = newNode; + } + + // Update numItems. + numItems++; +} + +//********************************************** +// Function dequeue removes the value at the * +// front of the queue, and copies it into num. * +//********************************************** + +void DynIntQueue::dequeue(int &num) +{ + QueueNode *temp = nullptr; + + if (isEmpty()) + { + cout << "The queue is empty.\n"; + } + else + { + // Save the front node value in num. + num = front->value; + + // Remove the front node and delete it. + temp = front; + front = front->next; + delete temp; + + // Update numItems. + numItems--; + } +} + +//********************************************* +// Function isEmpty returns true if the queue * +// is empty, and false otherwise. * +//********************************************* + +bool DynIntQueue::isEmpty() const +{ + bool status; + + if (numItems > 0) + status = false; + else + status = true; + return status; +} + +//******************************************** +// Function clear dequeues all the elements * +// in the queue. * +//******************************************** + +void DynIntQueue::clear() +{ + int value; // Dummy variable for dequeue + + while(!isEmpty()) + dequeue(value); +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynIntQueue.h b/SourceCode/Chapter 18/DynIntQueue.h new file mode 100755 index 0000000..0a60b26 --- /dev/null +++ b/SourceCode/Chapter 18/DynIntQueue.h @@ -0,0 +1,31 @@ +#ifndef DYNINTQUEUE_H +#define DYNINTQUEUE_H + +class DynIntQueue +{ +private: + // Structure for the queue nodes + struct QueueNode + { + int value; // Value in a node + QueueNode *next; // Pointer to the next node + }; + + QueueNode *front; // The front of the queue + QueueNode *rear; // The rear of the queue + int numItems; // Number of items in the queue +public: + // Constructor + DynIntQueue(); + + // Destructor + ~DynIntQueue(); + + // Queue operations + void enqueue(int); + void dequeue(int &); + bool isEmpty() const; + bool isFull() const; + void clear(); +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynIntStack.cpp b/SourceCode/Chapter 18/DynIntStack.cpp new file mode 100755 index 0000000..930ae65 --- /dev/null +++ b/SourceCode/Chapter 18/DynIntStack.cpp @@ -0,0 +1,92 @@ +#include +#include "DynIntStack.h" +using namespace std; + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +DynIntStack::~DynIntStack() +{ + StackNode *nodePtr = nullptr, *nextNode = nullptr; + + // Position nodePtr at the top of the stack. + nodePtr = top; + + // Traverse the list deleting each node. + while (nodePtr != nullptr) + { + nextNode = nodePtr->next; + delete nodePtr; + nodePtr = nextNode; + } +} + +//************************************************ +// Member function push pushes the argument onto * +// the stack. * +//************************************************ + +void DynIntStack::push(int num) +{ + StackNode *newNode = nullptr; // Pointer to a new node + + // Allocate a new node and store num there. + newNode = new StackNode; + newNode->value = num; + + // If there are no nodes in the list + // make newNode the first node. + if (isEmpty()) + { + top = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert NewNode before top. + { + newNode->next = top; + top = newNode; + } +} + +//**************************************************** +// Member function pop pops the value at the top * +// of the stack off, and copies it into the variable * +// passed as an argument. * +//**************************************************** + +void DynIntStack::pop(int &num) +{ + StackNode *temp = nullptr; // Temporary pointer + + // First make sure the stack isn't empty. + if (isEmpty()) + { + cout << "The stack is empty.\n"; + } + else // pop value off top of stack + { + num = top->value; + temp = top->next; + delete top; + top = temp; + } +} + +//**************************************************** +// Member function isEmpty returns true if the stack * +// is empty, or false otherwise. * +//**************************************************** + +bool DynIntStack::isEmpty() +{ + bool status; + + if (!top) + status = true; + else + status = false; + + return status; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynIntStack.h b/SourceCode/Chapter 18/DynIntStack.h new file mode 100755 index 0000000..fafa86b --- /dev/null +++ b/SourceCode/Chapter 18/DynIntStack.h @@ -0,0 +1,30 @@ +// Specification file for the DynIntStack class +#ifndef DYNINTSTACK_H +#define DYNINTSTACK_H + +class DynIntStack +{ +private: + // Structure for stack nodes + struct StackNode + { + int value; // Value in the node + StackNode *next; // Pointer to the next node + }; + + StackNode *top; // Pointer to the stack top + +public: + // Constructor + DynIntStack() + { top = nullptr; } + + // Destructor + ~DynIntStack(); + + // Stack operations + void push(int); + void pop(int &); + bool isEmpty(); +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynamicQueue.h b/SourceCode/Chapter 18/DynamicQueue.h new file mode 100755 index 0000000..f3bb9ad --- /dev/null +++ b/SourceCode/Chapter 18/DynamicQueue.h @@ -0,0 +1,142 @@ +#ifndef DYNAMICQUEUE_H +#define DYNAMICQUEUE_H +#include +using namespace std; + +// DynamicQueue template +template +class DynamicQueue +{ +private: + // Structure for the queue nodes + struct QueueNode + { + T value; // Value in a node + QueueNode *next; // Pointer to the next node + }; + + QueueNode *front; // The front of the queue + QueueNode *rear; // The rear of the queue + int numItems; // Number of items in the queue +public: + // Constructor + DynamicQueue(); + + // Destructor + ~DynamicQueue(); + + // Queue operations + void enqueue(T); + void dequeue(T &); + bool isEmpty() const; + bool isFull() const; + void clear(); +}; + +//******************************************** +// The constructor creates an empty queue. * +//******************************************** +template +DynamicQueue::DynamicQueue() +{ + front = nullptr; + rear = nullptr; + numItems = 0; +} + +//******************************************** +// Destructor * +//******************************************** +template +DynamicQueue::~DynamicQueue() +{ + clear(); +} + +//******************************************** +// Function enqueue inserts the value in num * +// at the rear of the queue. * +//******************************************** +template +void DynamicQueue::enqueue(T item) +{ + QueueNode *newNode = nullptr; + + // Create a new node and store num there. + newNode = new QueueNode; + newNode->value = item; + newNode->next = nullptr; + + // Adjust front and rear as necessary. + if (isEmpty()) + { + front = newNode; + rear = newNode; + } + else + { + rear->next = newNode; + rear = newNode; + } + + // Update numItems. + numItems++; +} + +//********************************************** +// Function dequeue removes the value at the * +// front of the queue, and copies it into num. * +//********************************************** +template +void DynamicQueue::dequeue(T &item) +{ + QueueNode *temp = nullptr; + + if (isEmpty()) + { + cout << "The queue is empty.\n"; + } + else + { + // Save the front node value in num. + item = front->value; + + // Remove the front node and delete it. + temp = front; + front = front->next; + delete temp; + + // Update numItems. + numItems--; + } +} + +//********************************************* +// Function isEmpty returns true if the queue * +// is empty, and false otherwise. * +//********************************************* +template +bool DynamicQueue::isEmpty() const +{ + bool status; + + if (numItems > 0) + status = false; + else + status = true; + return status; +} + +//******************************************** +// Function clear dequeues all the elements * +// in the queue. * +//******************************************** +template +void DynamicQueue::clear() +{ + T value; // Dummy variable for dequeue + + while(!isEmpty()) + dequeue(value); +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynamicStack.h b/SourceCode/Chapter 18/DynamicStack.h new file mode 100755 index 0000000..65c6b54 --- /dev/null +++ b/SourceCode/Chapter 18/DynamicStack.h @@ -0,0 +1,124 @@ +#ifndef DYNAMICSTACK_H +#define DYNAMICSTACK_H +#include +using namespace std; + +// Stack template +template +class DynamicStack +{ +private: + // Structure for the stach nodes + struct StackNode + { + T value; // Value in the node + StackNode *next; // Pointer to next node + }; + + StackNode *top; // Pointer to the stack top + +public: + //Constructor + DynamicStack() + { top = nullptr; } + + // Destructor + ~DynamicStack(); + + // Stack operations + void push(T); + void pop(T &); + bool isEmpty(); +}; + +//*************************************************** +// Destructor * +//*************************************************** +template +DynamicStack::~DynamicStack() +{ + StackNode *nodePtr, *nextNode; + + // Position nodePtr at the top of the stack. + nodePtr = top; + + // Traverse the list deleting each node. + while (nodePtr != nullptr) + { + nextNode = nodePtr->next; + delete nodePtr; + nodePtr = nextNode; + } +} + +//************************************************************* +// Member function push pushes the argument onto * +// the stack. * +//************************************************************* + +template +void DynamicStack::push(T item) +{ + StackNode *newNode = nullptr; // Pointer to a new node + + // Allocate a new node and store num there. + newNode = new StackNode; + newNode->value = item; + + // If there are no nodes in the list + // make newNode the first node. + if (isEmpty()) + { + top = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert NewNode before top. + { + newNode->next = top; + top = newNode; + } +} + +//************************************************************* +// Member function pop pops the value at the top * +// of the stack off, and copies it into the variable * +// passed as an argument. * +//************************************************************* + +template +void DynamicStack::pop(T &item) +{ + StackNode *temp = nullptr; // Temporary pointer + + // First make sure the stack isn't empty. + if (isEmpty()) + { + cout << "The stack is empty.\n"; + } + else // pop value off top of stack + { + item = top->value; + temp = top->next; + delete top; + top = temp; + } +} + +//************************************************************* +// Member function isEmpty returns true if the stack * +// is empty, or false otherwise. * +//************************************************************* + +template +bool DynamicStack::isEmpty() +{ + bool status; + + if (!top) + status = true; + else + status = false; + + return status; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/IntQueue.cpp b/SourceCode/Chapter 18/IntQueue.cpp new file mode 100755 index 0000000..3bbc6f7 --- /dev/null +++ b/SourceCode/Chapter 18/IntQueue.cpp @@ -0,0 +1,128 @@ +// Implementation file for the IntQueue class +#include +#include "IntQueue.h" +using namespace std; + +//*************************************************************** +// This constructor creates an empty queue of a specified size. * +//*************************************************************** + +IntQueue::IntQueue(int s) +{ + queueArray = new int[s]; + queueSize = s; + front = -1; + rear = -1; + numItems = 0; +} + +//*************************************************************** +// Copy constructor * +//*************************************************************** + +IntQueue::IntQueue(const IntQueue &obj) +{ + // Allocate the queue array. + queueArray = new int[obj.queueSize]; + + // Copy the other object's attributes. + queueSize = obj.queueSize; + front = obj.front; + rear = obj.rear; + numItems = obj.numItems; + + // Copy the other object's queue array. + for (int count = 0; count < obj.queueSize; count++) + queueArray[count] = obj.queueArray[count]; +} + +//*************************************************************** +// Destructor * +//*************************************************************** + +IntQueue::~IntQueue() +{ + delete [] queueArray; +} + +//*************************************************************** +// Function enqueue inserts a value at the rear of the queue. * +//*************************************************************** + +void IntQueue::enqueue(int num) +{ + if (isFull()) + cout << "The queue is full.\n"; + else + { + // Calculate the new rear position + rear = (rear + 1) % queueSize; + // Insert new item + queueArray[rear] = num; + // Update item count + numItems++; + } +} + +//*************************************************************** +// Function dequeue removes the value at the front of the queue * +// and copies t into num. * +//*************************************************************** + +void IntQueue::dequeue(int &num) +{ + if (isEmpty()) + cout << "The queue is empty.\n"; + else + { + // Move front + front = (front + 1) % queueSize; + // Retrieve the front item + num = queueArray[front]; + // Update item count + numItems--; + } +} + +//*************************************************************** +// isEmpty returns true if the queue is empty, otherwise false. * +//*************************************************************** + +bool IntQueue::isEmpty() const +{ + bool status; + + if (numItems) + status = false; + else + status = true; + + return status; +} + +//*************************************************************** +// isFull returns true if the queue is full, otherwise false. * +//*************************************************************** + +bool IntQueue::isFull() const +{ + bool status; + + if (numItems < queueSize) + status = false; + else + status = true; + + return status; +} + +//***************************************************************** +// clear sets the front and rear indices, and sets numItems to 0. * +//***************************************************************** + +void IntQueue::clear() +{ + front = queueSize - 1; + rear = queueSize - 1; + numItems = 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/IntQueue.h b/SourceCode/Chapter 18/IntQueue.h new file mode 100755 index 0000000..ec40d3b --- /dev/null +++ b/SourceCode/Chapter 18/IntQueue.h @@ -0,0 +1,30 @@ +// Specification file for the IntQueue class +#ifndef INTQUEUE_H +#define INTQUEUE_H + +class IntQueue +{ +private: + int *queueArray; // Points to the queue array + int queueSize; // The queue size + int front; // Subscript of the queue front + int rear; // Subscript of the queue rear + int numItems; // Number of items in the queue +public: + // Constructor + IntQueue(int); + + // Copy constructor + IntQueue(const IntQueue &); + + // Destructor + ~IntQueue(); + + // Queue operations + void enqueue(int); + void dequeue(int &); + bool isEmpty() const; + bool isFull() const; + void clear(); +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/IntStack.cpp b/SourceCode/Chapter 18/IntStack.cpp new file mode 100755 index 0000000..27c882d --- /dev/null +++ b/SourceCode/Chapter 18/IntStack.cpp @@ -0,0 +1,120 @@ +// Implementation file for the IntStach class +#include +#include "IntStack.h" +using namespace std; + +//*********************************************** +// Constructor * +// This constructor creates an empty stack. The * +// size parameter is the size of the stack. * +//*********************************************** + +IntStack::IntStack(int size) +{ + stackArray = new int[size]; + stackSize = size; + top = -1; +} + +//*********************************************** +// Copy constructor * +//*********************************************** + +IntStack::IntStack(const IntStack &obj) +{ + // Create the stack array. + if (obj.stackSize > 0) + stackArray = new int[obj.stackSize]; + else + stackArray = nullptr; + + // Copy the stackSize attribute. + stackSize = obj.stackSize; + + // Copy the stack contents. + for (int count = 0; count < stackSize; count++) + stackArray[count] = obj.stackArray[count]; + + // Set the top of the stack. + top = obj.top; +} + +//*********************************************** +// Destructor * +//*********************************************** + +IntStack::~IntStack() +{ + delete [] stackArray; +} + +//************************************************* +// Member function push pushes the argument onto * +// the stack. * +//************************************************* + +void IntStack::push(int num) +{ + if (isFull()) + { + cout << "The stack is full.\n"; + } + else + { + top++; + stackArray[top] = num; + } +} + +//**************************************************** +// Member function pop pops the value at the top * +// of the stack off, and copies it into the variable * +// passed as an argument. * +//**************************************************** + +void IntStack::pop(int &num) +{ + if (isEmpty()) + { + cout << "The stack is empty.\n"; + } + else + { + num = stackArray[top]; + top--; + } +} + +//*************************************************** +// Member function isFull returns true if the stack * +// is full, or false otherwise. * +//*************************************************** + +bool IntStack::isFull() const +{ + bool status; + + if (top == stackSize - 1) + status = true; + else + status = false; + + return status; +} + +//**************************************************** +// Member funciton isEmpty returns true if the stack * +// is empty, or false otherwise. * +//**************************************************** + +bool IntStack::isEmpty() const +{ + bool status; + + if (top == -1) + status = true; + else + status = false; + + return status; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/IntStack.h b/SourceCode/Chapter 18/IntStack.h new file mode 100755 index 0000000..67245a3 --- /dev/null +++ b/SourceCode/Chapter 18/IntStack.h @@ -0,0 +1,28 @@ +// Specification file for the IntStack class +#ifndef INTSTACK_H +#define INTSTACK_H + +class IntStack +{ +private: + int *stackArray; // Pointer to the stack array + int stackSize; // The stack size + int top; // Indicates the top of the stack + +public: + // Constructor + IntStack(int); + + // Copy constructor + IntStack(const IntStack &); + + // Destructor + ~IntStack(); + + // Stack operations + void push(int); + void pop(int &); + bool isFull() const; + bool isEmpty() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/MathStack.cpp b/SourceCode/Chapter 18/MathStack.cpp new file mode 100755 index 0000000..17adb6d --- /dev/null +++ b/SourceCode/Chapter 18/MathStack.cpp @@ -0,0 +1,46 @@ +// Implementation file for the MathStack class +#include "MathStack.h" + +//*********************************************** +// Member function add. add pops * +// the first two values off the stack and * +// adds them. The sum is pushed onto the stack. * +//*********************************************** + +void MathStack::add() +{ + int num, sum; + + // Pop the first two values off the stack. + pop(sum); + pop(num); + + // Add the two values, store in sum. + sum += num; + + // Push sum back onto the stack. + push(sum); +} + +//*********************************************** +// Member function sub. sub pops the * +// first two values off the stack. The * +// second value is subtracted from the * +// first value. The difference is pushed * +// onto the stack. * +//*********************************************** + +void MathStack::sub() +{ + int num, diff; + + // Pop the first two values off the stack. + pop(diff); + pop(num); + + // Subtract num from diff. + diff -= num; + + // Push diff back onto the stack. + push(diff); +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/MathStack.h b/SourceCode/Chapter 18/MathStack.h new file mode 100755 index 0000000..dc57ce4 --- /dev/null +++ b/SourceCode/Chapter 18/MathStack.h @@ -0,0 +1,16 @@ +// Specification file for the MathStack class +#ifndef MATHSTACK_H +#define MATHSTACK_H +#include "IntStack.h" + +class MathStack : public IntStack +{ +public: + // Constructor + MathStack(int s) : IntStack(s) {} + + // MathStack operations + void add(); + void sub(); +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-1.cpp b/SourceCode/Chapter 18/Pr18-1.cpp new file mode 100755 index 0000000..7254008 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-1.cpp @@ -0,0 +1,38 @@ +// This program demonstrates the IntStack class. +#include +#include "IntStack.h" +using namespace std; + +int main() +{ + int catchVar; // To hold values popped off the stack + + // Define a stack object to hold 5 values. + IntStack stack(5); + + // Push the values 5, 10, 15, 20, and 25 onto the stack. + cout << "Pushing 5\n"; + stack.push(5); + cout << "Pushing 10\n"; + stack.push(10); + cout << "Pushing 15\n"; + stack.push(15); + cout << "Pushing 20\n"; + stack.push(20); + cout << "Pushing 25\n"; + stack.push(25); + + // Pop the values off the stack. + cout << "Popping...\n"; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-10.cpp b/SourceCode/Chapter 18/Pr18-10.cpp new file mode 100755 index 0000000..165c42c --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-10.cpp @@ -0,0 +1,32 @@ +// This program demonstrates the DynamicQueue template. +#include +#include +#include "DynamicQueue.h" +using namespace std; + +const int QUEUE_SIZE = 5; + +int main() +{ + string name; + + // Create a Queue. + DynamicQueue queue; + + // Enqueue some names. + for (int count = 0; count < QUEUE_SIZE; count++) + { + cout << "Enter an name: "; + getline(cin, name); + queue.enqueue(name); + } + + // Dequeue the names and display them. + cout << "\nHere are the names you entered:\n"; + for (int count = 0; count < QUEUE_SIZE; count++) + { + queue.dequeue(name); + cout << name << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-11.cpp b/SourceCode/Chapter 18/Pr18-11.cpp new file mode 100755 index 0000000..d87e044 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-11.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the STL deque container. +#include +#include +using namespace std; + +int main() +{ + const int MAX = 8; // Max value + int count; // Loop counter + + // Create a deque object. + deque iDeque; + + // Enqueue a series of numbers. + cout << "I will now enqueue items...\n"; + for (count = 2; count < MAX; count += 2) + { + cout << "Pushing " << count << endl; + iDeque.push_back(count); + } + + // Dequeue and display the numbers. + cout << "I will now dequeue items...\n"; + for (count = 2; count < MAX; count += 2) + { + cout << "Popping "<< iDeque.front() << endl; + iDeque.pop_front(); + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-12.cpp b/SourceCode/Chapter 18/Pr18-12.cpp new file mode 100755 index 0000000..2e753c2 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-12.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the STL queue container adapter. +#include +#include +using namespace std; + +int main() +{ + const int MAX = 8; // Max value + int count; // Loop counter + + // Define a queue object. + queue iQueue; + + // Enqueue a series of numbers. + cout << "I will now enqueue items...\n"; + for (count = 2; count < MAX; count += 2) + { + cout << "Pushing " << count << endl; + iQueue.push(count); + } + + // Dequeue and display the numbers. + cout << "I will now dequeue items...\n"; + for (count = 2; count < MAX; count += 2) + { + cout << "Popping " << iQueue.front() << endl; + iQueue.pop(); + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-2.cpp b/SourceCode/Chapter 18/Pr18-2.cpp new file mode 100755 index 0000000..48b9a0f --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-2.cpp @@ -0,0 +1,41 @@ +// This program demonstrates the MathStack class. +#include +#include "MathStack.h" +using namespace std; + +int main() +{ + int catchVar; // To hold values popped off the stack + + // Create a MathStack object. + MathStack stack(5); + + // Push 3 and 6 onto the stack. + cout << "Pushing 3\n"; + stack.push(3); + cout << "Pushing 6\n"; + stack.push(6); + + // Add the two values. + stack.add(); + + // Pop the sum off the stack and display it. + cout << "The sum is "; + stack.pop(catchVar); + cout << catchVar << endl << endl; + + // Push 7 and 10 onto the stack + cout << "Pushing 7\n"; + stack.push(7); + cout << "Pushing 10\n"; + stack.push(10); + + // Subtract 7 from 10. + stack.sub(); + + // Pop the difference off the stack and display it. + cout << "The difference is "; + stack.pop(catchVar); + cout << catchVar << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-3.cpp b/SourceCode/Chapter 18/Pr18-3.cpp new file mode 100755 index 0000000..eacc704 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-3.cpp @@ -0,0 +1,124 @@ +// This program demonstrates the Stack template. +#include +#include +#include "Stack.h" +using namespace std; + +// Constants for the menu choices +const int PUSH_CHOICE = 1, + POP_CHOICE = 2, + QUIT_CHOICE = 3; + +// Function prototypes +void menu(int &); +void getStackSize(int &); +void pushItem(Stack&); +void popItem(Stack&); + +int main() +{ + int stackSize; // The stack size + int choice; // To hold a menu choice + + // Get the stack size. + getStackSize(stackSize); + + // Create the stack. + Stack stack(stackSize); + + do + { + // Get the user's menu choice. + menu(choice); + + // Perform the user's choice. + if (choice != QUIT_CHOICE) + { + switch (choice) + { + case PUSH_CHOICE: + pushItem(stack); + break; + case POP_CHOICE: + popItem(stack); + } + } + } while (choice != QUIT_CHOICE); + + return 0; +} + +//************************************************ +// The getStackSize function gets the desired * +// stack size, which is assigned to the * +// reference parameter. * +//************************************************ +void getStackSize(int &size) +{ + // Get the desired stack size. + cout << "How big should I make the stack? "; + cin >> size; + + // Validate the size. + while (size < 1) + { + cout << "Enter 1 or greater: "; + cin >> size; + } +} + +//************************************************ +// The menu function displays the menu and gets * +// the user's choice, which is assigned to the * +// reference parameter. * +//************************************************ +void menu(int &choice) +{ + // Display the menu and get the user's choice. + cout << "\nWhat do you want to do?\n" + << PUSH_CHOICE + << " - Push an item onto the stack\n" + << POP_CHOICE + << " - Pop an item off the stack\n" + << QUIT_CHOICE + << " - Quit the program\n" + << "Enter your choice: "; + cin >> choice; + + // Validate the choice + while (choice < PUSH_CHOICE || choice > QUIT_CHOICE) + { + cout << "Enter a valid choice: "; + cin >> choice; + } +} + +//************************************************ +// The pushItem function gets an item from the * +// user and pushes it onto the stack. * +//************************************************ +void pushItem(Stack &stack) +{ + string item; + + // Get an item to push onto the stack. + cin.ignore(); + cout << "\nEnter an item: "; + getline(cin, item); + stack.push(item); +} + +//*************************************************** +// The popItem function pops an item from the stack * +//*************************************************** +void popItem(Stack &stack) +{ + string item = ""; + + // Pop the item. + stack.pop(item); + + // Display the item. + if (item != "") + cout << item << " was popped.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-4.cpp b/SourceCode/Chapter 18/Pr18-4.cpp new file mode 100755 index 0000000..ed63e73 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-4.cpp @@ -0,0 +1,35 @@ +// This program demonstrates the dynamic stack +// class DynIntClass. +#include +#include "DynIntStack.h" +using namespace std; + +int main() +{ + int catchVar; // To hold values popped off the stack + + // Create a DynIntStack object. + DynIntStack stack; + + // Push 5, 10, and 15 onto the stack. + cout << "Pushing 5\n"; + stack.push(5); + cout << "Pushing 10\n"; + stack.push(10); + cout << "Pushing 15\n"; + stack.push(15); + + // Pop the values off the stack and display them. + cout << "Popping...\n"; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + + // Try to pop another value off the stack. + cout << "\nAttempting to pop again... "; + stack.pop(catchVar); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-5.cpp b/SourceCode/Chapter 18/Pr18-5.cpp new file mode 100755 index 0000000..4fcf121 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-5.cpp @@ -0,0 +1,100 @@ +#include +#include +#include "DynamicStack.h" +using namespace std; + +// Constants for the menu choices +const int PUSH_CHOICE = 1, + POP_CHOICE = 2, + QUIT_CHOICE = 3; + +// Function prototypes +void menu(int &); +void getStackSize(int &); +void pushItem(DynamicStack &); +void popItem(DynamicStack &); + +int main() +{ + int choice; // To hold a menu choice + + // Create the stack. + DynamicStack stack; + + do + { + // Get the user's menu choice. + menu(choice); + + // Perform the user's choice. + if (choice != QUIT_CHOICE) + { + switch (choice) + { + case PUSH_CHOICE: + pushItem(stack); + break; + case POP_CHOICE: + popItem(stack); + } + } + } while (choice != QUIT_CHOICE); + + return 0; +} + +//************************************************ +// The menu function displays the menu and gets * +// the user's choice, which is assigned to the * +// reference parameter. * +//************************************************ +void menu(int &choice) +{ + // Display the menu and get the user's choice. + cout << "What do you want to do?\n" + << PUSH_CHOICE + << " - Push an item onto the stack\n" + << POP_CHOICE + << " - Pop an item off the stack\n" + << QUIT_CHOICE + << " - Quit the program\n" + << "Enter your choice: "; + cin >> choice; + + // Validate the choice + while (choice < PUSH_CHOICE || choice > QUIT_CHOICE) + { + cout << "Enter a valid choice: "; + cin >> choice; + } +} + +//************************************************ +// The pushItem function gets an item from the * +// user and pushes it onto the stack. * +//************************************************ +void pushItem(DynamicStack &stack) +{ + string item; + + // Get an item to push onto the stack. + cin.ignore(); + cout << "\nEnter an item: "; + getline(cin, item); + stack.push(item); +} + +//*************************************************** +// The popItem function pops an item from the stack * +//*************************************************** +void popItem(DynamicStack &stack) +{ + string item = ""; + + // Pop the item. + stack.pop(item); + + // Display the item. + if (item != "") + cout << item << " was popped.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-6.cpp b/SourceCode/Chapter 18/Pr18-6.cpp new file mode 100755 index 0000000..265419b --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-6.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the STL stack +// container adapter. +#include +#include +#include +using namespace std; + +int main() +{ + const int MAX = 8; // Max value to store in the stack + int count; // Loop counter + + // Define an STL stack + stack< int, vector > iStack; + + // Push values onto the stack. + for (count = 2; count < MAX; count += 2) + { + cout << "Pushing " << count << endl; + iStack.push(count); + } + + // Display the size of the stack. + cout << "The size of the stack is "; + cout << iStack.size() << endl; + + // Pop the values of the stack. + for (count = 2; count < MAX; count += 2) + { + cout << "Popping " << iStack.top() << endl; + iStack.pop(); + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-7.cpp b/SourceCode/Chapter 18/Pr18-7.cpp new file mode 100755 index 0000000..0e74a8b --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-7.cpp @@ -0,0 +1,31 @@ +// This program demonstrates the IntQueue class. +#include +#include "IntQueue.h" +using namespace std; + +int main() +{ + const int MAX_VALUES = 5; // Max number of values + + // Create an IntQueue to hold the values. + IntQueue iQueue(MAX_VALUES); + + // Enqueue a series of items. + cout << "Enqueuing " << MAX_VALUES << " items...\n"; + for (int x = 0; x < MAX_VALUES; x++) + iQueue.enqueue(x); + + // Attempt to enqueue just one more item. + cout << "Now attempting to enqueue again...\n"; + iQueue.enqueue(MAX_VALUES); + + // Dequeue and retrieve all items in the queue. + cout << "The values in the queue were:\n"; + while (!iQueue.isEmpty()) + { + int value; + iQueue.dequeue(value); + cout << value << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-8.cpp b/SourceCode/Chapter 18/Pr18-8.cpp new file mode 100755 index 0000000..dec173e --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-8.cpp @@ -0,0 +1,32 @@ +// This program demonstrates the Queue template. +#include +#include +#include "Queue.h" +using namespace std; + +const int QUEUE_SIZE = 5; + +int main() +{ + string name; + + // Create a Queue. + Queue queue(QUEUE_SIZE); + + // Enqueue some names. + for (int count = 0; count < QUEUE_SIZE; count++) + { + cout << "Enter an name: "; + getline(cin, name); + queue.enqueue(name); + } + + // Dequeue the names and display them. + cout << "\nHere are the names you entered:\n"; + for (int count = 0; count < QUEUE_SIZE; count++) + { + queue.dequeue(name); + cout << name << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-9.cpp b/SourceCode/Chapter 18/Pr18-9.cpp new file mode 100755 index 0000000..8b053a6 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-9.cpp @@ -0,0 +1,27 @@ +// This program demonstrates the DynIntQueue class. +#include +#include "DynIntQueue.h" +using namespace std; + +int main() +{ + const int MAX_VALUES = 5; + + // Create a DynIntQueue object. + DynIntQueue iQueue; + + // Enqueue a series of numbers. + cout << "Enqueuing " << MAX_VALUES << " items...\n"; + for (int x = 0; x < 5; x++) + iQueue.enqueue(x); + + // Dequeue and retrieve all numbers in the queue + cout << "The values in the queue were:\n"; + while (!iQueue.isEmpty()) + { + int value; + iQueue.dequeue(value); + cout << value << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Queue.h b/SourceCode/Chapter 18/Queue.h new file mode 100755 index 0000000..7b2d91c --- /dev/null +++ b/SourceCode/Chapter 18/Queue.h @@ -0,0 +1,157 @@ +#ifndef QUEUE_H +#define QUEUE_H +#include +using namespace std; + +// Stack template +template +class Queue +{ +private: + T *queueArray; // Points to the queue array + int queueSize; // The queue size + int front; // Subscript of the queue front + int rear; // Subscript of the queue rear + int numItems; // Number of items in the queue +public: + // Constructor + Queue(int); + + // Copy constructor + Queue(const Queue &); + + // Destructor + ~Queue(); + + // Queue operations + void enqueue(T); + void dequeue(T &); + bool isEmpty() const; + bool isFull() const; + void clear(); +}; + +//*************************************************************** +// This constructor creates an empty queue of a specified size. * +//*************************************************************** +template +Queue::Queue(int s) +{ + queueArray = new T[s]; + queueSize = s; + front = -1; + rear = -1; + numItems = 0; +} + +//*************************************************************** +// Copy constructor * +//*************************************************************** +template +Queue::Queue(const Queue &obj) +{ + // Allocate the queue array. + queueArray = new T[obj.queueSize]; + + // Copy the other object's attributes. + queueSize = obj.queueSize; + front = obj.front; + rear = obj.rear; + numItems = obj.numItems; + + // Copy the other object's queue array. + for (int count = 0; count < obj.queueSize; count++) + queueArray[count] = obj.queueArray[count]; +} + +//*************************************************************** +// Destructor * +//*************************************************************** +template +Queue::~Queue() +{ + delete [] queueArray; +} + +//*************************************************************** +// Function enqueue inserts a value at the rear of the queue. * +//*************************************************************** +template +void Queue::enqueue(T item) +{ + if (isFull()) + cout << "The queue is full.\n"; + else + { + // Calculate the new rear position + rear = (rear + 1) % queueSize; + // Insert new item + queueArray[rear] = item; + // Update item count + numItems++; + } +} + +//*************************************************************** +// Function dequeue removes the value at the front of the queue * +// and copies t into num. * +//*************************************************************** +template +void Queue::dequeue(T &item) +{ + if (isEmpty()) + cout << "The queue is empty.\n"; + else + { + // Move front + front = (front + 1) % queueSize; + // Retrieve the front item + item = queueArray[front]; + // Update item count + numItems--; + } +} + +//*************************************************************** +// isEmpty returns true if the queue is empty, otherwise false. * +//*************************************************************** +template +bool Queue::isEmpty() const +{ + bool status; + + if (numItems) + status = false; + else + status = true; + + return status; +} + +//*************************************************************** +// isFull returns true if the queue is full, otherwise false. * +//*************************************************************** +template +bool Queue::isFull() const +{ + bool status; + + if (numItems < queueSize) + status = false; + else + status = true; + + return status; +} + +//***************************************************************** +// clear sets the front and rear indices, and sets numItems to 0. * +//***************************************************************** +template +void Queue::clear() +{ + front = queueSize - 1; + rear = queueSize - 1; + numItems = 0; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/Stack.h b/SourceCode/Chapter 18/Stack.h new file mode 100755 index 0000000..5c18d0e --- /dev/null +++ b/SourceCode/Chapter 18/Stack.h @@ -0,0 +1,153 @@ +#ifndef STACK_H +#define STACK_H +#include +using namespace std; + +// Stack template +template +class Stack +{ +private: + T *stackArray; + int stackSize; + int top; + +public: + //Constructor + Stack(int); + + // Copy constructor + Stack(const Stack&); + + // Destructor + ~Stack(); + + // Stack operations + void push(T); + void pop(T &); + bool isFull(); + bool isEmpty(); +}; + +//*************************************************** +// Constructor * +//*************************************************** + +template +Stack::Stack(int size) +{ + stackArray = new T[size]; + stackSize = size; + top = -1; +} + +//*************************************************** +// Copy constructor * +//*************************************************** + +template +Stack::Stack(const Stack &obj) +{ + // Create the stack array. + if (obj.stackSize > 0) + stackArray = new T[obj.stackSize]; + else + stackArray = nullptr; + + // Copy the stackSize attribute. + stackSize = obj.stackSize; + + // Copy the stack contents. + for (int count = 0; count < stackSize; count++) + stackArray[count] = obj.stackArray[count]; + + // Set the top of the stack. + top = obj.top; +} + +//*************************************************** +// Destructor * +//*************************************************** + +template +Stack::~Stack() +{ + if (stackSize > 0) + delete [] stackArray; +} + +//************************************************************* +// Member function push pushes the argument onto * +// the stack. * +//************************************************************* + +template +void Stack::push(T item) +{ + if (isFull()) + { + cout << "The stack is full.\n"; + } + else + { + top++; + stackArray[top] = item; + } +} + +//************************************************************* +// Member function pop pops the value at the top * +// of the stack off, and copies it into the variable * +// passed as an argument. * +//************************************************************* + +template +void Stack::pop(T &item) +{ + if (isEmpty()) + { + cout << "The stack is empty.\n"; + } + else + { + item = stackArray[top]; + top--; + } +} + +//************************************************************* +// Member function isFull returns true if the stack * +// is full, or false otherwise. * +//************************************************************* + +template +bool Stack::isFull() +{ + bool status; + + if (top == stackSize - 1) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Member function isEmpty returns true if the stack * +// is empty, or false otherwise. * +//************************************************************* + +template +bool Stack::isEmpty() +{ + bool status; + + if (top == -1) + status = true; + else + status = false; + + return status; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 19/NumberList.cpp b/SourceCode/Chapter 19/NumberList.cpp new file mode 100755 index 0000000..ccde20f --- /dev/null +++ b/SourceCode/Chapter 19/NumberList.cpp @@ -0,0 +1,215 @@ +// Implementation file for the NumberList class +#include // For cout +#include "NumberList.h" +using namespace std; + +//************************************************** +// appendNode appends a node containing the * +// value pased into num, to the end of the list. * +//************************************************** + +void NumberList::appendNode(double num) +{ + ListNode *newNode; // To point to a new node + ListNode *nodePtr; // To move through the list + + // Allocate a new node and store num there. + newNode = new ListNode; + newNode->value = num; + newNode->next = nullptr; + + // If there are no nodes in the list + // make newNode the first node. + if (!head) + head = newNode; + else // Otherwise, insert newNode at end. + { + // Initialize nodePtr to head of list. + nodePtr = head; + + // Find the last node in the list. + while (nodePtr->next) + nodePtr = nodePtr->next; + + // Insert newNode as the last node. + nodePtr->next = newNode; + } +} + +//************************************************** +// displayList shows the value * +// stored in each node of the linked list * +// pointed to by head. * +//************************************************** + +void NumberList::displayList() const +{ + ListNode *nodePtr; // To move through the list + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr points to a node, traverse + // the list. + while (nodePtr) + { + // Display the value in this node. + cout << nodePtr->value << endl; + + // Move to the next node. + nodePtr = nodePtr->next; + } +} + +//************************************************** +// The insertNode function inserts a node with * +// num copied to its value member. * +//************************************************** + +void NumberList::insertNode(double num) +{ + ListNode *newNode; // A new node + ListNode *nodePtr; // To traverse the list + ListNode *previousNode = nullptr; // The previous node + + // Allocate a new node and store num there. + newNode = new ListNode; + newNode->value = num; + + // If there are no nodes in the list + // make newNode the first node + if (!head) + { + head = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert newNode + { + // Position nodePtr at the head of list. + nodePtr = head; + + // Initialize previousNode to nullptr. + previousNode = nullptr; + + // Skip all nodes whose value is less than num. + while (nodePtr != nullptr && nodePtr->value < num) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If the new node is to be the 1st in the list, + // insert it before all other nodes. + if (previousNode == nullptr) + { + head = newNode; + newNode->next = nodePtr; + } + else // Otherwise insert after the previous node. + { + previousNode->next = newNode; + newNode->next = nodePtr; + } + } +} + +//************************************************** +// The deleteNode function searches for a node * +// with num as its value. The node, if found, is * +// deleted from the list and from memory. * +//************************************************** + +void NumberList::deleteNode(double num) +{ + ListNode *nodePtr; // To traverse the list + ListNode *previousNode; // To point to the previous node + + // If the list is empty, do nothing. + if (!head) + return; + + // Determine if the first node is the one. + if (head->value == num) + { + nodePtr = head->next; + delete head; + head = nodePtr; + } + else + { + // Initialize nodePtr to head of list + nodePtr = head; + + // Skip all nodes whose value member is + // not equal to num. + while (nodePtr != nullptr && nodePtr->value != num) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If nodePtr is not at the end of the list, + // link the previous node to the node after + // nodePtr, then delete nodePtr. + if (nodePtr) + { + previousNode->next = nodePtr->next; + delete nodePtr; + } + } +} + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +NumberList::~NumberList() +{ + ListNode *nodePtr; // To traverse the list + ListNode *nextNode; // To point to the next node + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr is not at the end of the list... + while (nodePtr != nullptr) + { + // Save a pointer to the next node. + nextNode = nodePtr->next; + + // Delete the current node. + delete nodePtr; + + // Position nodePtr at the next node. + nodePtr = nextNode; + } +} + +//************************************************** +// countNodes is a recursive function that returns * +// the number of nodes in the list. * +//************************************************** + +int NumberList::countNodes(ListNode *nodePtr) const +{ + if (nodePtr != nullptr) + return 1 + countNodes(nodePtr->next); + else + return 0; +} + +//**************************************************** +// showReverse is a recursive function that displays * +// the values stored in the list in reverse. The * +// function is called from DisplayBackwards. * +//**************************************************** + +void NumberList::showReverse(ListNode *nodePtr) const +{ + if (nodePtr != nullptr) + { + showReverse(nodePtr->next); + cout << nodePtr->value << " "; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/NumberList.h b/SourceCode/Chapter 19/NumberList.h new file mode 100755 index 0000000..11bc3cb --- /dev/null +++ b/SourceCode/Chapter 19/NumberList.h @@ -0,0 +1,39 @@ +// Specification file for the NumberList class +#ifndef NUMBERLIST_H +#define NUMBERLIST_H + +class NumberList +{ +private: + // Declare a structure for the list + struct ListNode + { + double value; + struct ListNode *next; + }; + + ListNode *head; // List head pointer + + // Private member functions + int countNodes(ListNode *) const; + void showReverse(ListNode *) const; + +public: + // Constructor + NumberList() + { head = nullptr; } + + // Destructor + ~NumberList(); + + // Linked List Operations + void appendNode(double); + void insertNode(double); + void deleteNode(double); + void displayList() const; + int numNodes() const + { return countNodes(head); } + void displayBackwards() const + { showReverse(head); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-1.cpp b/SourceCode/Chapter 19/Pr19-1.cpp new file mode 100755 index 0000000..be97492 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-1.cpp @@ -0,0 +1,28 @@ +// This program demonstrates a simple recursive function. +#include +using namespace std; + +// Function prototype +void message(int); + +int main() +{ + message(5); + return 0; +} + +//*********************************************************** +// Definition of function Message. If the value in times is * +// greater than 0, the message is displayed and the * +// function is recursively called with the argument * +// times - 1. * +//*********************************************************** + +void message(int times) +{ + if (times > 0) + { + cout << "This is a recursive function.\n"; + message(times - 1); + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-10.cpp b/SourceCode/Chapter 19/Pr19-10.cpp new file mode 100755 index 0000000..fb5762e --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-10.cpp @@ -0,0 +1,41 @@ +// This program displays a solution to the Towers of +// Hanoi game. +#include +using namespace std; + +// Function prototype +void moveDiscs(int, int, int, int); + +int main() +{ + const int NUM_DISCS = 3; // Number of discs to move + const int FROM_PEG = 1; // Initial "from" peg + const int TO_PEG = 3; // Initial "to" peg + const int TEMP_PEG = 2; // Initial "temp" peg + + // Play the game. + moveDiscs(NUM_DISCS, FROM_PEG, TO_PEG, TEMP_PEG); + cout << "All the pegs are moved!\n"; + return 0; +} + +//*************************************************** +// The moveDiscs function displays a disc move in * +// the Towers of Hanoi game. * +// The parameters are: * +// num: The number of discs to move. * +// fromPeg: The peg to move from. * +// toPeg: The peg to move to. * +// tempPeg: The temporary peg. * +//*************************************************** + +void moveDiscs(int num, int fromPeg, int toPeg, int tempPeg) +{ + if (num > 0) + { + moveDiscs(num - 1, fromPeg, tempPeg, toPeg); + cout << "Move a disc from peg " << fromPeg + << " to peg " << toPeg << endl; + moveDiscs(num - 1, tempPeg, toPeg, fromPeg); + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-11.cpp b/SourceCode/Chapter 19/Pr19-11.cpp new file mode 100755 index 0000000..1f05ec2 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-11.cpp @@ -0,0 +1,89 @@ +// This program demonstrates the QuickSort Algorithm. +#include +using namespace std; + +// Function prototypes +void quickSort(int [], int, int); +int partition(int [], int, int); +void swap(int &, int &); + +int main() +{ + const int SIZE = 10; // Array size + int count; // Loop counter + int array[SIZE] = {7, 3, 9, 2, 0, 1, 8, 4, 6, 5}; + + // Display the array contents. + for (count = 0; count < SIZE; count++) + cout << array[count] << " "; + cout << endl; + + // Sort the array. + quickSort(array, 0, SIZE - 1); + + // Display the array contents. + for (count = 0; count < SIZE; count++) + cout << array[count] << " "; + cout << endl; + return 0; +} + +//************************************************ +// quickSort uses the quicksort algorithm to * +// sort set, from set[start] through set[end]. * +//************************************************ + +void quickSort(int set[], int start, int end) +{ + int pivotPoint; + + if (start < end) + { + // Get the pivot point. + pivotPoint = partition(set, start, end); + // Sort the first sub list. + quickSort(set, start, pivotPoint - 1); + // Sort the second sub list. + quickSort(set, pivotPoint + 1, end); + } +} + +//********************************************************** +// partition selects the value in the middle of the * +// array set as the pivot. The list is rearranged so * +// all the values less than the pivot are on its left * +// and all the values greater than pivot are on its right. * +//********************************************************** + +int partition(int set[], int start, int end) +{ + int pivotValue, pivotIndex, mid; + + mid = (start + end) / 2; + swap(set[start], set[mid]); + pivotIndex = start; + pivotValue = set[start]; + for (int scan = start + 1; scan <= end; scan++) + { + if (set[scan] < pivotValue) + { + pivotIndex++; + swap(set[pivotIndex], set[scan]); + } + } + swap(set[start], set[pivotIndex]); + return pivotIndex; +} + +//********************************************** +// swap simply exchanges the contents of * +// value1 and value2. * +//********************************************** + +void swap(int &value1, int &value2) +{ + int temp = value1; + + value1 = value2; + value2 = temp; +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-12.cpp b/SourceCode/Chapter 19/Pr19-12.cpp new file mode 100755 index 0000000..d411b27 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-12.cpp @@ -0,0 +1,108 @@ +// This program demonstrates a recursive function that exhaustively +// searches through all possible combinations of coin values to find +// the best way to make change for a specified amount. +#include +using namespace std; + +// Constants +const int MAX_COINS_CHANGE = 100; // Max number of coins to give in change +const int MAX_COIN_VALUES = 6; // Max number of coin values +const int NO_SOLUTION = INT_MAX; // Indicates no solution + +// Function prototype +void makeChange(int, int, int[], int); + +// coinValues - global array of coin values to choose from +int coinValues[MAX_COIN_VALUES] = {100, 50, 25, 10, 5, 1 }; + +// bestCoins - global array of best coins to make change with +int bestCoins[MAX_COINS_CHANGE]; + +// Global variables +int numBestCoins = NO_SOLUTION, // Number of coins in bestCoins + numSolutions = 0, // Number of ways to make change + numCoins; // Number of allowable coins + + +int main() +{ + int coinsUsed[MAX_COINS_CHANGE], // List of coins used + numCoinsUsed = 0, // The number coins used + amount; // The amount to make change for + + // Display the possible coin values. + cout << "Here are the valid coin values, in cents: "; + for (int index = 0; index < 5; index++) + cout << coinValues[index] << " "; + cout << endl; + + // Get input from the user. + cout << "Enter the amount of cents (as an integer) " + << "to make change for: "; + cin >> amount; + cout << "What is the maximum number of coins to give as change? "; + cin >> numCoins; + + // Call the recursive function. + makeChange(numCoins, amount, coinsUsed, numCoinsUsed); + + // Display the results. + cout << "Number of possible combinations: " << numSolutions << endl; + cout << "Best combination of coins:\n"; + if (numBestCoins == NO_SOLUTION) + cout << "\tNo solution\n"; + else + { + for (int count = 0; count < numBestCoins; count++) + cout << bestCoins[count] << " "; + } + cout << endl; + return 0; +} + +//********************************************************************** +// Function makeChange. This function uses the following parameters: * +// coinsLeft - The number of coins left to choose from. * +// amount - The amount to make change for. * +// coinsUsed - An array that contains the coin values used so far. * +// numCoinsUsed - The number of values in the coinsUsed array. * +// * +// This recursive function finds all the possible ways to make change * +// for the value in amount. The best combination of coins is stored in * +// the array bestCoins. * +//********************************************************************** + +void makeChange(int coinsLeft, int amount, int coinsUsed[], + int numCoinsUsed) +{ + int coinPos, // To calculate array position of coin being used + count; // Loop counter + + if (coinsLeft == 0) // If no more coins are left + return; + else if (amount < 0) // If amount to make change for is negative + return; + else if (amount == 0) // If solution is found + { + // Store as bestCoins if best + if (numCoinsUsed < numBestCoins) + { + for (count = 0; count < numCoinsUsed; count++) + bestCoins[count] = coinsUsed[count]; + numBestCoins = numCoinsUsed; + } + numSolutions++; + return; + } + + // Find the other combinations using the coin + coinPos = numCoins - coinsLeft; + coinsUsed[numCoinsUsed] = coinValues[coinPos]; + numCoinsUsed++; + makeChange(coinsLeft, amount - coinValues[coinPos], + coinsUsed, numCoinsUsed); + + // Find the other combinations not using the coin. + numCoinsUsed--; + makeChange(coinsLeft - 1, amount, coinsUsed, numCoinsUsed); +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-2.cpp b/SourceCode/Chapter 19/Pr19-2.cpp new file mode 100755 index 0000000..c4e2199 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-2.cpp @@ -0,0 +1,32 @@ +// This program demonstrates a simple recursive function. +#include +using namespace std; + +// Function prototype +void message(int); + +int main() +{ + message(5); + return 0; +} + +//************************************************************ +// Definition of function message. If the value in times is * +// greater than 0, the message is displayed and the function * +// is recursively called with the argument times - 1. * +//************************************************************ + +void message(int times) +{ + cout << "message called with " << times << " in times.\n"; + + if (times > 0) + { + cout << "This is a recursive function.\n"; + message(times - 1); + } + + cout << "message returning with " << times; + cout << " in times.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-3.cpp b/SourceCode/Chapter 19/Pr19-3.cpp new file mode 100755 index 0000000..413538a --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-3.cpp @@ -0,0 +1,35 @@ +// This program demonstrates a recursive function to +// calculate the factorial of a number. +#include +using namespace std; + +// Function prototype +int factorial(int); + +int main() +{ + int number; + + // Get a number from the user. + cout << "Enter an integer value and I will display\n"; + cout << "its factorial: "; + cin >> number; + + // Display the factorial of the number. + cout << "The factorial of " << number << " is "; + cout << factorial(number) << endl; + return 0; +} + +//************************************************************* +// Definition of factorial. A recursive function to calculate * +// the factorial of the parameter n. * +//************************************************************* + +int factorial(int n) +{ + if (n == 0) + return 1; // Base case + else + return n * factorial(n - 1); // Recursive case +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-4.cpp b/SourceCode/Chapter 19/Pr19-4.cpp new file mode 100755 index 0000000..62b1226 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-4.cpp @@ -0,0 +1,50 @@ +// This program demonstrates a recursive function for counting +// the number of times a character appears in a string. +#include +#include +using namespace std; + +// Function prototype +int numChars(char, string, int); + +int main() +{ + string str = "abcddddef"; + + // Display the number of times the letter + // 'd' appears in the string. + cout << "The letter d appears " + << numChars('d', str, 0) << " times.\n"; + + return 0; +} + +//************************************************ +// Function numChars. This recursive function * +// counts the number of times the character * +// search appears in the string str. The search * +// begins at the subscript stored in subscript. * +//************************************************ + +int numChars(char search, string str, int subscript) +{ + if (subscript >= str.length()) + { + // Base case: The end of the string is reached. + return 0; + } + else if (str[subscript] == search) + { + // Recursive case: A matching character was found. + // Return 1 plus the number of times the search + // search appears in the rest of the string. + return 1 + numChars(search, str, subscript+1); + } + else + { + // Recursive case: A character that does not match the + // search character was found. Return the number of times + // the search character appears in the rest of the string. + return numChars(search, str, subscript+1); + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-5.cpp b/SourceCode/Chapter 19/Pr19-5.cpp new file mode 100755 index 0000000..e3114f3 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-5.cpp @@ -0,0 +1,36 @@ +// This program demonstrates a recursive function to calculate +// the greatest common divisor (gcd) of two numbers. +#include +using namespace std; + +// Function prototype +int gcd(int, int); + +int main() +{ + int num1, num2; + + // Get two numbers. + cout << "Enter two integers: "; + cin >> num1 >> num2; + + // Display the GCD of the numbers. + cout << "The greatest common divisor of " << num1; + cout << " and " << num2 << " is "; + cout << gcd(num1, num2) << endl; + return 0; +} + +//********************************************************* +// Definition of gcd. This function uses recursion to * +// calculate the greatest common divisor of two integers, * +// passed into the parameters x and y. * +//********************************************************* + +int gcd(int x, int y) +{ + if (x % y == 0) + return y; // Base case + else + return gcd(y, x % y); // Recusrsive case +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-6.cpp b/SourceCode/Chapter 19/Pr19-6.cpp new file mode 100755 index 0000000..aeab8df --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-6.cpp @@ -0,0 +1,32 @@ +// This program demonstrates a recursive function +// that calculates Fibonacci numbers. +#include +using namespace std; + +// Function prototype +int fib(int); + +int main() +{ + cout << "The first 10 Fibonacci numbers are:\n"; + for (int x = 0; x < 10; x++) + cout << fib(x) << " "; + cout << endl; + return 0; +} + +//***************************************** +// Function fib. Accepts an int argument * +// in n. This function returns the nth * +// Fibonacci number. * +//***************************************** + +int fib(int n) +{ + if (n <= 0) + return 0; // Base case + else if (n == 1) + return 1; // Base case + else + return fib(n - 1) + fib(n - 2); // Recursive case +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-7.cpp b/SourceCode/Chapter 19/Pr19-7.cpp new file mode 100755 index 0000000..1c527cb --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-7.cpp @@ -0,0 +1,21 @@ +// This program counts the nodes in a list. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + const int MAX = 10; // Maximum number of values + + // Define a NumberList object. + NumberList list; + + // Build the list with a series of numbers. + for (int x = 0; x < MAX; x++) + list.insertNode(x); + + // Display the number of nodes in the list. + cout << "The number of nodes is " + << list.numNodes() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-8.cpp b/SourceCode/Chapter 19/Pr19-8.cpp new file mode 100755 index 0000000..9500569 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-8.cpp @@ -0,0 +1,26 @@ +// This program demonstrates the recursive function +// for displaying the list’s nodes in reverse. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + const double MAX = 10.0; // Upper limit of values + + // Create a NumberList object. + NumberList list; + + // Add a series of numbers to the list. + for (double x = 1.5; x < MAX; x += 1.1) + list.appendNode(x); + + // Display the values in the list. + cout << "Here are the values in the list:\n"; + list.displayList(); + + // Display the values in reverse order. + cout << "Here are the values in reverse order:\n"; + list.displayBackwards(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-9.cpp b/SourceCode/Chapter 19/Pr19-9.cpp new file mode 100755 index 0000000..e1f1f44 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-9.cpp @@ -0,0 +1,61 @@ +// This program demonstrates the recursive binarySearch function. +#include +using namespace std; + +// Function prototype +int binarySearch(int [], int, int, int); + +const int SIZE = 20; // Array size + +int main() +{ + // Define an array of employee ID numbers + int tests[SIZE] = {101, 142, 147, 189, 199, 207, 222, + 234, 289, 296, 310, 319, 388, 394, + 417, 429, 447, 521, 536, 600}; + int empID; // To hold an ID number + int results; // To hold the search results + + // Get an employee ID number to search for. + cout << "Enter the Employee ID you wish to search for: "; + cin >> empID; + + // Search for the ID number in the array. + results = binarySearch(tests, 0, SIZE - 1, empID); + + // Display the results of the search. + if (results == -1) + cout << "That number does not exist in the array.\n"; + else + { + cout << "That ID is found at element " << results; + cout << " in the array\n"; + } + return 0; +} + +//*************************************************************** +// The binarySearch function performs a recursive binary search * +// on a range of elements of an integer array passed into the * +// parameter array. The parameter first holds the subscript of * +// the range's starting element, and last holds the subscript * +// of the ranges's last element. The paramter value holds the * +// the search value. If the search value is found, its array * +// subscript is returned. Otherwise, -1 is returned indicating * +// the value was not in the array. * +//*************************************************************** + +int binarySearch(int array[], int first, int last, int value) +{ + int middle; // Mid point of search + + if (first > last) + return -1; + middle = (first + last)/2; + if (array[middle]==value) + return middle; + if (array[middle] +using namespace std; + +// Stack template +template +class BinaryTree +{ +private: + struct TreeNode + { + T value; // The value in the node + TreeNode *left; // Pointer to left child node + TreeNode *right; // Pointer to right child node + }; + + TreeNode *root; // Pointer to the root node + + // Private member functions + void insert(TreeNode *&, TreeNode *&); + void destroySubTree(TreeNode *); + void deleteNode(T, TreeNode *&); + void makeDeletion(TreeNode *&); + void displayInOrder(TreeNode *) const; + void displayPreOrder(TreeNode *) const; + void displayPostOrder(TreeNode *) const; + +public: + // Constructor + BinaryTree() + { root = nullptr; } + + // Destructor + ~BinaryTree() + { destroySubTree(root); } + + // Binary tree operations + void insertNode(T); + bool searchNode(T); + void remove(T); + + void displayInOrder() const + { displayInOrder(root); } + + void displayPreOrder() const + { displayPreOrder(root); } + + void displayPostOrder() const + { displayPostOrder(root); } +}; + +//************************************************************* +// insert accepts a TreeNode pointer and a pointer to a node. * +// The function inserts the node into the tree pointed to by * +// the TreeNode pointer. This function is called recursively. * +//************************************************************* +template +void BinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode) +{ + if (nodePtr == nullptr) + nodePtr = newNode; // Insert the node. + else if (newNode->value < nodePtr->value) + insert(nodePtr->left, newNode); // Search the left branch + else + insert(nodePtr->right, newNode); // Search the right branch +} + +//********************************************************** +// insertNode creates a new node to hold num as its value, * +// and passes it to the insert function. * +//********************************************************** +template +void BinaryTree::insertNode(T item) +{ + TreeNode *newNode = nullptr; // Pointer to a new node. + + // Create a new node and store num in it. + newNode = new TreeNode; + newNode->value = item; + newNode->left = newNode->right = nullptr; + + // Insert the node. + insert(root, newNode); +} + +//*************************************************** +// destroySubTree is called by the destructor. It * +// deletes all nodes in the tree. * +//*************************************************** +template +void BinaryTree::destroySubTree(TreeNode *nodePtr) +{ + if (nodePtr) + { + if (nodePtr->left) + destroySubTree(nodePtr->left); + if (nodePtr->right) + destroySubTree(nodePtr->right); + delete nodePtr; + } +} + +//*************************************************** +// searchNode determines if a value is present in * +// the tree. If so, the function returns true. * +// Otherwise, it returns false. * +//*************************************************** +template +bool BinaryTree::searchNode(T item) +{ + TreeNode *nodePtr = root; + + while (nodePtr) + { + if (nodePtr->value == item) + return true; + else if (item < nodePtr->value) + nodePtr = nodePtr->left; + else + nodePtr = nodePtr->right; + } + return false; +} + +//********************************************** +// remove calls deleteNode to delete the * +// node whose value member is the same as num. * +//********************************************** +template +void BinaryTree::remove(T item) +{ + deleteNode(item, root); +} + +//******************************************** +// deleteNode deletes the node whose value * +// member is the same as num. * +//******************************************** +template +void BinaryTree::deleteNode(T item, TreeNode *&nodePtr) +{ + if (item < nodePtr->value) + deleteNode(item, nodePtr->left); + else if (item > nodePtr->value) + deleteNode(item, nodePtr->right); + else + makeDeletion(nodePtr); +} + +//*********************************************************** +// makeDeletion takes a reference to a pointer to the node * +// that is to be deleted. The node is removed and the * +// branches of the tree below the node are reattached. * +//*********************************************************** +template +void BinaryTree::makeDeletion(TreeNode *&nodePtr) +{ + // Define a temporary pointer to use in reattaching + // the left subtree. + TreeNode *tempNodePtr = nullptr; + + if (nodePtr == nullptr) + cout << "Cannot delete empty node.\n"; + else if (nodePtr->right == nullptr) + { + tempNodePtr = nodePtr; + nodePtr = nodePtr->left; // Reattach the left child + delete tempNodePtr; + } + else if (nodePtr->left == nullptr) + { + tempNodePtr = nodePtr; + nodePtr = nodePtr->right; // Reattach the right child + delete tempNodePtr; + } + // If the node has two children. + else + { + // Move one node the right. + tempNodePtr = nodePtr->right; + // Go to the end left node. + while (tempNodePtr->left) + tempNodePtr = tempNodePtr->left; + // Reattach the left subtree. + tempNodePtr->left = nodePtr->left; + tempNodePtr = nodePtr; + // Reattach the right subtree. + nodePtr = nodePtr->right; + delete tempNodePtr; + } +} + +//**************************************************************** +// The displayInOrder member function displays the values * +// in the subtree pointed to by nodePtr, via inorder traversal. * +//**************************************************************** +template +void BinaryTree::displayInOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + displayInOrder(nodePtr->left); + cout << nodePtr->value << endl; + displayInOrder(nodePtr->right); + } +} + +//**************************************************************** +// The displayPreOrder member function displays the values * +// in the subtree pointed to by nodePtr, via preorder traversal. * +//**************************************************************** +template +void BinaryTree::displayPreOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + cout << nodePtr->value << endl; + displayPreOrder(nodePtr->left); + displayPreOrder(nodePtr->right); + } +} + +//**************************************************************** +// The displayPostOrder member function displays the values * +// in the subtree pointed to by nodePtr, via postorder traversal.* +//**************************************************************** +template +void BinaryTree::displayPostOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + displayPostOrder(nodePtr->left); + displayPostOrder(nodePtr->right); + cout << nodePtr->value << endl; + } +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 20/IntBinaryTree.cpp b/SourceCode/Chapter 20/IntBinaryTree.cpp new file mode 100755 index 0000000..58fa9e4 --- /dev/null +++ b/SourceCode/Chapter 20/IntBinaryTree.cpp @@ -0,0 +1,192 @@ +// Implementation file for the IntBinaryTree class +#include +#include "IntBinaryTree.h" +using namespace std; + +//************************************************************* +// insert accepts a TreeNode pointer and a pointer to a node. * +// The function inserts the node into the tree pointed to by * +// the TreeNode pointer. This function is called recursively. * +//************************************************************* + +void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode) +{ + if (nodePtr == nullptr) + nodePtr = newNode; // Insert the node. + else if (newNode->value < nodePtr->value) + insert(nodePtr->left, newNode); // Search the left branch + else + insert(nodePtr->right, newNode); // Search the right branch +} + +//********************************************************** +// insertNode creates a new node to hold num as its value, * +// and passes it to the insert function. * +//********************************************************** + +void IntBinaryTree::insertNode(int num) +{ + TreeNode *newNode = nullptr; // Pointer to a new node. + + // Create a new node and store num in it. + newNode = new TreeNode; + newNode->value = num; + newNode->left = newNode->right = nullptr; + + // Insert the node. + insert(root, newNode); +} + +//*************************************************** +// destroySubTree is called by the destructor. It * +// deletes all nodes in the tree. * +//*************************************************** + +void IntBinaryTree::destroySubTree(TreeNode *nodePtr) +{ + if (nodePtr) + { + if (nodePtr->left) + destroySubTree(nodePtr->left); + if (nodePtr->right) + destroySubTree(nodePtr->right); + delete nodePtr; + } +} + +//*************************************************** +// searchNode determines if a value is present in * +// the tree. If so, the function returns true. * +// Otherwise, it returns false. * +//*************************************************** + +bool IntBinaryTree::searchNode(int num) +{ + TreeNode *nodePtr = root; + + while (nodePtr) + { + if (nodePtr->value == num) + return true; + else if (num < nodePtr->value) + nodePtr = nodePtr->left; + else + nodePtr = nodePtr->right; + } + return false; +} + +//********************************************** +// remove calls deleteNode to delete the * +// node whose value member is the same as num. * +//********************************************** + +void IntBinaryTree::remove(int num) +{ + deleteNode(num, root); +} + + +//******************************************** +// deleteNode deletes the node whose value * +// member is the same as num. * +//******************************************** + +void IntBinaryTree::deleteNode(int num, TreeNode *&nodePtr) +{ + if (num < nodePtr->value) + deleteNode(num, nodePtr->left); + else if (num > nodePtr->value) + deleteNode(num, nodePtr->right); + else + makeDeletion(nodePtr); +} + + +//*********************************************************** +// makeDeletion takes a reference to a pointer to the node * +// that is to be deleted. The node is removed and the * +// branches of the tree below the node are reattached. * +//*********************************************************** + +void IntBinaryTree::makeDeletion(TreeNode *&nodePtr) +{ + // Define a temporary pointer to use in reattaching + // the left subtree. + TreeNode *tempNodePtr = nullptr; + + if (nodePtr == nullptr) + cout << "Cannot delete empty node.\n"; + else if (nodePtr->right == nullptr) + { + tempNodePtr = nodePtr; + nodePtr = nodePtr->left; // Reattach the left child + delete tempNodePtr; + } + else if (nodePtr->left == nullptr) + { + tempNodePtr = nodePtr; + nodePtr = nodePtr->right; // Reattach the right child + delete tempNodePtr; + } + // If the node has two children. + else + { + // Move one node the right. + tempNodePtr = nodePtr->right; + // Go to the end left node. + while (tempNodePtr->left) + tempNodePtr = tempNodePtr->left; + // Reattach the left subtree. + tempNodePtr->left = nodePtr->left; + tempNodePtr = nodePtr; + // Reattach the right subtree. + nodePtr = nodePtr->right; + delete tempNodePtr; + } +} + +//**************************************************************** +// The displayInOrder member function displays the values * +// in the subtree pointed to by nodePtr, via inorder traversal. * +//**************************************************************** + +void IntBinaryTree::displayInOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + displayInOrder(nodePtr->left); + cout << nodePtr->value << endl; + displayInOrder(nodePtr->right); + } +} + +//**************************************************************** +// The displayPreOrder member function displays the values * +// in the subtree pointed to by nodePtr, via preorder traversal. * +//**************************************************************** + +void IntBinaryTree::displayPreOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + cout << nodePtr->value << endl; + displayPreOrder(nodePtr->left); + displayPreOrder(nodePtr->right); + } +} + +//**************************************************************** +// The displayPostOrder member function displays the values * +// in the subtree pointed to by nodePtr, via postorder traversal.* +//**************************************************************** + +void IntBinaryTree::displayPostOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + displayPostOrder(nodePtr->left); + displayPostOrder(nodePtr->right); + cout << nodePtr->value << endl; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/IntBinaryTree.h b/SourceCode/Chapter 20/IntBinaryTree.h new file mode 100755 index 0000000..aaf5245 --- /dev/null +++ b/SourceCode/Chapter 20/IntBinaryTree.h @@ -0,0 +1,49 @@ +// Specification file for the IntBinaryTree class +#ifndef INTBINARYTREE_H +#define INTBINARYTREE_H + +class IntBinaryTree +{ +private: + struct TreeNode + { + int value; // The value in the node + TreeNode *left; // Pointer to left child node + TreeNode *right; // Pointer to right child node + }; + + TreeNode *root; // Pointer to the root node + + // Private member functions + void insert(TreeNode *&, TreeNode *&); + void destroySubTree(TreeNode *); + void deleteNode(int, TreeNode *&); + void makeDeletion(TreeNode *&); + void displayInOrder(TreeNode *) const; + void displayPreOrder(TreeNode *) const; + void displayPostOrder(TreeNode *) const; + +public: + // Constructor + IntBinaryTree() + { root = nullptr; } + + // Destructor + ~IntBinaryTree() + { destroySubTree(root); } + + // Binary tree operations + void insertNode(int); + bool searchNode(int); + void remove(int); + + void displayInOrder() const + { displayInOrder(root); } + + void displayPreOrder() const + { displayPreOrder(root); } + + void displayPostOrder() const + { displayPostOrder(root); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-1.cpp b/SourceCode/Chapter 20/Pr20-1.cpp new file mode 100755 index 0000000..8f7ae5c --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-1.cpp @@ -0,0 +1,19 @@ +// This program builds a binary tree with 5 nodes. +#include +#include "IntBinaryTree.h" +using namespace std; + +int main() +{ + IntBinaryTree tree; + + cout << "Inserting nodes. "; + tree.insertNode(5); + tree.insertNode(8); + tree.insertNode(3); + tree.insertNode(12); + tree.insertNode(9); + cout << "Done.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-2.cpp b/SourceCode/Chapter 20/Pr20-2.cpp new file mode 100755 index 0000000..d1f48ce --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-2.cpp @@ -0,0 +1,32 @@ +// This program builds a binary tree with 5 nodes. +// The nodes are displayed with inorder, preorder, +// and postorder algorithms. +#include +#include "IntBinaryTree.h" +using namespace std; + +int main() +{ + IntBinaryTree tree; + + // Insert some nodes. + cout << "Inserting nodes.\n"; + tree.insertNode(5); + tree.insertNode(8); + tree.insertNode(3); + tree.insertNode(12); + tree.insertNode(9); + + // Display inorder. + cout << "Inorder traversal:\n"; + tree.displayInOrder(); + + // Display preorder. + cout << "\nPreorder traversal:\n"; + tree.displayPreOrder(); + + // Display postorder. + cout << "\nPostorder traversal:\n"; + tree.displayPostOrder(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-3.cpp b/SourceCode/Chapter 20/Pr20-3.cpp new file mode 100755 index 0000000..6641af9 --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-3.cpp @@ -0,0 +1,31 @@ +// This program builds a binary tree with 5 nodes. +// The SearchNode function is demonstrated. +#include +#include "IntBinaryTree.h" +using namespace std; + +int main() +{ + IntBinaryTree tree; + + // Insert some nodes in the tree. + cout << "Inserting nodes.\n"; + tree.insertNode(5); + tree.insertNode(8); + tree.insertNode(3); + tree.insertNode(12); + tree.insertNode(9); + + // Search for the value 3. + if (tree.searchNode(3)) + cout << "3 is found in the tree.\n"; + else + cout << "3 was not found in the tree.\n"; + + // Search for the value 100. + if (tree.searchNode(100)) + cout << "100 is found in the tree.\n"; + else + cout << "100 was not found in the tree.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-4.cpp b/SourceCode/Chapter 20/Pr20-4.cpp new file mode 100755 index 0000000..b179e4d --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-4.cpp @@ -0,0 +1,35 @@ +// This program builds a binary tree with 5 nodes. +// The DeleteNode function is used to remove two of them. +#include +#include "IntBinaryTree.h" +using namespace std; + +int main() +{ + IntBinaryTree tree; + + // Insert some values into the tree. + cout << "Inserting nodes.\n"; + tree.insertNode(5); + tree.insertNode(8); + tree.insertNode(3); + tree.insertNode(12); + tree.insertNode(9); + + // Display the values. + cout << "Here are the values in the tree:\n"; + tree.displayInOrder(); + + // Delete the value 8. + cout << "Deleting 8...\n"; + tree.remove(8); + + // Delete the value 12. + cout << "Deleting 12...\n"; + tree.remove(12); + + // Display the values. + cout << "Now, here are the nodes:\n"; + tree.displayInOrder(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-5.cpp b/SourceCode/Chapter 20/Pr20-5.cpp new file mode 100755 index 0000000..e8cafd8 --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-5.cpp @@ -0,0 +1,28 @@ +// This program demonstrates the BinaryTree class template. +// It builds a binary tree with 5 nodes. +#include +#include "BinaryTree.h" +using namespace std; + +const int NUM_NODES = 5; + +int main() +{ + string name; + + // Create the binary tree. + BinaryTree tree; + + // Insert some names. + for (int count = 0; count < NUM_NODES; count++) + { + cout << "Enter an name: "; + getline(cin, name); + tree.insertNode(name); + } + + // Display the values. + cout << "\nHere are the values in the tree:\n"; + tree.displayInOrder(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/Creating a String Class/MyString.cpp b/SourceCode/case studies/Creating a String Class/MyString.cpp new file mode 100755 index 0000000..226dd39 --- /dev/null +++ b/SourceCode/case studies/Creating a String Class/MyString.cpp @@ -0,0 +1,280 @@ +// Implementation file for the MyString class +#include // For string library functions +#include "MyString.h" +using namespace std; + +//************************************************* +// Overloaded = operator. Called when operand * +// on the right is another MyString object. * +// Returns the calling object. * +//************************************************* + +const MyString MyString::operator=(MyString &right) +{ + if (len != 0) + delete [] str; + str = new char[right.length() + 1]; + strcpy(str, right.getValue()); + len = right.length(); + return *this; +} + +//************************************************* +// Overloaded = operator. Called when operand * +// on the right is a C-string. * +// Returns the str member of the calling object. * +//************************************************* + +const char *MyString::operator=(const char *right) +{ + if (len != 0) + delete [] str; + len = strlen(right); + str = new char[len + 1]; + strcpy(str, right); + return str; +} + +//************************************************* +// Overloaded += operator. Called when operand * +// on the right is another MyString object. * +// Concatenates the str member of right to the * +// str member of the calling object. * +// Returns the calling object. * +//************************************************* + +const MyString MyString::operator+=(MyString &right) +{ + char *temp = str; + + str = new char[strlen(str) + right.length() + 1]; + strcpy(str, temp); + strcat(str, right.getValue()); + if (len != 0) + delete [] temp; + len = strlen(str); + return *this; +} + +//************************************************* +// Overloaded += operator. Called when operand * +// on the right is a string. Concatenates the * +// str member of right to the str member of * +// the calling object. * +// Returns the str member of the calling object. * +//************************************************* + +const char *MyString::operator+=(const char *right) +{ + char *temp = str; + + str = new char[strlen(str) + strlen(right) + 1]; + strcpy(str, temp); + strcat(str, right); + if (len != 0) + delete [] temp; + return str; +} + +//***************************************************** +// Overloaded == operator. * +// Called when the operand on the right is a MyString * +// object. Returns 1 if right.str is the same as str. * +//***************************************************** + +int MyString::operator==(MyString &right) +{ + return !strcmp(str, right.getValue()); +} + +//**************************************************** +// Overloaded == operator. * +// Called when the operand on the right is a string. * +// Returns 1 if right is the same as str. * +//**************************************************** + +int MyString::operator==(const char *right) +{ + return !strcmp(str, right); +} + +//********************************************************* +// Overloaded != operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if right.str is not equal to str. * +//********************************************************* + +int MyString::operator!=(MyString &right) +{ + return strcmp(str, right.getValue()); +} + +//**************************************************** +// Overloaded != operator. * +// Called when the operand on the right is a string. * +// Returns true if right is not equal to str. * +//**************************************************** + +int MyString::operator!=(const char *right) +{ + return strcmp(str, right); +} + +//********************************************************* +// Overloaded > operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if str is greater than right.str. * +//********************************************************* + +bool MyString::operator>(MyString &right) +{ + bool status; + + if (strcmp(str, right.getValue()) > 0) + status = true; + else + status = false; + return status; +} + +//**************************************************** +// Overloaded > operator. * +// Called when the operand on the right is a string. * +// Returns true if str is greater than right. * +//**************************************************** + +bool MyString::operator>(const char *right) +{ + bool status; + + if (strcmp(str, right) > 0) + status = true; + else + status = false; + return status; +} + +//****************************************************** +// Overloaded < operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if str is less than right.str. * +//****************************************************** + +bool MyString::operator<(MyString &right) +{ + bool status; + + if (strcmp(str, right.getValue()) < 0) + status = true; + else + status = false; + return status; +} + +//**************************************************** +// Overloaded < operator. * +// Called when the operand on the right is a string. * +// Returns true if str is less than right. * +//**************************************************** + +bool MyString::operator<(const char *right) +{ + bool status; + + if (strcmp(str, right) < 0) + status = true; + else + status = false; + return status; +} + +//***************************************************** +// Overloaded >= operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if str is greater than or * +// equal to right.str * +//***************************************************** + +bool MyString::operator>=(MyString &right) +{ + bool status; + + if (strcmp(str, right.getValue()) >= 0) + status = true; + else + status = false; + return status; +} + +//********************************************************* +// Overloaded >= operator. * +// Called when the operand on the right is a string. * +// Returns true if str is greater than or equal to right. * +//********************************************************* + +bool MyString::operator>=(const char *right) +{ + bool status; + + if (strcmp(str, right) >= 0) + status = true; + else + status = false; + return status; +} + +//********************************************************** +// Overloaded <= operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if right.str is less than or equal * +// to right.str. * +//********************************************************** + +bool MyString::operator<=(MyString &right) +{ + bool status; + + if (strcmp(str, right.getValue()) <= 0) + status = true; + else + status = false; + return status; +} + +//****************************************************** +// Overloaded <= operator. * +// Called when the operand on the right is a string. * +// Returns true if str is less than or equal to right. * +//****************************************************** + +bool MyString::operator<=(const char *right) +{ + bool status; + + if (strcmp(str, right) <= 0) + status = true; + else + status = false; + return status; +} + +//************************************************* +// Overloaded stream insertion operator (<<). * +//************************************************* + +ostream &operator<<(ostream &strm, const MyString &obj) +{ + strm << obj.str; + return strm; +} + +//************************************************* +// Overloaded stream extraction operator (>>). * +//************************************************* + +istream &operator>>(istream &strm, MyString &obj) +{ + strm.getline(obj.str, obj.len); + strm.ignore(); + return strm; +} \ No newline at end of file diff --git a/SourceCode/case studies/Creating a String Class/MyString.h b/SourceCode/case studies/Creating a String Class/MyString.h new file mode 100755 index 0000000..ddf98ce --- /dev/null +++ b/SourceCode/case studies/Creating a String Class/MyString.h @@ -0,0 +1,71 @@ +// Specification file for the MyString class +#ifndef MYSTRING_H +#define MYSTRING_H +#include +using namespace std; + +class MyString; // Forward declaration. +ostream &operator<<(ostream &, const MyString &); +istream &operator>>(istream &, MyString &); + +// MyString class. An abstract data type for handling strings. + +class MyString +{ +private: + char *str; + int len; +public: + // Default constructor + MyString() + { str = '\0'; len = 0; } + + // Copy constructor + MyString(MyString &right) + { str = new char[right.length() + 1]; + strcpy(str, right.getValue()); + len = right.length(); } + + // The following constructor initializes the + // MyString object with a C-string + MyString(char *sptr) + { len = strlen(sptr); + str = new char[len + 1]; + strcpy(str, sptr); } + + // Destructor + ~MyString() + { if (len != 0) delete [] str; } + + // The length function returns the string length. + int length() const + { return len; } + + // The getValue function returns the string. + const char *getValue() const + { return str; }; + + // Overloaded operators + const MyString operator+=(MyString &); + const char *operator+=(const char *); + const MyString operator=(MyString &); + const char *operator=(const char *); + int operator==(MyString &); + int operator==(const char *); + int operator!=(MyString &); + int operator!=(const char *); + bool operator>(MyString &); + bool operator>(const char *); + bool operator<(MyString &); + bool operator<(const char *); + bool operator>=(MyString &); + bool operator>=(const char*); + bool operator<=(MyString &); + bool operator<=(const char *); + + // Friends + friend ostream &operator<<(ostream &, const MyString &); + friend istream &operator>>(istream &, MyString &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/case studies/Creating a String Class/Program 14-18.cpp b/SourceCode/case studies/Creating a String Class/Program 14-18.cpp new file mode 100755 index 0000000..f3a9116 --- /dev/null +++ b/SourceCode/case studies/Creating a String Class/Program 14-18.cpp @@ -0,0 +1,37 @@ +// This program demonstrates the MyString class. +#include +#include "MyString.h" + +int main() +{ + // Define and initialize several MyString objects. + MyString object1("This"), object2("is"); + MyString object3("a test."); + MyString object4 = object1; + MyString object5("is only a test."); + // Define a C-string. + char string1[] = "a test."; + + // Display the MyString objects. + cout << "object1: " << object1 << endl; + cout << "object2: " << object2 << endl; + cout << "object3: " << object3 << endl; + cout << "object4: " << object4 << endl; + cout << "object5: " << object5 << endl; + + // Display the C-string. + cout << "string1: " << string1 << endl; + + // Test the overloaded += operator. + object1 += " "; + object1 += object2; + object1 += " "; + object1 += object3; + object1 += " "; + object1 += object4; + object1 += " "; + object1 += object5; + cout << "object1: " << object1 << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/Creating a String Class/Program 14-19.cpp b/SourceCode/case studies/Creating a String Class/Program 14-19.cpp new file mode 100755 index 0000000..fd9f36a --- /dev/null +++ b/SourceCode/case studies/Creating a String Class/Program 14-19.cpp @@ -0,0 +1,62 @@ +// This program demonstrates the MyString class. +#include +#include "MyString.h" +using namespace std; + +int main() +{ + // Define several MyString objects. + MyString name1("Billy"), name2("Sue"); + MyString name3("joe"); + MyString string1("ABC"), string2("DEF"); + + // Display the MyString object values. + cout << "name1: " << name1.getValue() << endl; + cout << "name2: " << name2.getValue() << endl; + cout << "name3: " << name3.getValue() << endl; + cout << "string1: " << string1.getValue() << endl; + cout << "string2: " << string2.getValue() << endl; + + // Test the overloaded relational operators. + if (name1 == name2) + cout << "name1 is equal to name2.\n"; + else + cout << "name1 is not equal to name2.\n"; + + if (name3 == "joe") + cout << "name3 is equal to joe.\n"; + else + cout << "name3 is not equal to joe.\n"; + + if (string1 > string2) + cout << "string1 is greater than string2.\n"; + else + cout << "string1 is not greater than string2.\n"; + + if (string1 < string2) + cout << "string1 is less than string2.\n"; + else + cout << "string1 is not less than string2.\n"; + + if (string1 >= string2) + cout << "string1 is greater than or equal to string2.\n"; + else + cout << "string1 is not greater than or equal to string2.\n"; + + if (string1 >= "ABC") + cout << "string1 is greater than or equal to ABC.\n"; + else + cout << "string1 is not greater than or equal to ABC.\n"; + + if (string1 <= string2) + cout << "string1 is less than or equal to string2.\n"; + else + cout << "string1 is not less than or equal to string2.\n"; + + if (string2 <= "DEF") + cout << "string2 is less than or equal to DEF.\n"; + else + cout << "string2 is not less than or equal to DEF.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/High Adventure Travel Agency - Part 1/Program 6-31.cpp b/SourceCode/case studies/High Adventure Travel Agency - Part 1/Program 6-31.cpp new file mode 100755 index 0000000..113b424 --- /dev/null +++ b/SourceCode/case studies/High Adventure Travel Agency - Part 1/Program 6-31.cpp @@ -0,0 +1,266 @@ +// This program will assist the High Adventure Travel Agency +// in calculating the costs of their 4 major vacation packages. +#include +#include +using namespace std; + +// Constants for the charges. +const double CLIMB_RATE = 350.0; // Base rate - Devil's Courthouse +const double SCUBA_RATE = 1000.0; // Base rate - Bahamas +const double SKY_DIVE_RATE = 400.0; // Base rate - Sky diving +const double CAVE_RATE = 700.0; // Base rate - Spelunking +const double CLIMB_INSTRUCT = 100.0; // Climbing instruction +const double SCUBA_INSTRUCT = 100.0; // Scuba instruction +const double DAILY_CAMP_RENTAL = 40.0; // Daily camping equipment rental +const double DAY_LODGE_1 = 65.0; // Lodging option (sky diving) +const double DAY_LODGE_2 = 120.0; // Lodging option (sky diving) + +// Function prototypes +void climbing(); +void scuba(); +void skyDive(); +void spelunk(); +int menu(); + +int main() +{ + int selection; + + cout << fixed << showpoint << setprecision(2); + do + { + selection = menu(); + switch (selection) + { + case 1: climbing(); + break; + case 2: scuba(); + break; + case 3: skyDive(); + break; + case 4: spelunk(); + break; + case 5: cout << "Exiting program.\n\n"; + } + } while (selection != 5); + return 0; +} + +//****************************************************** +// Definition of function menu. * +// Displays the main menu and asks the user to select * +// an option. Returns an integer in the range 1 - 5. * +//****************************************************** + +int menu() +{ + int choice; + + cout << "High Adventure Travel Agency\n"; + cout << "----------------------------\n"; + cout << "1) Devil's Courthouse Adventure Weekend\n"; + cout << "2) Scuba Bahama\n"; + cout << "3) Sky Dive Colorado\n"; + cout << "4) Barron Cliff Spelunk\n"; + cout << "5) Exit Program\n\n"; + cout << "Enter 1, 2, 3, 4, or 5: "; + cin >> choice; + while (choice < 1 || choice > 5) // Validate input + { + cout << "Invalid Selection. Enter 1, 2, 3, 4, or 5: "; + cin >> choice; + } + return choice; +} + +//************************************************* +// Definition of climbing function. * +// This function calculates the charges for the * +// Devil's Courthouse Adventure Weekend package. * +//************************************************* + +void climbing() +{ + int beginners, // Those needing instruction + advanced, // Those not needing instruction + needEquip; // Those renting camping equipment + double baseCharges, // Base charges + charges, // Total charges + instruction, // Cost of instruction + equipment, // Cost of equipment rental + discount = 0, // Discount + deposit; // Required deposit + + cout << "\nDevil's Courthouse Adventure Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> beginners; + cout << "How many advanced climbers will be going? "; + cin >> advanced; + cout << "How many will rent camping equipment? "; + cin >> needEquip; + // Calculate the base charges. + baseCharges = (beginners + advanced) * CLIMB_RATE; + charges = baseCharges; + // Calculate 10% discount for 5 or more. + if ((beginners + advanced) > 4) + { + discount = (charges * .1); + charges -= discount; + } + // Add cost of instruction. + instruction = beginners * CLIMB_INSTRUCT; + charges += instruction; + // Add cost of camping equipment rental. + equipment = needEquip * DAILY_CAMP_RENTAL * 4; + charges += equipment; + // Calculate required deposit. + deposit = charges / 2.0; + cout << "Number in party: " << (beginners + advanced); + cout << endl; + cout << "Base charges: $" << baseCharges << endl; + cout << "Instruction cost: $" << instruction << endl; + cout << "Equipment Rental: $" << equipment << endl; + cout << "Discount: $" << discount << endl; + cout << "Total Charges: $" << charges << endl; + cout << "Required Deposit: $" << deposit << endl << endl; +} + +//************************************************ +// Definition of scuba function. * +// This function calculates the charges for the * +// Scuba Bahama package. * +//************************************************ + +void scuba() +{ + int beginners, // Those needing instruction + advanced; // Those not needing instruction + double baseCharges, // Base charges + charges, // Total charges + instruction, // Cost of instruction + discount = 0, // Discount + deposit; // Required deposit + + cout << "\nScuba Bahama\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> beginners; + cout << "How many advanced scuba divers will be going? "; + cin >> advanced; + // Calculate base charges. + baseCharges = (beginners + advanced) * SCUBA_RATE; + charges = baseCharges; + // Calculate 10% discount for 5 or more. + if ((beginners + advanced) > 4) + { + discount = (charges * .1); + charges -= discount; + } + // Add cost of instruction. + instruction = beginners * SCUBA_INSTRUCT; + charges += instruction; + + // Calcuate the required deposit. + deposit = charges / 2.0; + cout << "Number in party: " << (beginners + advanced); + cout << endl; + cout << "Base charges: $" << baseCharges << endl; + cout << "Instruction cost: $" << instruction << endl; + cout << "Discount: $" << discount << endl; + cout << "Total Charges: $" << charges << endl; + cout << "Required Deposit: $" << deposit << endl << endl; +} + +//************************************************ +// Definition of skyDive function. * +// This function calculates the charges for the * +// Sky Dive Colorado package. * +//************************************************ + +void skyDive() +{ + int party, // Number in party + lodge1, // Number at 1st lodging choice + lodge2; // Number at 2nd lodging choice + double baseCharges, // Base charges + charges, // Total charges + discount = 0, // Discount + lodging, // Cost of lodging + deposit; // Required deposit + + cout << "\nSky Dive Colorado\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> party; + // Calculate base charges. + baseCharges = party * SKY_DIVE_RATE; + charges = baseCharges; + // Calculate 10% discount for 5 or more. + if (party > 4) + { + discount = (charges * .1); + charges -= discount; + } + // Calculate lodging costs. + cout << "How many will stay at Wilderness Lodge? "; + cin >> lodge1; + cout << "How many will stay at Luxury Inn? "; + cin >> lodge2; + lodging = (lodge1 * DAY_LODGE_1) + (lodge2 * DAY_LODGE_2); + charges += lodging; + + // Calculate required deposit. + deposit = charges / 2.0; + cout << "Number in party: " << party << endl; + cout << "Base charges: $" << baseCharges << endl; + cout << "Lodging: $" << lodging << endl; + cout << "Discount: $" << discount << endl; + cout << "Total Charges: $" << charges << endl; + cout << "Required Deposit: $" << deposit << endl << endl; +} + +//************************************************ +// Definition of spelunk function. * +// This function calculates the charges for the * +// Barron Cliff Spelunk package. * +//************************************************ + +void spelunk() +{ + int party, // Number in party + needEquip; // Those renting camping equipment + double baseCharges, // Base charges + charges, // Total charges + equipment, // Cost of equipment rental + discount = 0, // Discount + deposit; // Required deposit + + cout << "\nBarron Cliff Spelunk Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> party; + cout << "How many will rent camping equipment? "; + cin >> needEquip; + // Calculate base charges. + baseCharges = party * CAVE_RATE; + charges = baseCharges; + // Calculate 10% discount for 5 or more. + if (party > 4) + { + discount = (charges * .1); + charges -= discount; + } + // Add cost of camping equipment rental + equipment = needEquip * DAILY_CAMP_RENTAL * 4; + charges += equipment; + + // Calculate required deposit. + deposit = charges / 2.0; + cout << "Number in party: " << party << endl; + cout << "Base charges: $" << baseCharges << endl; + cout << "Equipment Rental: $" << equipment << endl; + cout << "Discount: $" << discount << endl; + cout << "Total Charges: $" << charges << endl; + cout << "Required Deposit: $" << deposit << endl << endl; +} \ No newline at end of file diff --git a/SourceCode/case studies/High Adventure Travel Agency - Part 2/Program 11-15.cpp b/SourceCode/case studies/High Adventure Travel Agency - Part 2/Program 11-15.cpp new file mode 100755 index 0000000..d8ee18a --- /dev/null +++ b/SourceCode/case studies/High Adventure Travel Agency - Part 2/Program 11-15.cpp @@ -0,0 +1,430 @@ +// This program will assist the High Adventure Travel Agency +// in calculating the costs of their 4 major vacation packages. +// In this version of the program, the data structures needed +// to store the information in a database will be designed. +// The next modification will implement the file operations. +#include +#include +using namespace std; + +// The data structures + +struct Package1 // Climbing Package +{ + int num; // Number in party + int beginners; // Those needing instruction + int advanced; // Those not needing instruction + int needEquip; // Those renting camping equipment + double baseCharges; // Base charges + double charges; // Total charges + double instruction; // Cost of instruction + double equipment; // Cost of equipment rental + double discount; // Discount + double deposit; // Required deposit +}; + +struct Package2 // Scuba Package +{ + int num; // Number in party + int beginners; // Those needing instruction + int advanced; // Those not needing instruction + double baseCharges; // Base charges + double charges; // Total charges + double instruction; // Cost of instruction + double discount; // Discount + double deposit; // Required deposit +}; + +struct Package3 // Sky Diving Package +{ + int num; // Number in party + int lodge1; // number at 1st lodging choice + int lodge2; // number at 2nd lodging choice + double baseCharges; // Base charges + double charges; // Total charges + double discount; // Discount + double lodging; // Cost of lodging + double deposit; // Required deposit +}; + +struct Package4 // Spelunking Package +{ + int num; // Number in party + int needEquip; // Those renting camping equipment + double baseCharges; // Base charges + double charges; // Total charges + double equipment; // Cost of equipment rental + double discount; // Discount + double deposit; // Required deposit +}; + +union Pack // Combines the four structs +{ + struct Package1 climb; + struct Package2 scuba; + struct Package3 sky; + struct Package4 spel; +}; + +struct Reservation +{ + int packNum; // Indicates which package is stored + union Pack packs; +}; + +// Constants for the charges. +const double CLIMB_RATE = 350.0; // Base rate - Devil's Courthouse +const double SCUBA_RATE = 1000.0; // Base rate - Bahamas +const double SKY_DIVE_RATE = 400.0; // Base rate - Sky diving +const double CAVE_RATE = 700.0; // Base rate - Spelunking +const double CLIMB_INSTRUCT = 100.0; // Climbing instruction +const double SCUBA_INSTRUCT = 100.0; // Scuba instruction +const double DAILY_CAMP_RENTAL = 40.0; // Daily camping equip. rental +const double DAY_LODGE_1 = 65.0; // Lodging option (sky diving) +const double DAY_LODGE_2 = 120.0; // Lodging option (sky diving) + +// Function prototypes +void climbing(Reservation &); +void scuba(Reservation &); +void skyDive(Reservation &); +void spelunk(Reservation &); +int menu(); +void displayInfo(const Reservation &); +void displayPack1(const Reservation &); +void displayPack2(const Reservation &); +void displayPack3(const Reservation &); +void displayPack4(const Reservation &); + +int main() +{ + int selection; + Reservation group; + + cout << fixed << showpoint << setprecision(2); + do + { + selection = menu(); + switch(selection) + { + case 1 : climbing(group); + break; + case 2 : scuba(group); + break; + case 3 : skyDive(group); + break; + case 4 : spelunk(group); + break; + case 5 : cout << "Exiting program.\n\n"; + } + if (selection < 5) + displayInfo(group); + } while (selection != 5); + return 0; +} + +//***************************************************** +// Definition of function menu. * +// Displays the main menu and asks the user to select * +// an option. Returns an integer in the range 1 - 5. * +//***************************************************** + +int menu() +{ + int choice; + + cout << "High Adventure Travel Agency\n"; + cout << "----------------------------\n"; + cout << "1) Devil's Courthouse Adventure Weekend\n"; + cout << "2) Scuba Bahama\n"; + cout << "3) Sky Dive Colorado\n"; + cout << "4) Barron Cliff Spelunk\n"; + cout << "5) Exit Program\n\n"; + cout << "Enter 1, 2, 3, 4, or 5: "; + cin >> choice; + while (choice < 1 || choice > 5) // Validate input + { + cout << "Invalid Selection. Enter 1, 2, 3, 4, or 5: "; + cin >> choice; + } + return choice; +} + +//****************************************************** +// Definition of climbing function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Devil's Courthouse Adventure Weekend package. * +//****************************************************** + +void climbing(Reservation &group) +{ + group.packNum = 1; + cout << "\nDevil's Courthouse Adventure Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> group.packs.climb.beginners; + cout << "How many advanced climbers will be going? "; + cin >> group.packs.climb.advanced; + group.packs.climb.num = group.packs.climb.beginners + + group.packs.climb.advanced; + cout << "How many will rent camping equipment? "; + cin >> group.packs.climb.needEquip; + // Calculate base charges. + group.packs.climb.baseCharges = group.packs.climb.num * + CLIMB_RATE; + group.packs.climb.charges = group.packs.climb.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.climb.num > 4) + { + group.packs.climb.discount = group.packs.climb.charges + * .1; + group.packs.climb.charges -= group.packs.climb.discount; + } + else + group.packs.climb.discount = 0; + // Add cost of instruction. + group.packs.climb.instruction = group.packs.climb.beginners + * CLIMB_INSTRUCT; + group.packs.climb.charges += group.packs.climb.instruction; + // Add cost of camping equipment rental + group.packs.climb.equipment = group.packs.climb.needEquip * + DAILY_CAMP_RENTAL * 4; + group.packs.climb.charges += group.packs.climb.equipment; + // Calculate required deposit. + group.packs.climb.deposit = group.packs.climb.charges / 2.0; +} + +//****************************************************** +// Definition of scuba function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Scuba Bahama package. * +//****************************************************** + +void scuba(Reservation &group) +{ + group.packNum = 2; + cout << "\nScuba Bahama\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> group.packs.scuba.beginners; + cout << "How many advanced scuba divers will be going? "; + cin >> group.packs.scuba.advanced; + group.packs.scuba.num = group.packs.scuba.beginners + + group.packs.scuba.advanced; + // Calculate base charges. + group.packs.scuba.baseCharges = group.packs.scuba.num * + SCUBA_RATE; + group.packs.scuba.charges = group.packs.scuba.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.scuba.num > 4) + { + group.packs.scuba.discount = group.packs.scuba.charges + * .1; + group.packs.scuba.charges -= group.packs.scuba.discount; + } + else + group.packs.scuba.discount = 0; + // Add cost of instruction. + group.packs.scuba.instruction = group.packs.scuba.beginners + * SCUBA_INSTRUCT; + group.packs.scuba.charges += group.packs.scuba.instruction; + // Calculate required deposit. + group.packs.scuba.deposit = group.packs.scuba.charges / 2.0; +} + +//****************************************************** +// Definition of skyDive function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Sky Dive Colorado package. * +//****************************************************** + +void skyDive(Reservation &group) +{ + group.packNum = 3; + cout << "\nSky Dive Colorado\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> group.packs.sky.num; + // Calculate base charges. + group.packs.sky.baseCharges = group.packs.sky.num + * SKY_DIVE_RATE; + group.packs.sky.charges = group.packs.sky.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.sky.num > 4) + { + group.packs.sky.discount = group.packs.sky.charges * .1; + group.packs.sky.charges -= group.packs.sky.discount; + } + else + group.packs.sky.discount = 0; + // Calculate lodging costs. + cout << "How may will stay at Wilderness Lodge? "; + cin >> group.packs.sky.lodge1; + cout << "How many will stay at Luxury Inn? "; + cin >> group.packs.sky.lodge2; + group.packs.sky.lodging = (group.packs.sky.lodge1 * + DAY_LODGE_1) + (group.packs.sky.lodge2 * + DAY_LODGE_2); + // Calculate required deposit. + group.packs.sky.deposit = group.packs.sky.charges / 2.0; +} + +//****************************************************** +// Definition of spelunk function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Barron Cliff Spelunk package. * +//****************************************************** + +void spelunk(Reservation &group) +{ + group.packNum = 4; + cout << "\nBarron Cliff Spelunk Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> group.packs.spel.num; + cout << "How many will rent camping equipment? "; + cin >> group.packs.spel.needEquip; + // Calculate base charges. + group.packs.spel.baseCharges = group.packs.spel.num * + CAVE_RATE; + group.packs.spel.charges = group.packs.spel.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.spel.num > 4) + { + group.packs.spel.discount = group.packs.spel.charges * .1; + group.packs.spel.charges -= group.packs.spel.discount; + } + else + group.packs.spel.discount = 0; + // Add cost of camping equipment rental + group.packs.spel.equipment = group.packs.spel.needEquip * + DAILY_CAMP_RENTAL * 4; + group.packs.spel.charges += group.packs.spel.equipment; + // Calculate required deposit. + group.packs.spel.deposit = group.packs.spel.charges / 2.0; +} + +//************************************************************** +// Definition of function displayInfo. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function looks in the * +// group.packNum member to determine which function to call * +// to display the vacation package information. * +//************************************************************** + +void displayInfo(const Reservation &group) +{ + switch (group.packNum) + { + case 1: displayPack1(group); + break; + case 2: displayPack2(group); + break; + case 3: displayPack3(group); + break; + case 4: displayPack4(group); + break; + default: cout << "ERROR: Invalid package number.\n"; + } +} + +//************************************************************** +// Definition of function displayPack1. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 1. * +//************************************************************** + +void displayPack1(const Reservation &group) +{ + cout << "Number in party: " + << group.packs.climb.num << endl; + cout << "Base charges: $" + << group.packs.climb.baseCharges << endl; + cout << "Instruction cost: $" + << group.packs.climb.instruction << endl; + cout << "Equipment Rental: $" + << group.packs.climb.equipment << endl; + cout << "Discount: $" + << group.packs.climb.discount << endl; + cout << "Total charges: $" + << group.packs.climb.charges << endl; + cout << "Required deposit: $" + << group.packs.climb.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack2. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 2. * +//************************************************************** + +void displayPack2(const Reservation &group) +{ + cout << "Number in party: " + << group.packs.scuba.num << endl; + cout << "Base charges: $" + << group.packs.scuba.baseCharges << endl; + cout << "Instruction cost: $" + << group.packs.scuba.instruction << endl; + cout << "Discount: $" + << group.packs.scuba.discount << endl; + cout << "Total Charges: $" + << group.packs.scuba.charges << endl; + cout << "Required deposit: $" + << group.packs.scuba.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack3. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 3. * +//************************************************************** + +void displayPack3(const Reservation &group) +{ + cout << "Number in party: " + << group.packs.sky.num << endl; + cout << "Base charges: $" + << group.packs.sky.baseCharges << endl; + cout << "Lodging: $" + << group.packs.sky.lodging << endl; + cout << "Discount: $" + << group.packs.sky.discount << endl; + cout << "Total Charges: $" + << group.packs.sky.charges << endl; + cout << "Required deposit: $" + << group.packs.sky.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack4. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 4. * +//************************************************************** + +void displayPack4(const Reservation &group) +{ + cout << "Number in party: " + << group.packs.spel.num << endl; + cout << "Base charges: $" + << group.packs.spel.baseCharges << endl; + cout << "Equipment Rental: $" + << group.packs.spel.equipment << endl; + cout << "Discount: $" + << group.packs.spel.discount << endl; + cout << "Total Charges: $" + << group.packs.spel.charges << endl; + cout << "Required deposit: $" + << group.packs.spel.deposit << endl << endl; +} \ No newline at end of file diff --git a/SourceCode/case studies/High Adventure Travel Agency - Part 3/Program 12-23.cpp b/SourceCode/case studies/High Adventure Travel Agency - Part 3/Program 12-23.cpp new file mode 100755 index 0000000..59465a7 --- /dev/null +++ b/SourceCode/case studies/High Adventure Travel Agency - Part 3/Program 12-23.cpp @@ -0,0 +1,533 @@ +// This program will assist the High Adventure Travel Agency +// in booking reservations for any of their 4 major +// vacation packages. +#include +#include +#include +#include +using namespace std; + +// Data Structures +struct Package1 // Climbing Package +{ + int num; // Number in party + int beginners; // Those needing instruction + int advanced; // Those not needing instruction + int needEquip; // Those renting camping equipment + double baseCharges; // Base charges + double charges; // Total charges + double instruction; // Cost of instruction + double equipment; // Cost of equipment rental + double discount; // Discount + double deposit; // Required deposit +}; + +struct Package2 // Scuba Package +{ + int num; // Number in party + int beginners; // Those needing instruction + int advanced; // Those not needing instruction + double baseCharges; // Base charges + double charges; // Total charges + double instruction; // Cost of instruction + double discount; // Discount + double deposit; // Required deposit +}; + +struct Package3 // Sky Diving Package +{ + int num; // Number in party + int lodge1; // Number at 1st lodging choice + int lodge2; // Number at 2nd lodging choice + double baseCharges; // Base charges + double charges; // Total charges + double discount; // Discount + double lodging; // Cost of lodging + double deposit; // Required deposit +}; + +struct Package4 // Spelunking Package +{ + int num; // Number in party + int needEquip; // Those renting camping equipment + double baseCharges; // Base charges + double charges; // Total charges + double equipment; // Cost of equipment rental + double discount; // Discount + double deposit; // Required deposit +}; + +union Pack +{ + struct Package1 climb; + struct Package2 scuba; + struct Package3 sky; + struct Package4 spel; +}; + +struct Reservation +{ + int packNum; + union Pack packs; +}; + +// Constants for the charges. +const double CLIMB_RATE = 350.0; // Base rate - Devil's Courthouse +const double SCUBA_RATE = 1000.0; // Base rate - Bahamas +const double SKY_DIVE_RATE = 400.0; // Base rate - Sky diving +const double CAVE_RATE = 700.0; // Base rate - Spelunking +const double CLIMB_INSTRUCT = 100.0; // Climbing instruction +const double SCUBA_INSTRUCT = 100.0; // Scuba instruction +const double DAILY_CAMP_RENTAL = 40.0; // Daily camping equip. rental +const double DAY_LODGE_1 = 65.0; // Lodging option (sky diving) +const double DAY_LODGE_2 = 120.0; // Lodging option (sky diving) + +// Function prototypes +void openFile(fstream &); +void saveInfo(Reservation &, fstream &); +void climbing(Reservation &); +void scuba(Reservation &); +void skyDive(Reservation &); +void spelunk(Reservation &); +int menu(); +void displayInfo(Reservation &); +void displayPack1(Reservation &); +void displayPack2(Reservation &); +void displayPack3(Reservation &); +void displayPack4(Reservation &); +void showRes(fstream &); + +int main() +{ + int selection; + Reservation group; + fstream file; + + cout << fixed << showpoint << setprecision(2); + openFile(file); + do + { + selection = menu(); + switch(selection) + { + case 1 : climbing(group); + break; + case 2 : scuba(group); + break; + case 3 : skyDive(group); + break; + case 4 : spelunk(group); + break; + case 5 : showRes(file); + break; + case 6 : cout << "Exiting program.\n\n"; + } + if (selection < 5) + { + displayInfo(group); + saveInfo(group, file); + } + } while (selection != 6); + file.close(); + return 0; +} + +//************************************************** +// Definition of function openFile. * +// Accepts an fstream object as an argument. The * +// file is opened for both input and output, in * +// binary mode. * +//************************************************** + +void openFile(fstream &file) +{ + const int SIZE = 256; + char fileName[SIZE]; + + cout << "File name: "; + cin.getline(fileName, SIZE); + + file.open(fileName, ios::in | ios::out | ios::binary); + if (!file) + { + cout << "Creating " << fileName << "...\n"; + // Create the file. + file.open(fileName, ios::out); + // Close the file. + file.close(); + // Reopen the file for input and output. + file.open(fileName, ios::in | ios::out | ios::binary); + } +} + +//************************************************************ +// Definition of function saveInfo. * +// Accepts a Reservation structure and an fstream object. * +// The user is asked if the data in the structure * +// is to be saved. If so, it is saved at the end of the file.* +//************************************************************ + +void saveInfo(Reservation &group, fstream &file) +{ + char yorN; + + cout << "Do you want to save this data? (Y/N) "; + cin >> yorN; + yorN = toupper(yorN); + + // Validate input + while (yorN != 'Y' && yorN != 'N') + { + cout << "Please enter Y or N\n"; + cin >> yorN; + yorN = toupper(yorN); + } + + // Save the data. + if (yorN == 'Y') + { + cout << "Saving reservation data.\n"; + file.write(reinterpret_cast(&group), sizeof(group)); + if (!file) + cout << "Could not write to file!\n"; + } +} + +//***************************************************** +// Definition of function menu. * +// Displays the main menu and asks the user to select * +// an option. Returns an integer in the range 1 - 6. * +//***************************************************** + +int menu( ) +{ + int choice; + + cout << "High Adventure Travel Agency\n"; + cout << "----------------------------\n"; + cout << "1) Devil's Courthouse Adventure Weekend\n"; + cout << "2) Scuba Bahama\n"; + cout << "3) Sky Dive Colorado\n"; + cout << "4) Barron Cliff Spelunk\n"; + cout << "5) Show Booked Reservations\n"; + cout << "6) Exit Program\n\n"; + cout << "Enter 1, 2, 3, 4, 5, or 6: "; + cin >> choice; + + while (choice < 1 || choice > 6) + { + cout << "Invalid Selection\n"; + cin >> choice; + } + return choice; +} + +//****************************************************** +// Definition of climbing function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Devil's Courthouse Adventure Weekend package. * +//****************************************************** + +void climbing(Reservation &group) +{ + group.packNum = 1; + cout << "\nDevil's Courthouse Adventure Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> group.packs.climb.beginners; + cout << "How many advanced climbers will be going? "; + cin >> group.packs.climb.advanced; + group.packs.climb.num = group.packs.climb.beginners + + group.packs.climb.advanced; + cout << "How many will rent camping equipment? "; + cin >> group.packs.climb.needEquip; + // Calculate base charges. + group.packs.climb.baseCharges = group.packs.climb.num * + CLIMB_RATE; + group.packs.climb.charges = group.packs.climb.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.climb.num > 4) + { + group.packs.climb.discount = group.packs.climb.charges + * .1; + group.packs.climb.charges -= group.packs.climb.discount; + } + else + group.packs.climb.discount = 0; + // Add cost of instruction. + group.packs.climb.instruction = group.packs.climb.beginners + * CLIMB_INSTRUCT; + group.packs.climb.charges += group.packs.climb.instruction; + // Add cost of camping equipment rental + group.packs.climb.equipment = group.packs.climb.needEquip * + DAILY_CAMP_RENTAL * 4; + group.packs.climb.charges += group.packs.climb.equipment; + // Calculate required deposit. + group.packs.climb.deposit = group.packs.climb.charges / 2.0; +} + +//****************************************************** +// Definition of scuba function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Scuba Bahama package. * +//****************************************************** + +void scuba(Reservation &group) +{ + group.packNum = 2; + cout << "\nScuba Bahama\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> group.packs.scuba.beginners; + cout << "How many advanced scuba divers will be going? "; + cin >> group.packs.scuba.advanced; + group.packs.scuba.num = group.packs.scuba.beginners + + group.packs.scuba.advanced; + // Calculate base charges. + group.packs.scuba.baseCharges = group.packs.scuba.num * + SCUBA_RATE; + group.packs.scuba.charges = group.packs.scuba.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.scuba.num > 4) + { + group.packs.scuba.discount = group.packs.scuba.charges + * .1; + group.packs.scuba.charges -= group.packs.scuba.discount; + } + else + group.packs.scuba.discount = 0; + // Add cost of instruction. + group.packs.scuba.instruction = group.packs.scuba.beginners + * SCUBA_INSTRUCT; + group.packs.scuba.charges += group.packs.scuba.instruction; + // Calculate required deposit. + group.packs.scuba.deposit = group.packs.scuba.charges / 2.0; +} + +//****************************************************** +// Definition of skyDive function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Sky Dive Colorado package. * +//****************************************************** + +void skyDive(Reservation &group) +{ + group.packNum = 3; + cout << "\nSky Dive Colorado\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> group.packs.sky.num; + // Calculate base charges. + group.packs.sky.baseCharges = group.packs.sky.num * + SKY_DIVE_RATE; + group.packs.sky.charges = group.packs.sky.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.sky.num > 4) + { + group.packs.sky.discount = group.packs.sky.charges * .1; + group.packs.sky.charges -= group.packs.sky.discount; + } + else + group.packs.sky.discount = 0; + // Calculate lodging costs. + cout << "How may will stay at Wilderness Lodge? "; + cin >> group.packs.sky.lodge1; + cout << "How many will stay at Luxury Inn? "; + cin >> group.packs.sky.lodge2; + group.packs.sky.lodging = (group.packs.sky.lodge1 * + DAY_LODGE_1) + (group.packs.sky.lodge2 * DAY_LODGE_2); + group.packs.sky.charges += group.packs.sky.lodging; + // Calculate required deposit. + group.packs.sky.deposit = group.packs.sky.charges / 2.0; +} + +//****************************************************** +// Definition of spelunk function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Barron Cliff Spelunk package. * +//****************************************************** + +void spelunk(Reservation &group) +{ + group.packNum = 4; + cout << "\nBarron Cliff spelunk Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> group.packs.spel.num; + cout << "How many will rent camping equipment? "; + cin >> group.packs.spel.needEquip; + // Calculate base charges. + group.packs.spel.baseCharges = group.packs.spel.num * + CAVE_RATE; + group.packs.spel.charges = group.packs.spel.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.spel.num > 4) + { + group.packs.spel.discount = group.packs.spel.charges * .1; + group.packs.spel.charges -= group.packs.spel.discount; + } + else + group.packs.spel.discount = 0; + // Add cost of camping equipment rental + group.packs.spel.equipment = group.packs.spel.needEquip * + DAILY_CAMP_RENTAL * 4; + group.packs.spel.charges += group.packs.spel.equipment; + // Calculate required deposit. + group.packs.spel.deposit = group.packs.spel.charges / 2.0; +} + +//************************************************************** +// Definition of function displayInfo. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function looks in the * +// group.packNum member to determine which function to call * +// to display the vacation package information. * +//************************************************************** + +void displayInfo(Reservation &group) +{ + switch (group.packNum) + { + case 1: displayPack1(group); + break; + case 2: displayPack2(group); + break; + case 3: displayPack3(group); + break; + case 4: displayPack4(group); + break; + default: cout << "ERROR: Invalid package number.\n"; + } +} + +//************************************************************** +// Definition of function displayPack1. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 1. * +//************************************************************** + +void displayPack1(Reservation &group) +{ + cout << "Package: Devil's Courthouse Adventure Weekend\n"; + cout << "Number in party: " + << group.packs.climb.num << endl; + cout << "Base charges: $" + << group.packs.climb.baseCharges << endl; + cout << "Instruction cost: $" + << group.packs.climb.instruction << endl; + cout << "Equipment rental: $" + << group.packs.climb.equipment << endl; + cout << "Discount: $" + << group.packs.climb.discount << endl; + cout << "Total charges: $" + << group.packs.climb.charges << endl; + cout << "Required deposit: $" + << group.packs.climb.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack2. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 2. * +//************************************************************** + +void displayPack2(Reservation &group) +{ + cout << "Package: Scuba Bahama\n"; + cout << "Number in party: " + << group.packs.scuba.num << endl; + cout << "Base charges: $" + << group.packs.scuba.baseCharges << endl; + cout << "Instruction cost: $" + << group.packs.scuba.instruction << endl; + cout << "Discount: $" + << group.packs.scuba.discount << endl; + cout << "Total charges: $" + << group.packs.scuba.charges << endl; + cout << "Required deposit: $" + << group.packs.scuba.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack3. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 3. * +//************************************************************** + +void displayPack3(Reservation &group) +{ + cout << "Package: Sky Dive Colorado\n"; + cout << "Number in party: " + << group.packs.sky.num << endl; + cout << "Base charges: $" + << group.packs.sky.baseCharges << endl; + cout << "Lodging: $" + << group.packs.sky.lodging << endl; + cout << "Discount: $" + << group.packs.sky.discount << endl; + cout << "Total charges: $" + << group.packs.sky.charges << endl; + cout << "Required deposit: $" + << group.packs.sky.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack4. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 4. * +//************************************************************** + +void displayPack4(Reservation &group) +{ + cout << "Package: Barron Cliff Spelunk\n"; + cout << "Number in party: " + << group.packs.spel.num << endl; + cout << "Base charges: $" + << group.packs.spel.baseCharges << endl; + cout << "Equipment rental: $" + << group.packs.spel.equipment << endl; + cout << "Discount: $" + << group.packs.spel.discount << endl; + cout << "Total charges: $" + << group.packs.spel.charges << endl; + cout << "Required deposit: $" + << group.packs.spel.deposit << endl << endl; +} + +//************************************************************** +// Definition of function showRes. * +// Accepts an fstream object as an argument. Seeks the * +// beginning of the file and then reads and displays * +// each record. * +//************************************************************** + +void showRes(fstream &file) +{ + Reservation temp; + char skip[2]; + + file.seekg(0L, ios::beg); // Go to beginning of file. + file.read(reinterpret_cast(&temp), sizeof(temp)); + while (!file.eof()) + { + displayInfo(temp); + cout << "Type a character and press Enter " + << "to continue:"; + cin >> skip; + file.read(reinterpret_cast(&temp), sizeof(temp)); + } + if (file.fail()) + file.clear(); // Clear any error state +} \ No newline at end of file diff --git a/SourceCode/case studies/High Adventure Travel Agency - Part 3/resfile b/SourceCode/case studies/High Adventure Travel Agency - Part 3/resfile new file mode 100755 index 0000000..26283b5 Binary files /dev/null and b/SourceCode/case studies/High Adventure Travel Agency - Part 3/resfile differ diff --git a/SourceCode/case studies/Intersection of Sets/Program 7-32.cpp b/SourceCode/case studies/Intersection of Sets/Program 7-32.cpp new file mode 100755 index 0000000..ddd6c58 --- /dev/null +++ b/SourceCode/case studies/Intersection of Sets/Program 7-32.cpp @@ -0,0 +1,101 @@ +// This program allows the user to enter two sets of numbers. +// It finds the intersection of the two sets (which is the +// set of numbers contained in both sets). The intersecting +// values are displayed. +#include +using namespace std; + +// Function Prototypes +void getArrays(int [], int [], int); +int findIntersection(int [], int [], int [], int); +void displayIntValues(int [], int); + +int main() +{ + const int NUM_VALUES = 10; // Number of values in each array + int set1[NUM_VALUES], // First set + set2[NUM_VALUES], // Second set + intersection[NUM_VALUES], // Set containing intersection values + numIntValues; // number of values in intersection + + // Get values for the sets. + getArrays(set1, set2, NUM_VALUES); + + // Find the intersection of the two sets + numIntValues = findIntersection(set1, set2, + intersection, NUM_VALUES); + + // Display the intersecting values + displayIntValues(intersection, numIntValues); + return 0; +} + +//******************************************************** +// Definition of function getArrays * +// This function accepts two int arrays as arguments. * +// It prompts the user to enter 10 values for each array * +//******************************************************** + +void getArrays(int first[], int second[], int size) +{ + // Get values for first array. + cout << "Enter 10 values for the first set:\n"; + for (int index = 0; index < size; index++) + cin >> first[index]; + + // Get values for second array. + cout << "Enter 10 values for the second set:\n"; + for (int index = 0; index < size; index++) + cin >> second[index]; +} + + +//************************************************************ +// Definition of function findIntersection * +// This functon accepts three arrays as arguments. * +// The first two arrays (first and second) are scanned, * +// and all values appearing in both are stored in the * +// third array (intersect). The number of values that appear * +// in both arrays is returned. * +//************************************************************ + +int findIntersection(int first[], int second[], int intersect[], int size) +{ + int intCount = 0, // Number of intersecting values + index3 = 0; // Subscript variable for intersect array + + for (int index1 = 0; index1 < size; index1++) + { + for(int index2 = 0; index2 < size; index2++) + { + if (first[index1] == second[index2]) + { + intersect[index3] = first[index1]; + index3++; + intCount++; + } + } + } + return intCount; // Return the number of intersecting values. +} + +//******************************************************* +// Definition of function displayIntValues * +// This function acepts two arguments: an array of ints * +// and an int. The second argument is the number of * +// valid elements contained in the array. * +// These values are displayed, if there are any. * +//******************************************************* + +void displayIntValues(int intersect[], int num) +{ + if (!num) + cout << "There are no intersecting values.\n"; + else + { + cout << "Here is a list of the intersecting values:\n"; + for (int index = 0; index < num; index++) + cout << intersect[index] << " "; + cout << endl; + } +} \ No newline at end of file diff --git a/SourceCode/case studies/Loan Amortization/Program 5-27.cpp b/SourceCode/case studies/Loan Amortization/Program 5-27.cpp new file mode 100755 index 0000000..0dce3ac --- /dev/null +++ b/SourceCode/case studies/Loan Amortization/Program 5-27.cpp @@ -0,0 +1,69 @@ +// This program produces a loan amortization chart for the +// Central Mountain Credit Union. +#include +#include +#include // For pow function +using namespace std; + +int main() +{ + const int MONTHS = 12; // Months per year + double loan, // Loan amount + rate, // Annual interest rate + years, // Years of loan + balance, // Monthly balance + term, // Used to calculate payment + payment; // Monthly payment + + // Ask user for input. + cout << "Loan amount: $"; + cin >> loan; + cout << "Annual interest rate: "; + cin >> rate; + cout << "Years of loan: "; + cin >> years; + + // Calculate monthly payment. + term = pow((1 + rate / MONTHS), MONTHS * years); + payment = (loan * rate / MONTHS * term) / (term - 1.0); + + // Display monthly payment. + cout << fixed << showpoint << setprecision(2); + cout << "Monthly payment: $" << payment << endl; + + // Display report header. + cout << endl; + cout << setw(5) << "Month"; + cout << setw(10) << "Interest"; + cout << setw(10) << "Principal"; + cout << setw(10) << "Balance" << endl; + cout << "----------------------------------------\n"; + + // Produce a listing for each month. + balance = loan; + int numPayments = MONTHS * years; + for (int month = 1; month <= numPayments; month++) + { + double minterest, principal; + // Calculate monthly interest + minterest = rate / MONTHS * balance; + if (month != numPayments) + principal = payment - minterest; + + else // If this is the last month + { + principal = balance; + payment = balance + minterest; + } + + // Calculate the new loan balance. + balance -= principal; + + // Display payment figures + cout << setw(4) << month; + cout << setw(10) << minterest; + cout << setw(10) << principal; + cout << setw(10) << balance << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/Sales Commission/Program 4-31.cpp b/SourceCode/case studies/Sales Commission/Program 4-31.cpp new file mode 100755 index 0000000..89229d6 --- /dev/null +++ b/SourceCode/case studies/Sales Commission/Program 4-31.cpp @@ -0,0 +1,50 @@ +// This program is used by Crazy Al's Computer Emporium +// to calculate the monthly pay of commissioned sales people. +#include +#include +using namespace std; +int main() +{ + double sales, // Monthly Sales + rate, // Rate of Commission + commission, // Amount of Commission + advance, // Advanced Pay Drawn + pay; // Pay remaining to be paid + + // Ask user for the salesperson's sales and the + // amount of advanced pay. + cout << "Enter the salesperson's monthly sales: "; + cin >> sales; + cout << "Enter the amount of advanced pay for this "; + cout << "salesperson: "; + cin >> advance; + + // Determine the commission rate. + if (sales < 10000) + rate = 0.05; + else if (sales < 14999) + rate = 0.1; + else if (sales < 17999) + rate = 0.12; + else if (sales < 21999) + rate = 0.14; + else + rate = 0.16; + + // Calculate the sales commission. + commission = sales * rate; + + // Calculate the salesperson's pay. + pay = commission - advance; + + // Display the results. + cout << fixed << showpoint << setprecision(2); + cout << "\nPay Results\n"; + cout << "-----------\n"; + cout << "Sales: $" << sales << endl; + cout << "Commission Rate: " << rate << endl; + cout << "Commission: $" << commission << endl; + cout << "Advanced Pay: $" << advance << endl; + cout << "Remaining Pay: $" << pay << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/String Manipulation/Program 10-24.cpp b/SourceCode/case studies/String Manipulation/Program 10-24.cpp new file mode 100755 index 0000000..966ef3e --- /dev/null +++ b/SourceCode/case studies/String Manipulation/Program 10-24.cpp @@ -0,0 +1,195 @@ +// This program prints a simple form letter reminding a customer +// of an overdue account balance. +#include +#include +#include +using namespace std; + +// Function Prototypes +void printLetter(char *, char *, char *, char *, char *); +void getInfo(char *, char *, char *, char *, char *); +void getSal(char *); +void printline(const char *, int&); + +// Strings that make up the form letter +const char part1[] = "Dear "; +const char part2[] = "Our records show that your account has a" + " balance of $"; +const char part3[] = " and a past due amount of $"; +const char part4[] = "Your last payment was on "; +const char part5[] = "Since we haven't heard from you in some" + " time, would you please take a moment to send" + " us a check for the past-due amount? We value" + " your business and look forward to serving you" + " in the future.\n\n"; +const char part6[] = "Sincerely,\n"; +const char part7[] = "The Management\n\n"; +const char part8[] = "P.S. If you've already sent your payment, ignore" + " this reminder."; + +int main() +{ + char salutation[4]; // To hold the salutation + char lastName[16]; // Customer's last name + char lastPayment[16]; // Date of last payment + char balance[9]; // Account balace + char pastDue[9]; // Amount past due + char again; // To hold Y or N + + do + { + // Call getInfo to get input from the user + getInfo(salutation, lastName, balance, pastDue, + lastPayment); + cout << "\n\n"; + // Now print the form letter + printLetter(salutation, lastName, balance, pastDue, + lastPayment); + cout << "\n\nDo another letter? (Y/N) "; + cin >> again; + } while (toupper(again) == 'Y'); + return 0; +} + +//***************************************************************** +// Definition of function getInfo. * +// This function allows the user to enter the following items: * +// salutation, last name, account balance, past due amount, and * +// date of last payment. The function arguments are pointers to * +// strings where the input will be stored. * +//***************************************************************** + +void getInfo(char *sal, char *lname, char *bal, char *due, + char *lastPay) +{ + getSal(sal); + cout << "Last name: "; + cin >> lname; + lname[0] = toupper(lname[0]); + cout << "Account balance: "; + cin >> bal; + cout << "Past due Amount: "; + cin >> due; + cout << "Date of last payment (MM/DD/YYYY): "; + cin >> lastPay; +} + +//**************************************************************** +// Definition of function getSal. * +// This function gives the user a menu from which to pick a * +// suitable title for the letter's addressee. The choices are * +// Mr. and Ms. The choice will be copied to the address pointed * +// to by sal. * +//**************************************************************** + +void getSal(char *sal) +{ + int choice; + + do + { + cout << "salutation:\n"; + cout << "\t1) Mr.\n"; + cout << "\t2) Ms.\n"; + cout << "Select one: "; + cin >> choice; + } while (choice != 1 && choice != 2); + + if (choice == 1) + strcpy(sal, "Mr."); + else + strcpy(sal, "Ms."); +} + +//************************************************************* +// Definition of function printLetter. * +// This function prints the form letter. The parameters are * +// pointers to the fields that contain user input. * +//************************************************************* + +void printLetter(char *sal, char *lname, char *bal, char *due, + char *lastPay) +{ + int position; + + // Print the salutation part of the letter + position = 0; // Start a new line. + printline(part1, position); + cout << sal << " " << lname << ":" << endl << endl; + + // Print the body of the letter + position = 0; // Start a new line. + printline(part2, position); + cout << bal; // Print account balance. + + // Add length of balance to position. + position += strlen(bal); + printline(part3, position); + cout << due << ". "; // Print past due amount + position += strlen(due)+ 2; + + // Add length of due and the period and space at the + // end of the sentence to position. + printline(part4, position); + cout << lastPay << ". "; // Print date of last payment. + + // Now Add length of lastPay and the period and space at the + // end of the sentence to position. + position += strlen(lastPay) + 2; + printline(part5, position); + + // Print the closing. + position = 0; // Start a new line. + printline(part6, position); + position = 0; // Start a new line. + printline(part7, position); + + // Print the PS reminder. + position = 0; // Start a new line. + printline(part8, position); +} + +//******************************************************************* +// Definition of function printline. * +// This function has two parameters: line and startCount. * +// The string pointed to by line is printed. startCount is the * +// starting position of the line in an 80 character field. There * +// are 10-character left and right margins within the 80 * +// character field. The function performs word-wrap by looking * +// for space character within the line at or after the 60th * +// character. A new line is started when a space is found, or the * +// end of the field is reached. * +//******************************************************************* + +void printline(const char *line, int &startCount) +{ + int charCount = 0; + + if (startCount >= 70) // If the line is already at + { // or past the right margin... + cout << "\n"; // Start a new line. + startCount = 0; // Reset startCount. + } + + // The following while loop cycles through the string + // printing it one character at a time. It watches for + // spaces after the 60th position so word-wrap may be + // performed. + while (line[charCount] != '\0') + { + if (startCount >= 60 && line[charCount] == ' ') + { + cout << " \n"; // Print right margin. + charCount++; // Skip over the space. + startCount = 0; + } + if (startCount == 0) + { + cout << " "; // Print left margin. + startCount = 10; + } + cout.put(line[charCount]); // Print the character. + charCount++; // Update subscript. + startCount++; // Update position counter. + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Account.cpp b/SourceCode/chapter 13/Account.cpp new file mode 100755 index 0000000..1531464 --- /dev/null +++ b/SourceCode/chapter 13/Account.cpp @@ -0,0 +1,14 @@ +// Implementation file for the Account class. +#include "Account.h" + +bool Account::withdraw(double amount) +{ + if (balance < amount) + return false; // Not enough in the account + else + { + balance -= amount; + transactions++; + return true; + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Account.h b/SourceCode/chapter 13/Account.h new file mode 100755 index 0000000..86e8072 --- /dev/null +++ b/SourceCode/chapter 13/Account.h @@ -0,0 +1,42 @@ +// Specification file for the Account class. +#ifndef ACCOUNT_H +#define ACCOUNT_H + +class Account +{ +private: + double balance; // Account balance + double interestRate; // Interest rate for the period + double interest; // Interest earned for the period + int transactions; // Number of transactions +public: + Account(double iRate = 0.045, double bal = 0) + { balance = bal; + interestRate = iRate; + interest = 0; + transactions = 0; } + + void setInterestRate(double iRate) + { interestRate = iRate; } + + void makeDeposit(double amount) + { balance += amount; transactions++; } + + bool withdraw(double amount); // Defined in Account.cpp + + void calcInterest() + { interest = balance * interestRate; balance += interest; } + + double getInterestRate() const + { return interestRate; } + + double getBalance() const + { return balance; } + + double getInterest() const + { return interest; } + + int getTransactions() const + { return transactions; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/ContactInfo Version 1/ContactInfo.h b/SourceCode/chapter 13/ContactInfo Version 1/ContactInfo.h new file mode 100755 index 0000000..aa08154 --- /dev/null +++ b/SourceCode/chapter 13/ContactInfo Version 1/ContactInfo.h @@ -0,0 +1,34 @@ +// Specification file for the Contact class. +#ifndef CONTACTINFO_H +#define CONTACTINFO_H +#include // Needed for strlen and strcpy + +// ContactInfo class declaration. +class ContactInfo +{ +private: + char *name; // The contact's name + char *phone; // The contact's phone number +public: + // Constructor + ContactInfo(char *n, char *p) + { // Allocate just enough memory for the name and phone number. + name = new char[strlen(n) + 1]; + phone = new char[strlen(p) + 1]; + + // Copy the name and phone number to the allocated memory. + strcpy(name, n); + strcpy(phone, p); } + + // Destructor + ~ContactInfo() + { delete [] name; + delete [] phone; } + + const char *getName() const + { return name; } + + const char *getPhoneNumber() const + { return phone; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/ContactInfo Version 1/Pr13-12.cpp b/SourceCode/chapter 13/ContactInfo Version 1/Pr13-12.cpp new file mode 100755 index 0000000..1a3c4d8 --- /dev/null +++ b/SourceCode/chapter 13/ContactInfo Version 1/Pr13-12.cpp @@ -0,0 +1,16 @@ +// This program demonstrates a class with a destructor. +#include +#include "ContactInfo.h" +using namespace std; + +int main() +{ + // Define a ContactInfo object with the following data: + // Name: Kristen Lee Phone Number: 555-2021 + ContactInfo entry("Kristen Lee", "555-2021"); + + // Display the object's data. + cout << "Name: " << entry.getName() << endl; + cout << "Phone Number: " << entry.getPhoneNumber() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/ContactInfo Version 2/ContactInfo.h b/SourceCode/chapter 13/ContactInfo Version 2/ContactInfo.h new file mode 100755 index 0000000..580993b --- /dev/null +++ b/SourceCode/chapter 13/ContactInfo Version 2/ContactInfo.h @@ -0,0 +1,44 @@ +// Contact class specification file (version 2) +#ifndef CONTACTINFO_H +#define CONTACTINFO_H +#include // Needed for strlen and strcpy + +// ContactInfo class declaration. +class ContactInfo +{ +private: + char *name; // The contact's name + char *phone; // The contact's phone number + + // Private member function: initName + // This function initializes the name attribute. + void initName(char *n) + { name = new char[strlen(n) + 1]; + strcpy(name, n); } + + // Private member function: initPhone + // This function initializes the phone attribute. + void initPhone(char *p) + { phone = new char[strlen(p) + 1]; + strcpy(phone, p); } +public: + // Constructor + ContactInfo(char *n, char *p) + { // Initialize the name attribute. + initName(n); + + // Initialize the phone attribute. + initPhone(n); } + + // Destructor + ~ContactInfo() + { delete [] name; + delete [] phone; } + + const char *getName() const + { return name; } + + const char *getPhoneNumber() const + { return phone; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Dice/Die.cpp b/SourceCode/chapter 13/Dice/Die.cpp new file mode 100755 index 0000000..be47af9 --- /dev/null +++ b/SourceCode/chapter 13/Dice/Die.cpp @@ -0,0 +1,55 @@ +// Implememtation file for the Die class +#include // For rand and srand +#include // For the time function +#include "Die.h" +using namespace std; + +//******************************************************* +// The constructor accepts an argument for the number * +// of sides for the die, and performs a roll. * +//******************************************************* +Die::Die(int numSides) +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + // Set the number of sides. + sides = numSides; + + // Perform an initial roll. + roll(); +} + +//******************************************************* +// The roll member function simulates the rolling of * +// the die. * +//******************************************************* +void Die::roll() +{ + // Constant for the minimum die value + const int MIN_VALUE = 1; // Minimum die value + + // Get a random value for the die. + value = (rand() % (sides - MIN_VALUE + 1)) + MIN_VALUE; +} + +//******************************************************* +// The getSides member function returns the number of * +// for this die. * +//******************************************************* +int Die::getSides() +{ + return sides; +} + +//******************************************************* +// The getValue member function returns the die's value.* +//******************************************************* +int Die::getValue() +{ + return value; +} + diff --git a/SourceCode/chapter 13/Dice/Die.h b/SourceCode/chapter 13/Dice/Die.h new file mode 100755 index 0000000..585babc --- /dev/null +++ b/SourceCode/chapter 13/Dice/Die.h @@ -0,0 +1,17 @@ +// Specification file for the Die class +#ifndef DIE_H +#define DIE_H + +class Die +{ +private: + int sides; // Number of sides + int value; // The die's value + +public: + Die(int); // Constructor + void roll(); // Rolls the die + int getSides(); // Returns the number of sides + int getValue(); // REturns the die's value +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Dice/Pr13-16.cpp b/SourceCode/chapter 13/Dice/Pr13-16.cpp new file mode 100755 index 0000000..38d807a --- /dev/null +++ b/SourceCode/chapter 13/Dice/Pr13-16.cpp @@ -0,0 +1,39 @@ +// This program simulates the rolling of dice. +#include +#include "Die.h" +using namespace std; + +int main() +{ + const int DIE1_SIDES = 6; // Number of sides for die #1 + const int DIE2_SIDES = 12; // Number of sides for die #2 + const int MAX_ROLLS = 5; // Number of times to roll + + // Create two instances of the Die class. + Die die1(DIE1_SIDES); + Die die2(DIE2_SIDES); + + // Display the initial state of the dice. + cout << "This simulates the rolling of a " + << die1.getSides() << " sided die and a " + << die2.getSides() << " sided die.\n"; + + cout << "Initial value of the dice:\n"; + cout << die1.getValue() << " " + << die2.getValue() << endl; + + // Roll the dice five times. + cout << "Rolling the dice " << MAX_ROLLS + << " times.\n"; + for (int count = 0; count < MAX_ROLLS; count++) + { + // Roll the dice. + die1.roll(); + die2.roll(); + + // Display the values of the dice. + cout << die1.getValue() << " " + << die2.getValue() << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/IntegerList.cpp b/SourceCode/chapter 13/IntegerList.cpp new file mode 100755 index 0000000..7f04738 --- /dev/null +++ b/SourceCode/chapter 13/IntegerList.cpp @@ -0,0 +1,77 @@ +// Implementation file for the IntegerList class. +#include +#include +#include "IntegerList.h" +using namespace std; + +//*********************************************************** +// The constructor sets each element to zero. * +//*********************************************************** + +IntegerList::IntegerList(int size) +{ + list = new int[size]; + numElements = size; + for (int ndx = 0; ndx < size; ndx++) + list[ndx] = 0; +} + +//*********************************************************** +// The destructor releases allocated memory. * +//*********************************************************** + +IntegerList::~IntegerList() +{ + delete [] list; +} + +//*********************************************************** +// isValid member function. * +// This private member functon returns true if the argument * +// is a valid subscript, or false otherwise. * +//*********************************************************** + +bool IntegerList::isValid(int element) const +{ + bool status; + + if (element < 0 || element >= numElements) + status = false; + else + status = true; + return status; +} + +//*********************************************************** +// setElement member function. * +// Stores a value in a specific element of the list. If an * +// invalid subscript is passed, the program aborts. * +//*********************************************************** + +void IntegerList::setElement(int element, int value) +{ + if (isValid(element)) + list[element] = value; + else + { + cout << "Error: Invalid subscript\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// getElement member function. * +// Returns the value stored at the specified element. * +// If an invalid subscript is passed, the program aborts. * +//*********************************************************** + +int IntegerList::getElement(int element) const +{ + if (isValid(element)) + return list[element]; + else + { + cout << "Error: Invalid subscript\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/IntegerList.h b/SourceCode/chapter 13/IntegerList.h new file mode 100755 index 0000000..d870a8b --- /dev/null +++ b/SourceCode/chapter 13/IntegerList.h @@ -0,0 +1,17 @@ +// Specification file for the the IntegerList class. +#ifndef INTEGERLIST_H +#define INTEGERLIST_H + +class IntegerList +{ +private: + int *list; // Pointer to the array. + int numElements; // Number of elements. + bool isValid(int) const; // Validates subscripts. +public: + IntegerList(int); // Constructor + ~IntegerList(); // Destructor + void setElement(int, int); // Sets an element to a value + int getElement(int) const; // Returns an element +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/InventoryItem/InventoryItem.h b/SourceCode/chapter 13/InventoryItem/InventoryItem.h new file mode 100755 index 0000000..1b7aa2b --- /dev/null +++ b/SourceCode/chapter 13/InventoryItem/InventoryItem.h @@ -0,0 +1,57 @@ +// This class has overloaded constructors. +#ifndef INVENTORYITEM_H +#define INVENTORYITEM_H +#include +using namespace std; + +class InventoryItem +{ +private: + string description; // The item description + double cost; // The item cost + int units; // Number of units on hand +public: + // Constructor #1 + InventoryItem() + { // Initialize description, cost, and units. + description = ""; + cost = 0.0; + units = 0; } + + // Constructor #2 + InventoryItem(string desc) + { // Assign the value to description. + description = desc; + + // Initialize cost and units. + cost = 0.0; + units = 0; } + + // Constructor #3 + InventoryItem(string desc, double c, int u) + { // Assign values to description, cost, and units. + description = desc; + cost = c; + units = u; } + + // Mutator functions + void setDescription(string d) + { description = d; } + + void setCost(double c) + { cost = c; } + + void setUnits(int u) + { units = u; } + + // Accessor functions + string getDescription() const + { return description; } + + double getCost() const + { return cost; } + + int getUnits() const + { return units; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/InventoryItem/Pr13-13.cpp b/SourceCode/chapter 13/InventoryItem/Pr13-13.cpp new file mode 100755 index 0000000..6f1fadb --- /dev/null +++ b/SourceCode/chapter 13/InventoryItem/Pr13-13.cpp @@ -0,0 +1,41 @@ +// This program demonstrates a class with overloaded constructors. +#include +#include +#include "InventoryItem.h" + +int main() +{ + // Create an InventoryItem object and call + // the default constructor. + InventoryItem item1; + item1.setDescription("Hammer"); // Set the description + item1.setCost(6.95); // Set the cost + item1.setUnits(12); // Set the units + + // Create an InventoryItem object and call + // constructor #2. + InventoryItem item2("Pliers"); + + // Create an InventoryItem object and call + // constructor #3. + InventoryItem item3("Wrench", 8.75, 20); + + cout << "The following items are in inventory:\n"; + cout << setprecision(2) << fixed << showpoint; + + // Display the data for item 1. + cout << "Description: " << item1.getDescription() << endl; + cout << "Cost: $" << item1.getCost() << endl; + cout << "Units on Hand: " << item1.getUnits() << endl << endl; + + // Display the data for item 2. + cout << "Description: " << item2.getDescription() << endl; + cout << "Cost: $" << item2.getCost() << endl; + cout << "Units on Hand: " << item2.getUnits() << endl << endl; + + // Display the data for item 3. + cout << "Description: " << item3.getDescription() << endl; + cout << "Cost: $" << item3.getCost() << endl; + cout << "Units on Hand: " << item3.getUnits() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/InventoryItem/Pr13-14.cpp b/SourceCode/chapter 13/InventoryItem/Pr13-14.cpp new file mode 100755 index 0000000..4237e03 --- /dev/null +++ b/SourceCode/chapter 13/InventoryItem/Pr13-14.cpp @@ -0,0 +1,30 @@ +// This program demonstrates an array of class object. +#include +#include +#include "InventoryItem.h" +using namespace std; + +int main() +{ + const int NUM_ITEMS = 5; + InventoryItem inventory[NUM_ITEMS] = { + InventoryItem("Hammer", 6.95, 12), + InventoryItem("Wrench", 8.75, 20), + InventoryItem("Pliers", 3.75, 10), + InventoryItem("Ratchet", 7.95, 14), + InventoryItem("Screwdriver", 2.50, 22) }; + + cout << setw(14) << "Inventory Item" + << setw(8) << "Cost" << setw(8) + << setw(16) << "Units on Hand\n"; + cout << "-------------------------------------\n"; + + for (int i = 0; i < NUM_ITEMS; i++) + { + cout << setw(14) << inventory[i].getDescription(); + cout << setw(8) << inventory[i].getCost(); + cout << setw(7) << inventory[i].getUnits() << endl; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-1.cpp b/SourceCode/chapter 13/Pr13-1.cpp new file mode 100755 index 0000000..487e3e7 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-1.cpp @@ -0,0 +1,92 @@ +// This program demonstrates a simple class. +#include +using namespace std; + +// Rectangle class declaration. +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +//************************************************** +// setWidth assigns a value to the width member. * +//************************************************** + +void Rectangle::setWidth(double w) +{ + width = w; +} + +//************************************************** +// setLength assigns a value to the length member. * +//************************************************** + +void Rectangle::setLength(double len) +{ + length = len; +} + +//************************************************** +// getWidth returns the value in the width member. * +//************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//**************************************************** +// getLength returns the value in the length member. * +//**************************************************** + +double Rectangle::getLength() const +{ + return length; +} + +//***************************************************** +// getArea returns the product of width times length. * +//***************************************************** + +double Rectangle::getArea() const +{ + return width * length; +} + +//***************************************************** +// Function main * +//***************************************************** + +int main() +{ + Rectangle box; // Define an instance of the Rectangle class + double rectWidth; // Local variable for width + double rectLength; // Local variable for length + + // Get the rectangle's width and length from the user. + cout << "This program will calculate the area of a\n"; + cout << "rectangle. What is the width? "; + cin >> rectWidth; + cout << "What is the length? "; + cin >> rectLength; + + // Store the width and length of the rectangle + // in the box object. + box.setWidth(rectWidth); + box.setLength(rectLength); + + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-11.cpp b/SourceCode/chapter 13/Pr13-11.cpp new file mode 100755 index 0000000..d4484c0 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-11.cpp @@ -0,0 +1,33 @@ +// This program demonstrates a destructor. +#include +using namespace std; + +class Demo +{ +public: + Demo(); // Constructor + ~Demo(); // Destructor +}; + +Demo::Demo() +{ + cout << "Welcome to the constructor!\n"; +} + +Demo::~Demo() +{ + cout << "The destructor is now running.\n"; +} + +//********************************************* +// Function main. * +//********************************************* + +int main() +{ + Demo demoObject; // Define a demo object; + + cout << "This program demonstrates an object\n"; + cout << "with a constructor and destructor.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-15.cpp b/SourceCode/chapter 13/Pr13-15.cpp new file mode 100755 index 0000000..5dc20de --- /dev/null +++ b/SourceCode/chapter 13/Pr13-15.cpp @@ -0,0 +1,116 @@ +// This program demonstrates the Account class. +#include +#include +#include +#include "Account.h" +using namespace std; + +// Function prototypes +void displayMenu(); +void makeDeposit(Account &); +void withdraw(Account &); + +int main() +{ + Account savings; // Savings account object + char choice; // Menu selection + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu and get a valid selection. + displayMenu(); + cin >> choice; + while (toupper(choice) < 'A' || toupper(choice) > 'G') + { + cout << "Please make a choice in the range " + << "of A through G:"; + cin >> choice; + } + + // Process the user's menu selection. + switch(choice) + { + case 'a': + case 'A': cout << "The current balance is $"; + cout << savings.getBalance() << endl; + break; + case 'b': + case 'B': cout << "There have been "; + cout << savings.getTransactions() + << " transactions.\n"; + break; + case 'c': + case 'C': cout << "Interest earned for this period: $"; + cout << savings.getInterest() << endl; + break; + case 'd': + case 'D': makeDeposit(savings); + break; + case 'e': + case 'E': withdraw(savings); + break; + case 'f': + case 'F': savings.calcInterest(); + cout << "Interest added.\n"; + } + } while (toupper(choice) != 'G'); + + return 0; +} + +//**************************************************** +// Definition of function displayMenu. This function * +// displays the user's menu on the screen. * +//**************************************************** + +void displayMenu() +{ + cout << "\n MENU\n"; + cout << "-----------------------------------------\n"; + cout << "A) Display the account balance\n"; + cout << "B) Display the number of transactions\n"; + cout << "C) Display interest earned for this period\n"; + cout << "D) Make a deposit\n"; + cout << "E) Make a withdrawal\n"; + cout << "F) Add interest for this period\n"; + cout << "G) Exit the program\n\n"; + cout << "Enter your choice: "; +} + +//************************************************************* +// Definition of function makeDeposit. This function accepts * +// a reference to an Account object. The user is prompted for * +// the dollar amount of the deposit, and the makeDeposit * +// member of the Account object is then called. * +//************************************************************* + +void makeDeposit(Account &acnt) +{ + double dollars; + + cout << "Enter the amount of the deposit: "; + cin >> dollars; + cin.ignore(); + acnt.makeDeposit(dollars); +} + +//************************************************************* +// Definition of function withdraw. This function accepts * +// a reference to an Account object. The user is prompted for * +// the dollar amount of the withdrawal, and the withdraw * +// member of the Account object is then called. * +//************************************************************* + +void withdraw(Account &acnt) +{ + double dollars; + + cout << "Enter the amount of the withdrawal: "; + cin >> dollars; + cin.ignore(); + if (!acnt.withdraw(dollars)) + cout << "ERROR: Withdrawal amount too large.\n\n"; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-17.cpp b/SourceCode/chapter 13/Pr13-17.cpp new file mode 100755 index 0000000..c5a3d23 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-17.cpp @@ -0,0 +1,35 @@ +// This program demonstrates the IntegerList class. +#include +#include "IntegerList.h" +using namespace std; + +int main() +{ + const int SIZE = 20; + IntegerList numbers(SIZE); + int val, x; + + // Store 9s in the list and display an asterisk + // each time a 9 is successfully stored. + for (x = 0; x < SIZE; x++) + { + numbers.setElement(x, 9); + cout << "* "; + } + cout << endl; + + // Display the 9s. + for (x = 0; x < SIZE; x++) + { + val = numbers.getElement(x); + cout << val << " "; + } + cout << endl; + + // Attempt to store a value outside the list's bounds. + numbers.setElement(50, 9); + + // Will this message display? + cout << "Element 50 successfully set.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-2.cpp b/SourceCode/chapter 13/Pr13-2.cpp new file mode 100755 index 0000000..27abe45 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-2.cpp @@ -0,0 +1,109 @@ +// This program creates three instances of the Rectangle class. +#include +using namespace std; + +// Rectangle class declaration. +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +//************************************************** +// setWidth assigns a value to the width member. * +//************************************************** + +void Rectangle::setWidth(double w) +{ + width = w; +} + +//************************************************** +// setLength assigns a value to the length member. * +//************************************************** + +void Rectangle::setLength(double len) +{ + length = len; +} + +//************************************************** +// getWidth returns the value in the width member. * +//************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//**************************************************** +// getLength returns the value in the length member. * +//**************************************************** + +double Rectangle::getLength() const +{ + return length; +} + +//***************************************************** +// getArea returns the product of width times length. * +//***************************************************** + +double Rectangle::getArea() const +{ + return width * length; +} + +//***************************************************** +// Function main * +//***************************************************** + +int main() +{ + double number; // To hold a number + double totalArea; // The total area + Rectangle kitchen; // To hold kitchen dimensions + Rectangle bedroom; // To hold bedroom dimensions + Rectangle den; // To hold den dimensions + + // Get the kitchen dimensions. + cout << "What is the kitchen's length? "; + cin >> number; // Get the length + kitchen.setLength(number); // Store in kitchen object + cout << "What is the kitchen's width? "; + cin >> number; // Get the width + kitchen.setWidth(number); // Store in kitchen object + + // Get the bedroom dimensions. + cout << "What is the bedroom's length? "; + cin >> number; // Get the length + bedroom.setLength(number); // Store in bedroom object + cout << "What is the bedroom's width? "; + cin >> number; // Get the width + bedroom.setWidth(number); // Store in bedroom object + + // Get the den dimensions. + cout << "What is the den's length? "; + cin >> number; // Get the length + den.setLength(number); // Store in den object + cout << "What is the den's width? "; + cin >> number; // Get the width + den.setWidth(number); // Store in den object + + // Calculate the total area of the three rooms. + totalArea = kitchen.getArea() + bedroom.getArea() + + den.getArea(); + + // Display the total area of the three rooms. + cout << "The total area of the three rooms is " + << totalArea << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-3.cpp b/SourceCode/chapter 13/Pr13-3.cpp new file mode 100755 index 0000000..9b0cb51 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-3.cpp @@ -0,0 +1,122 @@ +// This program creates three instances of the Rectangle class. +#include +using namespace std; + +// Rectangle class declaration. +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +//************************************************** +// setWidth assigns a value to the width member. * +//************************************************** + +void Rectangle::setWidth(double w) +{ + width = w; +} + +//************************************************** +// setLength assigns a value to the length member. * +//************************************************** + +void Rectangle::setLength(double len) +{ + length = len; +} + +//************************************************** +// getWidth returns the value in the width member. * +//************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//**************************************************** +// getLength returns the value in the length member. * +//**************************************************** + +double Rectangle::getLength() const +{ + return length; +} + +//***************************************************** +// getArea returns the product of width times length. * +//***************************************************** + +double Rectangle::getArea() const +{ + return width * length; +} + +//***************************************************** +// Function main * +//***************************************************** + +int main() +{ + double number; // To hold a number + double totalArea; // The total area + Rectangle *kitchen = nullptr; // To point to kitchen dimensions + Rectangle *bedroom = nullptr; // To point to bedroom dimensions + Rectangle *den = nullptr; // To point to den dimensions + + // Dynamically allocate the objects. + kitchen = new Rectangle; + bedroom = new Rectangle; + den = new Rectangle; + + // Get the kitchen dimensions. + cout << "What is the kitchen's length? "; + cin >> number; // Get the length + kitchen->setLength(number); // Store in kitchen object + cout << "What is the kitchen's width? "; + cin >> number; // Get the width + kitchen->setWidth(number); // Store in kitchen object + + // Get the bedroom dimensions. + cout << "What is the bedroom's length? "; + cin >> number; // Get the length + bedroom->setLength(number); // Store in bedroom object + cout << "What is the bedroom's width? "; + cin >> number; // Get the width + bedroom->setWidth(number); // Store in bedroom object + + // Get the den dimensions. + cout << "What is the den's length? "; + cin >> number; // Get the length + den->setLength(number); // Store in den object + cout << "What is the den's width? "; + cin >> number; // Get the width + den->setWidth(number); // Store in den object + + // Calculate the total area of the three rooms. + totalArea = kitchen->getArea() + bedroom->getArea() + + den->getArea(); + + // Display the total area of the three rooms. + cout << "The total area of the three rooms is " + << totalArea << endl; + + // Delete the objects from memory. + delete kitchen; + delete bedroom; + delete den; + kitchen = nullptr; // Make kitchen a null pointer. + bedroom = nullptr; // Make bedroom a null pointer. + den = nullptr; // Make den a null pointer. + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-4.cpp b/SourceCode/chapter 13/Pr13-4.cpp new file mode 100755 index 0000000..47a553b --- /dev/null +++ b/SourceCode/chapter 13/Pr13-4.cpp @@ -0,0 +1,113 @@ +// This program uses smart pointers to allocate three +// instances of the Rectangle class. +#include +#include +using namespace std; + +// Rectangle class declaration. +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +//************************************************** +// setWidth assigns a value to the width member. * +//************************************************** + +void Rectangle::setWidth(double w) +{ + width = w; +} + +//************************************************** +// setLength assigns a value to the length member. * +//************************************************** + +void Rectangle::setLength(double len) +{ + length = len; +} + +//************************************************** +// getWidth returns the value in the width member. * +//************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//**************************************************** +// getLength returns the value in the length member. * +//**************************************************** + +double Rectangle::getLength() const +{ + return length; +} + +//***************************************************** +// getArea returns the product of width times length. * +//***************************************************** + +double Rectangle::getArea() const +{ + return width * length; +} + +//***************************************************** +// Function main * +//***************************************************** + +int main() +{ + double number; // To hold a number + double totalArea; // The total area + + // Dynamically allocate the objects. + unique_ptr kitchen(new Rectangle); + unique_ptr bedroom(new Rectangle); + unique_ptr den(new Rectangle); + + // Get the kitchen dimensions. + cout << "What is the kitchen's length? "; + cin >> number; // Get the length + kitchen->setLength(number); // Store in kitchen object + cout << "What is the kitchen's width? "; + cin >> number; // Get the width + kitchen->setWidth(number); // Store in kitchen object + + // Get the bedroom dimensions. + cout << "What is the bedroom's length? "; + cin >> number; // Get the length + bedroom->setLength(number); // Store in bedroom object + cout << "What is the bedroom's width? "; + cin >> number; // Get the width + bedroom->setWidth(number); // Store in bedroom object + + // Get the den dimensions. + cout << "What is the den's length? "; + cin >> number; // Get the length + den->setLength(number); // Store in den object + cout << "What is the den's width? "; + cin >> number; // Get the width + den->setWidth(number); // Store in den object + + // Calculate the total area of the three rooms. + totalArea = kitchen->getArea() + bedroom->getArea() + + den->getArea(); + + // Display the total area of the three rooms. + cout << "The total area of the three rooms is " + << totalArea << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-6.cpp b/SourceCode/chapter 13/Pr13-6.cpp new file mode 100755 index 0000000..abf3f63 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-6.cpp @@ -0,0 +1,29 @@ +// This program demonstrates a constructor. +#include +using namespace std; + +// Demo class declaration. + +class Demo +{ +public: + Demo(); // Constructor +}; + +Demo::Demo() +{ + cout << "Welcome to the constructor!\n"; +} + +//***************************************** +// Function main. * +//***************************************** + +int main() +{ + Demo demoObject; // Define a Demo object; + + cout << "This program demonstrates an object\n"; + cout << "with a constructor.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 1/Pr13-5.cpp b/SourceCode/chapter 13/Rectangle Version 1/Pr13-5.cpp new file mode 100755 index 0000000..ea45d2f --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 1/Pr13-5.cpp @@ -0,0 +1,33 @@ +// This program uses the Rectangle class, which is declared in +// the Rectangle.h file. The member Rectangle class's member +// functions are defined in the Rectangle.cpp file. This program +// should be compiled with those files in a project. +#include +#include "Rectangle.h" // Needed for Rectangle class +using namespace std; + +int main() +{ + Rectangle box; // Define an instance of the Rectangle class + double rectWidth; // Local variable for width + double rectLength; // Local variable for length + + // Get the rectangle's width and length from the user. + cout << "This program will calculate the area of a\n"; + cout << "rectangle. What is the width? "; + cin >> rectWidth; + cout << "What is the length? "; + cin >> rectLength; + + // Store the width and length of the rectangle + // in the box object. + box.setWidth(rectWidth); + box.setLength(rectLength); + + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 1/Rectangle.cpp b/SourceCode/chapter 13/Rectangle Version 1/Rectangle.cpp new file mode 100755 index 0000000..784c834 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 1/Rectangle.cpp @@ -0,0 +1,62 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// getWidth returns the value in the member variable width. * +//*********************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//************************************************************* +// getLength returns the value in the member variable length. * +//************************************************************* + +double Rectangle::getLength() const +{ + return length; +} + +//************************************************************ +// getArea returns the product of width times length. * +//************************************************************ + +double Rectangle::getArea() const +{ + return width * length; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 1/Rectangle.h b/SourceCode/chapter 13/Rectangle Version 1/Rectangle.h new file mode 100755 index 0000000..1cbef04 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 1/Rectangle.h @@ -0,0 +1,20 @@ +// Specification file for the Rectangle class. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +// Rectangle class declaration. + +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 2/Rectangle.cpp b/SourceCode/chapter 13/Rectangle Version 2/Rectangle.cpp new file mode 100755 index 0000000..6038ae4 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 2/Rectangle.cpp @@ -0,0 +1,37 @@ +// Implementation file for the Rectangle class. +// In this version of the class, the getWidth, getLength, +// and getArea functions are written inline in Rectangle.h. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 2/Rectangle.h b/SourceCode/chapter 13/Rectangle Version 2/Rectangle.h new file mode 100755 index 0000000..9630ae8 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 2/Rectangle.h @@ -0,0 +1,24 @@ +// Specification file for the Rectangle class +// This version uses some inline member functions. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 3/Pr13-7.cpp b/SourceCode/chapter 13/Rectangle Version 3/Pr13-7.cpp new file mode 100755 index 0000000..f775ee5 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 3/Pr13-7.cpp @@ -0,0 +1,16 @@ +// This program uses the Rectangle class's constructor. +#include +#include "Rectangle.h" // Needed for Rectangle class +using namespace std; + +int main() +{ + Rectangle box; // Define an instance of the Rectangle class + + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 3/Rectangle.cpp b/SourceCode/chapter 13/Rectangle Version 3/Rectangle.cpp new file mode 100755 index 0000000..d090c67 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 3/Rectangle.cpp @@ -0,0 +1,46 @@ +// Implementation file for the Rectangle class. +// This version has a constructor. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// The constructor initializes width and length to 0.0. * +//*********************************************************** + +Rectangle::Rectangle() +{ + width = 0.0; + length = 0.0; +} + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 3/Rectangle.h b/SourceCode/chapter 13/Rectangle Version 3/Rectangle.h new file mode 100755 index 0000000..b40f846 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 3/Rectangle.h @@ -0,0 +1,25 @@ +// Specification file for the Rectangle class +// This version has a constructor. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; + double length; + public: + Rectangle(); // Constructor + void setWidth(double); + void setLength(double); + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 4/Pr13-8.cpp b/SourceCode/chapter 13/Rectangle Version 4/Pr13-8.cpp new file mode 100755 index 0000000..647eb35 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 4/Pr13-8.cpp @@ -0,0 +1,32 @@ +// This program calls the Rectangle class constructor. +#include +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + double houseWidth, // To hold the room width + houseLength; // To hold the room length + + // Get the width of the house. + cout << "In feet, how wide is your house? "; + cin >> houseWidth; + + // Get the length of the house. + cout << "In feet, how long is your house? "; + cin >> houseLength; + + // Create a Rectangle object. + Rectangle house(houseWidth, houseLength ); + + // Display the house's width, length, and area. + cout << setprecision(2) << fixed; + cout << "The house is " << house.getWidth() + << " feet wide.\n"; + cout << "The house is " << house.getLength() + << " feet long.\n"; + cout << "The house has " << house.getArea() + << " square feet of area.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 4/Rectangle.cpp b/SourceCode/chapter 13/Rectangle Version 4/Rectangle.cpp new file mode 100755 index 0000000..200f8fb --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 4/Rectangle.cpp @@ -0,0 +1,46 @@ +// Implementation file for the Rectangle class. +// This version has a constructor that accepts arguments. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// The constructor accepts arguments for width and length. * +//*********************************************************** + +Rectangle::Rectangle(double w, double len) +{ + width = w; + length = len; +} + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 4/Rectangle.h b/SourceCode/chapter 13/Rectangle Version 4/Rectangle.h new file mode 100755 index 0000000..ac8f474 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 4/Rectangle.h @@ -0,0 +1,25 @@ +// Specification file for the Rectangle class +// This version has a constructor. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; + double length; + public: + Rectangle(double, double); // Constructor + void setWidth(double); + void setLength(double); + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Sale Version 1/Pr13-9.cpp b/SourceCode/chapter 13/Sale Version 1/Pr13-9.cpp new file mode 100755 index 0000000..0689cdd --- /dev/null +++ b/SourceCode/chapter 13/Sale Version 1/Pr13-9.cpp @@ -0,0 +1,28 @@ +// This program demonstrates passing an argument to a constructor. +#include +#include +#include "Sale.h" +using namespace std; + +int main() +{ + const double TAX_RATE = 0.06; // 6 percent sales tax rate + double cost; // To hold the item cost + + // Get the cost of the item. + cout << "Enter the cost of the item: "; + cin >> cost; + + // Create a Sale object for this transaction. + Sale itemSale(cost, TAX_RATE); + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the sales tax and total. + cout << "The amount of sales tax is $" + << itemSale.getTax() << endl; + cout << "The total of the sale is $"; + cout << itemSale.getTotal() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Sale Version 1/Sale.h b/SourceCode/chapter 13/Sale Version 1/Sale.h new file mode 100755 index 0000000..77b528b --- /dev/null +++ b/SourceCode/chapter 13/Sale Version 1/Sale.h @@ -0,0 +1,27 @@ +// Specification file for the Sale class. +#ifndef SALE_H +#define SALE_H + +class Sale +{ +private: + double itemCost; // Cost of the item + double taxRate; // Sales tax rate +public: + Sale(double cost, double rate) + { itemCost = cost; + taxRate = rate; } + + double getItemCost() const + { return itemCost; } + + double getTaxRate() const + { return taxRate; } + + double getTax() const + { return (itemCost * taxRate); } + + double getTotal() const + { return (itemCost + getTax()); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Sale Version 2/Pr13-10.cpp b/SourceCode/chapter 13/Sale Version 2/Pr13-10.cpp new file mode 100755 index 0000000..ffda451 --- /dev/null +++ b/SourceCode/chapter 13/Sale Version 2/Pr13-10.cpp @@ -0,0 +1,29 @@ +// This program uses a constructor's default argument. +#include +#include +#include "Sale.h" +using namespace std; + +int main() +{ + double cost; // To hold the item cost + + // Get the cost of the item. + cout << "Enter the cost of the item: "; + cin >> cost; + + // Create a Sale object for this transaction. + // Specify the item cost, but use the default + // tax rate of 5 percent. + Sale itemSale(cost); + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the sales tax and total. + cout << "The amount of sales tax is $" + << itemSale.getTax() << endl; + cout << "The total of the sale is $"; + cout << itemSale.getTotal() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Sale Version 2/Sale.h b/SourceCode/chapter 13/Sale Version 2/Sale.h new file mode 100755 index 0000000..8cffa06 --- /dev/null +++ b/SourceCode/chapter 13/Sale Version 2/Sale.h @@ -0,0 +1,28 @@ +// This version of the Sale class uses a default argument +// in the constructor. +#ifndef SALE_H +#define SALE_H + +class Sale +{ +private: + double itemCost; // Cost of the item + double taxRate; // Sales tax rate +public: + Sale(double cost, double rate = 0.05) + { itemCost = cost; + taxRate = rate; } + + double getItemCost() const + { return itemCost; } + + double getTaxRate() const + { return taxRate; } + + double getTax() const + { return (itemCost * taxRate); } + + double getTotal() const + { return (itemCost + getTax()); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 1/Budget.h b/SourceCode/chapter 14/Budget Version 1/Budget.h new file mode 100755 index 0000000..ef246cf --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 1/Budget.h @@ -0,0 +1,28 @@ +#ifndef BUDGET_H +#define BUDGET_H + +// Budget class declaration +class Budget +{ +private: + static double corpBudget; // Static member + double divisionBudget; // Instance member +public: + Budget() + { divisionBudget = 0; } + + void addBudget(double b) + { divisionBudget += b; + corpBudget += b; } + + double getDivisionBudget() const + { return divisionBudget; } + + double getCorpBudget() const + { return corpBudget; } +}; + +// Definition of static member variable corpBudget +double Budget::corpBudget = 0; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 1/Pr14-2.cpp b/SourceCode/chapter 14/Budget Version 1/Pr14-2.cpp new file mode 100755 index 0000000..5ead76e --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 1/Pr14-2.cpp @@ -0,0 +1,35 @@ +// This program demonstrates a static class member variable. +#include +#include +#include "Budget.h" +using namespace std; + +int main() +{ + int count; // Loop counter + const int NUM_DIVISIONS = 4; // Number of divisions + Budget divisions[NUM_DIVISIONS]; // Array of Budget objects + + // Get the budget requests for each division. + for (count = 0; count < NUM_DIVISIONS; count++) + { + double budgetAmount; + cout << "Enter the budget request for division "; + cout << (count + 1) << ": "; + cin >> budgetAmount; + divisions[count].addBudget(budgetAmount); + } + + // Display the budget requests and the corporate budget. + cout << fixed << showpoint << setprecision(2); + cout << "\nHere are the division budget requests:\n"; + for (count = 0; count < NUM_DIVISIONS; count++) + { + cout << "\tDivision " << (count + 1) << "\t$ "; + cout << divisions[count].getDivisionBudget() << endl; + } + cout << "\tTotal Budget Requests:\t$ "; + cout << divisions[0].getCorpBudget() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 2/Budget.cpp b/SourceCode/chapter 14/Budget Version 2/Budget.cpp new file mode 100755 index 0000000..3278b48 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 2/Budget.cpp @@ -0,0 +1,15 @@ +#include "Budget.h" + +// Definition of corpBudget static member variable +double Budget::corpBudget = 0; + +//********************************************************** +// Definition of static member function mainOffice. * +// This function adds the main office's budget request to * +// the corpBudget variable. * +//********************************************************** + +void Budget::mainOffice(double moffice) +{ + corpBudget += moffice; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 2/Budget.h b/SourceCode/chapter 14/Budget Version 2/Budget.h new file mode 100755 index 0000000..9ea96b8 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 2/Budget.h @@ -0,0 +1,27 @@ +#ifndef BUDGET_H +#define BUDGET_H + +// Budget class declaration +class Budget +{ +private: + static double corpBudget; // Static member variable + double divisionBudget; // Instance member variable +public: + Budget() + { divisionBudget = 0; } + + void addBudget(double b) + { divisionBudget += b; + corpBudget += b; } + + double getDivisionBudget() const + { return divisionBudget; } + + double getCorpBudget() const + { return corpBudget; } + + static void mainOffice(double); // Static member function +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 2/Pr14-3.cpp b/SourceCode/chapter 14/Budget Version 2/Pr14-3.cpp new file mode 100755 index 0000000..d77028c --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 2/Pr14-3.cpp @@ -0,0 +1,43 @@ +// This program demonstrates a static member function. +#include +#include +#include "Budget.h" +using namespace std; + +int main() +{ + int count; // Loop counter + double mainOfficeRequest; // Main office budget request + const int NUM_DIVISIONS = 4; // Number of divisions + + // Get the main office's budget request. + // Note that no instances of the Budget class have been defined. + cout << "Enter the main office's budget request: "; + cin >> mainOfficeRequest; + Budget::mainOffice(mainOfficeRequest); + + Budget divisions[NUM_DIVISIONS]; // An array of Budget objects. + + // Get the budget requests for each division. + for (count = 0; count < NUM_DIVISIONS; count++) + { + double budgetAmount; + cout << "Enter the budget request for division "; + cout << (count + 1) << ": "; + cin >> budgetAmount; + divisions[count].addBudget(budgetAmount); + } + + // Display the budget requests and the corporate budget. + cout << fixed << showpoint << setprecision(2); + cout << "\nHere are the division budget requests:\n"; + for (count = 0; count < NUM_DIVISIONS; count++) + { + cout << "\tDivision " << (count + 1) << "\t$ "; + cout << divisions[count].getDivisionBudget() << endl; + } + cout << "\tTotal Budget Requests:\t$ "; + cout << divisions[0].getCorpBudget() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Auxil.cpp b/SourceCode/chapter 14/Budget Version 3/Auxil.cpp new file mode 100755 index 0000000..01b4c02 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Auxil.cpp @@ -0,0 +1,15 @@ +#include "Auxil.h" +#include "Budget.h" + +//*********************************************************** +// Definition of member function mainOffice. * +// This function is declared a friend by the Budget class. * +// It adds the value of argument b to the static corpBudget * +// member variable of the Budget class. * +//*********************************************************** + +void AuxiliaryOffice::addBudget(double b, Budget &div) +{ + auxBudget += b; + div.corpBudget += b; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Auxil.h b/SourceCode/chapter 14/Budget Version 3/Auxil.h new file mode 100755 index 0000000..6476d81 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Auxil.h @@ -0,0 +1,22 @@ +#ifndef AUXIL_H +#define AUXIL_H + +class Budget; // Forward declaration of Budget class + +// Aux class declaration + +class AuxiliaryOffice +{ +private: + double auxBudget; +public: + AuxiliaryOffice() + { auxBudget = 0; } + + double getDivisionBudget() const + { return auxBudget; } + + void addBudget(double, Budget &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Budget.cpp b/SourceCode/chapter 14/Budget Version 3/Budget.cpp new file mode 100755 index 0000000..390b5cd --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Budget.cpp @@ -0,0 +1,13 @@ +#include "Budget.h" +double Budget::corpBudget = 0; // Definition of static member variable + +//********************************************************** +// Definition of static member function mainOffice. * +// This function adds the main office's budget request to * +// the corpBudget variable. * +//********************************************************** + +void Budget::mainOffice(double moffice) +{ + corpBudget += moffice; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Budget.h b/SourceCode/chapter 14/Budget Version 3/Budget.h new file mode 100755 index 0000000..1d81296 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Budget.h @@ -0,0 +1,32 @@ +#ifndef BUDGET_H +#define BUDGET_H +#include "Auxil.h" + +// Budget class declaration +class Budget +{ +private: + static double corpBudget; // Static member variable + double divisionBudget; // Instance member variable +public: + Budget() + { divisionBudget = 0; } + + void addBudget(double b) + { divisionBudget += b; + corpBudget += b; } + + double getDivisionBudget() const + { return divisionBudget; } + + double getCorpBudget() const + { return corpBudget; } + + // Static member function + static void mainOffice(double); + + // Friend function + friend void AuxiliaryOffice::addBudget(double, Budget &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Pr14-4.cpp b/SourceCode/chapter 14/Budget Version 3/Pr14-4.cpp new file mode 100755 index 0000000..f99637f --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Pr14-4.cpp @@ -0,0 +1,53 @@ +// This program demonstrates a static member function. +#include +#include +#include "Budget.h" +using namespace std; + +int main() +{ + int count; // Loop counter + double mainOfficeRequest; // Main office budget request + const int NUM_DIVISIONS = 4; // Number of divisions + + // Get the main office's budget request. + cout << "Enter the main office's budget request: "; + cin >> mainOfficeRequest; + Budget::mainOffice(mainOfficeRequest); + + Budget divisions[NUM_DIVISIONS]; // Array of Budget objects. + AuxiliaryOffice auxOffices[4]; // Array of AuxiliaryOffice + + // Get the budget requests for each division + // and their auxiliary offices. + for (count = 0; count < NUM_DIVISIONS; count++) + { + double budgetAmount; // To hold input + + // Get the request for the division office. + cout << "Enter the budget request for division "; + cout << (count + 1) << ": "; + cin >> budgetAmount; + divisions[count].addBudget(budgetAmount); + + // Get the request for the auxiliary office. + cout << "Enter the budget request for that division's\n"; + cout << "auxiliary office: "; + cin >> budgetAmount; + auxOffices[count].addBudget(budgetAmount, divisions[count]); + } + + // Display the budget requests and the corporate budget. + cout << fixed << showpoint << setprecision(2); + cout << "\nHere are the division budget requests:\n"; + for (count = 0; count < NUM_DIVISIONS; count++) + { + cout << "\tDivision " << (count + 1) << "\t\t$"; + cout << divisions[count].getDivisionBudget() << endl; + cout << "\tAuxiliary office:\t$"; + cout << auxOffices[count].getDivisionBudget() << endl << endl; + } + cout << "Total Budget Requests:\t$ "; + cout << divisions[0].getCorpBudget() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/ChoHan/Dealer.cpp b/SourceCode/chapter 14/ChoHan/Dealer.cpp new file mode 100755 index 0000000..8f15d8c --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Dealer.cpp @@ -0,0 +1,72 @@ +// Implementation file for the Dealer class +#include "Dealer.h" +#include "Die.h" +#include +using namespace std; + +//****************************************** +// Constructor * +//****************************************** +Dealer::Dealer() +{ + // Set the intial dice values to 0. + // (We will not use these values.) + die1Value = 0; + die2Value = 0; +} + +//****************************************** +// The rollDice member function rolls the * +// dice and saves their values. * +//****************************************** +void Dealer::rollDice() +{ + // Roll the dice. + die1.roll(); + die2.roll(); + + // Save the dice values. + die1Value = die1.getValue(); + die2Value = die2.getValue(); +} + +//****************************************** +// The getChoOrHan member function returns * +// the result of the dice roll, Cho (even) * +// or Han (odd). * +//****************************************** +string Dealer::getChoOrHan() +{ + string result; // To hold the result + + // Get the sum of the dice. + int sum = die1Value + die2Value; + + // Determine even or odd. + if (sum % 2 == 0) + result = "Cho (even)"; + else + result = "Han (odd)"; + + // Return the result. + return result; +} + +//******************************************* +// The getDie1Value member function returns * +// the value of die #1. * +//******************************************* +int Dealer::getDie1Value() +{ + return die1Value; +} + +//******************************************* +// The getDie2Value member function returns * +// the value of die #2. * +//******************************************* +int Dealer::getDie2Value() +{ + return die2Value; +} + diff --git a/SourceCode/chapter 14/ChoHan/Dealer.h b/SourceCode/chapter 14/ChoHan/Dealer.h new file mode 100755 index 0000000..7c2db6d --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Dealer.h @@ -0,0 +1,24 @@ +// Specification file for the Dealer class +#ifndef DEALER_H +#define DEALER_H +#include +#include "Die.h" +using namespace std; + +class Dealer +{ +private: + Die die1; // Object for die #1 + Die die2; // Object for die #2 + int die1Value; // Value of die #1 + int die2Value; // Value of die #2 + +public: + Dealer(); // Constructor + void rollDice(); // To roll the dice + string getChoOrHan(); // To get the result (Cho or Han) + int getDie1Value(); // To get the value of die #1 + int getDie2Value(); // To get the value of die #2 +}; +#endif + diff --git a/SourceCode/chapter 14/ChoHan/Player.cpp b/SourceCode/chapter 14/ChoHan/Player.cpp new file mode 100755 index 0000000..2a26f1d --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Player.cpp @@ -0,0 +1,80 @@ +// Implementation file for the Player class +#include "Player.h" +#include +#include +#include +using namespace std; + +//********************************************** +// Constructor * +//********************************************** +Player::Player(string playerName) +{ + // Seed the random number generator. + srand(time(0)); + + name = playerName; + guess = ""; + points = 0; +} + +//********************************************** +// The makeGuess member function causes the * +// player to make a guess, either "Cho (even)" * +// or "Han (odd)". * +//********************************************** +void Player::makeGuess() +{ + const int MIN_VALUE = 0; + const int MAX_VALUE = 1; + + int guessNumber; // For the user's guess + + // Get a random number, either 0 or 1. + guessNumber = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + + // Convert the random number to Cho or Han. + if (guessNumber == 0) + guess = "Cho (even)"; + else + guess = "Han (odd)"; +} + +//********************************************** +// The addPoints member function adds a * +// specified number of points to the player's * +// current balance. * +//********************************************** +void Player::addPoints(int newPoints) +{ + points += newPoints; +} + +//********************************************** +// The getName member function returns a * +// player's name. * +//********************************************** +string Player::getName() +{ + return name; +} + +//********************************************** +// The getGuess member function returns a * +// player's guess. * +//********************************************** +string Player::getGuess() +{ + return guess; +} + +//********************************************** +// The getPoints member function returns a * +// player's points. * +//********************************************** +int Player::getPoints() +{ + return points; +} + + diff --git a/SourceCode/chapter 14/ChoHan/Player.h b/SourceCode/chapter 14/ChoHan/Player.h new file mode 100755 index 0000000..b000146 --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Player.h @@ -0,0 +1,22 @@ +// Specification file for the Player class +#ifndef PLAYER_H +#define PLAYER_H +#include +using namespace std; + +class Player +{ +private: + string name; // The player's name + string guess; // The player's guess + int points; // The player's points + +public: + Player(string); // Constructor + void makeGuess(); // Causes player to make a guess + void addPoints(int); // Adds points to the player + string getName(); // Returns the player's name + string getGuess(); // Returns the player's guess + int getPoints(); // Returns the player's points +}; +#endif diff --git a/SourceCode/chapter 14/ChoHan/Pr14-17.cpp b/SourceCode/chapter 14/ChoHan/Pr14-17.cpp new file mode 100755 index 0000000..fd776a3 --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Pr14-17.cpp @@ -0,0 +1,133 @@ +// This program simulates the game of Cho-Han. +#include +#include +#include "Dealer.h" +#include "Player.h" +using namespace std; + +// Function prototypes +void roundResults(Dealer &, Player &, Player &); +void checkGuess(Player &, Dealer &); +void displayGrandWinner(Player, Player); + +int main() +{ + const int MAX_ROUNDS = 5; // Number of rounds + string player1Name; // First player's name + string player2Name; // Second player's name + + // Get the player's names. + cout << "Enter the first player's name: "; + cin >> player1Name; + cout << "Enter the second player's name: "; + cin >> player2Name; + + // Create the dealer. + Dealer dealer; + + // Create the two players. + Player player1(player1Name); + Player player2(player2Name); + + // Play the rounds. + for (int round = 0; round < MAX_ROUNDS; round++) + { + cout << "----------------------------\n"; + cout << "Now playing round " << (round + 1) + << endl; + + // Roll the dice. + dealer.rollDice(); + + // The players make their guesses. + player1.makeGuess(); + player2.makeGuess(); + + // Determine the winner of this round. + roundResults(dealer, player1, player2); + } + + // Display the grand winner. + displayGrandWinner(player1, player2); + return 0; +} + +//*************************************************** +// The roundResults function detremines the results * +// of the current round. * +//*************************************************** +void roundResults(Dealer &dealer, Player &player1, Player &player2) +{ + // Show the dice values. + cout << "The dealer rolled " << dealer.getDie1Value() + << " and " << dealer.getDie2Value() << endl; + + // Show the result (Cho or Han). + cout << "Result: " << dealer.getChoOrHan() << endl; + + // Check each player's guess and award points. + checkGuess(player1, dealer); + checkGuess(player2, dealer); +} + +//*************************************************** +// The checkGuess function checks a player's guess * +// against the dealer's result. * +//*************************************************** +void checkGuess(Player &player, Dealer &dealer) +{ + const int POINTS_TO_ADD = 1; // Points to award winner + + // Get the player's guess + string guess = player.getGuess(); + + // Get the result (Cho or Han). + string choHanResult = dealer.getChoOrHan(); + + // Display the player's guess. + cout << "The player " << player.getName() + << " guessed " << player.getGuess() << endl; + + // Award points if the player guessed correctly. + if (guess == choHanResult) + { + player.addPoints(POINTS_TO_ADD); + cout << "Awarding " << POINTS_TO_ADD + << " point(s) to " << player.getName() + << endl; + } +} + +//*************************************************** +// The displayGrandWinner function displays the * +// game's grand winner. * +//*************************************************** +void displayGrandWinner(Player player1, Player player2) +{ + cout << "----------------------------\n"; + cout << "Game over. Here are the results:\n"; + + // Display player #1's results. + cout << player1.getName() << ": " + << player1.getPoints() << " points\n"; + + // Display player #2's results. + cout << player2.getName() << ": " + << player2.getPoints() << " points\n"; + + // Determine the grand winner. + if (player1.getPoints() > player2.getPoints()) + { + cout << player1.getName() + << " is the grand winner!\n"; + } + else if (player2.getPoints() > player1.getPoints()) + { + cout << player2.getName() + << " is the grand winner!\n"; + } + else + { + cout << "Both players are tied!\n"; + } +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Course.h b/SourceCode/chapter 14/Course.h new file mode 100755 index 0000000..262062b --- /dev/null +++ b/SourceCode/chapter 14/Course.h @@ -0,0 +1,39 @@ +#ifndef COURSE +#define COURSE +#include +#include +#include "Instructor.h" +#include "TextBook.h" +using namespace std; + +class Course +{ +private: + string courseName; // Course name + Instructor instructor; // Instructor + TextBook textbook; // Textbook +public: + // Constructor + Course(string course, string instrLastName, + string instrFirstName, string instrOffice, + string textTitle, string author, + string publisher) + { // Assign the course name. + courseName = course; + + // Assign the instructor. + instructor.set(instrLastName, instrFirstName, instrOffice); + + // Assign the textbook. + textbook.set(textTitle, author, publisher); } + + // print function + void print() const + { cout << "Course name: " << courseName << endl << endl; + cout << "Instructor Information:\n"; + instructor.print(); + cout << "\nTextbook Information:\n"; + textbook.print(); + cout << endl; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 1/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 1/FeetInches.cpp new file mode 100755 index 0000000..8e26d32 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 1/FeetInches.cpp @@ -0,0 +1,55 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 1/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 1/FeetInches.h new file mode 100755 index 0000000..6c6782d --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 1/FeetInches.h @@ -0,0 +1,40 @@ +#ifndef FEETINCHES_H +#define FEETINCHES_H + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 1/Pr14-8.cpp b/SourceCode/chapter 14/FeetInches Version 1/Pr14-8.cpp new file mode 100755 index 0000000..f62bec4 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 1/Pr14-8.cpp @@ -0,0 +1,48 @@ +// This program demonstrates the FeetInches class's overloaded +// + and - operators. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + int feet, inches; // To hold input for feet and inches + + // Create three FeetInches objects. The default arguments + // for the constructor will be used. + FeetInches first, second, third; + + // Get a distance from the user. + cout << "Enter a distance in feet and inches: "; + cin >> feet >> inches; + + // Store the distance in the first object. + first.setFeet(feet); + first.setInches(inches); + + // Get another distance from the user. + cout << "Enter another distance in feet and inches: "; + cin >> feet >> inches; + + // Store the distance in second. + second.setFeet(feet); + second.setInches(inches); + + // Assign first + second to third. + third = first + second; + + // Display the result. + cout << "first + second = "; + cout << third.getFeet() << " feet, "; + cout << third.getInches() << " inches.\n"; + + // Assign first - second to third. + third = first - second; + + // Display the result. + cout << "first - second = "; + cout << third.getFeet() << " feet, "; + cout << third.getInches() << " inches.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 2/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 2/FeetInches.cpp new file mode 100755 index 0000000..2b54e39 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 2/FeetInches.cpp @@ -0,0 +1,83 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator++() +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator++(int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 2/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 2/FeetInches.h new file mode 100755 index 0000000..4190eb5 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 2/FeetInches.h @@ -0,0 +1,42 @@ +#ifndef FEETINCHES_H +#define FEETINCHES_H + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 2/Pr14-9.cpp b/SourceCode/chapter 14/FeetInches Version 2/Pr14-9.cpp new file mode 100755 index 0000000..c6787fb --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 2/Pr14-9.cpp @@ -0,0 +1,41 @@ +// This program demonstrates the FeetInches class' overloaded +// prefix and postfix ++ operators. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + int count; // Loop counter + + // Define a FeetInches object with the default + // value of 0 feet, 0 inches. + FeetInches first; + + // Define a FeetInches object with 1 foot 5 inches. + FeetInches second(1, 5); + + // Use the prefix ++ operator. + cout << "Demonstrating prefix ++ operator.\n"; + for (count = 0; count < 12; count++) + { + first = ++second; + cout << "first: " << first.getFeet() << " feet, "; + cout << first.getInches() << " inches. "; + cout << "second: " << second.getFeet() << " feet, "; + cout << second.getInches() << " inches.\n"; + } + + // Use the postfix ++ operator. + cout << "\nDemonstrating postfix ++ operator.\n"; + for (count = 0; count < 12; count++) + { + first = second++; + cout << "first: " << first.getFeet() << " feet, "; + cout << first.getInches() << " inches. "; + cout << "second: " << second.getFeet() << " feet, "; + cout << second.getInches() << " inches.\n"; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 3/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 3/FeetInches.cpp new file mode 100755 index 0000000..7fff308 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 3/FeetInches.cpp @@ -0,0 +1,138 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 3/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 3/FeetInches.h new file mode 100755 index 0000000..9e0e41a --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 3/FeetInches.h @@ -0,0 +1,46 @@ +// Specification file for the FeetInches class +#ifndef FEETINCHES_H +#define FEETINCHES_H + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 3/Pr14-10.cpp b/SourceCode/chapter 14/FeetInches Version 3/Pr14-10.cpp new file mode 100755 index 0000000..a3a3c5c --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 3/Pr14-10.cpp @@ -0,0 +1,40 @@ +// This program demonstrates the FeetInches class's overloaded +// relational operators. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + int feet, inches; // To hold input for feet and inches + + // Create two FeetInches objects. The default arguments + // for the constructor will be used. + FeetInches first, second; + + // Get a distance from the user. + cout << "Enter a distance in feet and inches: "; + cin >> feet >> inches; + + // Store the distance in first. + first.setFeet(feet); + first.setInches(inches); + + // Get another distance. + cout << "Enter another distance in feet and inches: "; + cin >> feet >> inches; + + // Store the distance in second. + second.setFeet(feet); + second.setInches(inches); + + // Compare the two objects. + if (first == second) + cout << "first is equal to second.\n"; + if (first > second) + cout << "first is greater than second.\n"; + if (first < second) + cout << "first is less than second.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 4/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 4/FeetInches.cpp new file mode 100755 index 0000000..ea33f56 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 4/FeetInches.cpp @@ -0,0 +1,170 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} + +//******************************************************** +// Overloaded << operator. Gives cout the ability to * +// directly display FeetInches objects. * +//******************************************************** + +ostream &operator<<(ostream &strm, const FeetInches &obj) +{ + strm << obj.feet << " feet, " << obj.inches << " inches"; + return strm; +} + +//******************************************************** +// Overloaded >> operator. Gives cin the ability to * +// store user input directly into FeetInches objects. * +//******************************************************** + +istream &operator >> (istream &strm, FeetInches &obj) +{ + // Prompt the user for the feet. + cout << "Feet: "; + strm >> obj.feet; + + // Prompt the user for the inches. + cout << "Inches: "; + strm >> obj.inches; + + // Normalize the values. + obj.simplify(); + + return strm; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 4/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 4/FeetInches.h new file mode 100755 index 0000000..8c43f5f --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 4/FeetInches.h @@ -0,0 +1,58 @@ +#ifndef FEETINCHES_H +#define FEETINCHES_H + +#include +using namespace std; + +class FeetInches; // Forward Declaration + +// Function Prototypes for Overloaded Stream Operators +ostream &operator << (ostream &, const FeetInches &); +istream &operator >> (istream &, FeetInches &); + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == + + // Friends + friend ostream &operator << (ostream &, const FeetInches &); + friend istream &operator >> (istream &, FeetInches &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 4/Pr14-11.cpp b/SourceCode/chapter 14/FeetInches Version 4/Pr14-11.cpp new file mode 100755 index 0000000..e8a32bd --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 4/Pr14-11.cpp @@ -0,0 +1,23 @@ +// This program demonstrates the << and >> operators, +// overloaded to work with the FeetInches class. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + FeetInches first, second; // Define two objects. + + // Get a distance for the first object. + cout << "Enter a distance in feet and inches.\n"; + cin >> first; + + // Get a distance for the second object. + cout << "Enter another distance in feet and inches.\n"; + cin >> second; + + // Display the values in the objects. + cout << "The values you entered are:\n"; + cout << first << " and " << second << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 5/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 5/FeetInches.cpp new file mode 100755 index 0000000..d47f51e --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 5/FeetInches.cpp @@ -0,0 +1,193 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} + +//******************************************************** +// Overloaded << operator. Gives cout the ability to * +// directly display FeetInches objects. * +//******************************************************** + +ostream &operator<<(ostream &strm, const FeetInches &obj) +{ + strm << obj.feet << " feet, " << obj.inches << " inches"; + return strm; +} + +//******************************************************** +// Overloaded >> operator. Gives cin the ability to * +// store user input directly into FeetInches objects. * +//******************************************************** + +istream &operator >> (istream &strm, FeetInches &obj) +{ + // Prompt the user for the feet. + cout << "Feet: "; + strm >> obj.feet; + + // Prompt the user for the inches. + cout << "Inches: "; + strm >> obj.inches; + + // Normalize the values. + obj.simplify(); + + return strm; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to a double. * +//************************************************************* + +FeetInches::operator double() +{ + double temp = feet; + + temp += (inches / 12.0); + return temp; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to an int. * +//************************************************************* + +FeetInches:: operator int() +{ + return feet; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 5/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 5/FeetInches.h new file mode 100755 index 0000000..9c92f58 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 5/FeetInches.h @@ -0,0 +1,63 @@ +// Specification file for the FeetInches class +#ifndef FEETINCHES_H +#define FEETINCHES_H + +#include +using namespace std; + +class FeetInches; // Forward Declaration + +// Function Prototypes for Overloaded Stream Operators +ostream &operator << (ostream &, const FeetInches &); +istream &operator >> (istream &, FeetInches &); + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == + + // Conversion functions + operator double(); + operator int(); + + // Friends + friend ostream &operator << (ostream &, const FeetInches &); + friend istream &operator >> (istream &, FeetInches &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 5/Pr14-14.cpp b/SourceCode/chapter 14/FeetInches Version 5/Pr14-14.cpp new file mode 100755 index 0000000..c6d6a3c --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 5/Pr14-14.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the the FeetInches class's +// conversion functions. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + double d; // To hold double input + int i; // To hold int input + + // Define a FeetInches object. + FeetInches distance; + + // Get a distance from the user. + cout << "Enter a distance in feet and inches:\n"; + cin >> distance; + + // Convert the distance object to a double. + d = distance; + + // Convert the distance object to an int. + i = distance; + + // Display the values. + cout << "The value " << distance; + cout << " is equivalent to " << d << " feet\n"; + cout << "or " << i << " feet, rounded down.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Instructor.h b/SourceCode/chapter 14/Instructor.h new file mode 100755 index 0000000..59846b6 --- /dev/null +++ b/SourceCode/chapter 14/Instructor.h @@ -0,0 +1,36 @@ +#ifndef INSTRUCTOR +#define INSTRUCTOR +#include +#include +using namespace std; + +// Instructor class +class Instructor +{ +private: + string lastName; // Last name + string firstName; // First name + string officeNumber; // Office number +public: + // The default constructor stores empty strings + // in the string objects. + Instructor() + { set("", "", ""); } + + // Constructor + Instructor(string lname, string fname, string office) + { set(lname, fname, office); } + + // set function + void set(string lname, string fname, string office) + { lastName = lname; + firstName = fname; + officeNumber = office; } + + // print function + void print() const + { cout << "Last name: " << lastName << endl; + cout << "First name: " << firstName << endl; + cout << "Office number: " << officeNumber << endl; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/IntArray.cpp b/SourceCode/chapter 14/IntArray.cpp new file mode 100755 index 0000000..3729109 --- /dev/null +++ b/SourceCode/chapter 14/IntArray.cpp @@ -0,0 +1,64 @@ +// Implementation file for the IntArray class +#include +#include // For the exit function +#include "IntArray.h" +using namespace std; + +//******************************************************* +// Constructor for IntArray class. Sets the size of the * +// array and allocates memory for it. * +//******************************************************* + +IntArray::IntArray(int s) +{ + arraySize = s; + aptr = new int [s]; + for (int count = 0; count < arraySize; count++) + *(aptr + count) = 0; +} + +//****************************************************** +// Copy Constructor for IntArray class. * +//****************************************************** + +IntArray::IntArray(const IntArray &obj) +{ + arraySize = obj.arraySize; + aptr = new int [arraySize]; + for(int count = 0; count < arraySize; count++) + *(aptr + count) = *(obj.aptr + count); +} + +//****************************************************** +// Destructor for IntArray class. * +//****************************************************** + +IntArray::~IntArray() +{ + if (arraySize > 0) + delete [] aptr; +} + +//*********************************************************** +// subscriptError function. Displays an error message and * +// terminates the program when a subscript is out of range. * +//*********************************************************** + +void IntArray::subscriptError() +{ + cout << "ERROR: Subscript out of range.\n"; + exit(0); +} + +//******************************************************* +// Overloaded [] operator. The argument is a subscript. * +// This function returns a reference to the element * +// in the array indexed by the subscript. * +//******************************************************* + +int &IntArray::operator[](const int &sub) +{ + if (sub < 0 || sub >= arraySize) + subscriptError(); + return aptr[sub]; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/IntArray.h b/SourceCode/chapter 14/IntArray.h new file mode 100755 index 0000000..bd1c7bc --- /dev/null +++ b/SourceCode/chapter 14/IntArray.h @@ -0,0 +1,21 @@ +// Specification file for the IntArray class +#ifndef INTARRAY_H +#define INTARRAY_H + +class IntArray +{ +private: + int *aptr; // Pointer to the array + int arraySize; // Holds the array size + void subscriptError(); // Handles invalid subscripts +public: + IntArray(int); // Constructor + IntArray(const IntArray &); // Copy constructor + ~IntArray(); // Destructor + + int size() const // Returns the array size + { return arraySize; } + + int &operator[](const int &); // Overloaded [] operator +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-1.cpp b/SourceCode/chapter 14/Pr14-1.cpp new file mode 100755 index 0000000..84298b2 --- /dev/null +++ b/SourceCode/chapter 14/Pr14-1.cpp @@ -0,0 +1,17 @@ +// This program demonstrates a static member variable. +#include +#include "Tree.h" +using namespace std; + +int main() +{ + // Define three Tree objects. + Tree oak; + Tree elm; + Tree pine; + + // Display the number of Tree objects we have. + cout << "We have " << pine.getObjectCount() + << " trees in our program!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-12.cpp b/SourceCode/chapter 14/Pr14-12.cpp new file mode 100755 index 0000000..43e6f5f --- /dev/null +++ b/SourceCode/chapter 14/Pr14-12.cpp @@ -0,0 +1,41 @@ +// This program demonstrates an overloaded [] operator. +#include +#include "IntArray.h" +using namespace std; + +int main() +{ + const int SIZE = 10; // Array size + + // Define an IntArray with 10 elements. + IntArray table(SIZE); + + // Store values in the array. + for (int x = 0; x < SIZE; x++) + table[x] = (x * 2); + + // Display the values in the array. + for (x = 0; x < SIZE; x++) + cout << table[x] << " "; + cout << endl; + + // Use the standard + operator on array elements. + for (x = 0; x < SIZE; x++) + table[x] = table[x] + 5; + + // Display the values in the array. + for (x = 0; x < SIZE; x++) + cout << table[x] << " "; + cout << endl; + + // Use the standard ++ operator on array elements. + for (x = 0; x < SIZE; x++) + table[x]++; + + // Display the values in the array. + for (x = 0; x < SIZE; x++) + cout << table[x] << " "; + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-13.cpp b/SourceCode/chapter 14/Pr14-13.cpp new file mode 100755 index 0000000..48f59ef --- /dev/null +++ b/SourceCode/chapter 14/Pr14-13.cpp @@ -0,0 +1,26 @@ +// This program demonstrates the IntArray class's bounds-checking ability. +#include +#include "IntArray.h" +using namespace std; + +int main() +{ + const int SIZE = 10; // Array size + + // Define an IntArray with 10 elements. + IntArray table(SIZE); + + // Store values in the array. + for (int x = 0; x < SIZE; x++) + table[x] = x; + + // Display the values in the array. + for (x = 0; x < SIZE; x++) + cout << table[x] << " "; + cout << endl; + + // Attempt to use an invalid subscript... + cout << "Now attempting to use an invalid subscript.\n"; + table[SIZE + 1] = 0; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-15.cpp b/SourceCode/chapter 14/Pr14-15.cpp new file mode 100755 index 0000000..7b57b22 --- /dev/null +++ b/SourceCode/chapter 14/Pr14-15.cpp @@ -0,0 +1,15 @@ +// This program demonstrates the Course class. +#include "Course.h" + +int main() +{ + // Create a Course object. + Course myCourse("Intro to Computer Science", // Course name + "Kramer", "Shawn", "RH3010", // Instructor info + "Starting Out with C++", "Gaddis", // Textbook title and author + "Addison-Wesley"); // Textbook publisher + + // Display the course info. + myCourse.print(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-16.cpp b/SourceCode/chapter 14/Pr14-16.cpp new file mode 100755 index 0000000..728c5c8 --- /dev/null +++ b/SourceCode/chapter 14/Pr14-16.cpp @@ -0,0 +1,36 @@ +// Stock trader program +#include +#include +#include "Stock.h" +#include "StockPurchase.h" +using namespace std; + +int main() +{ + int sharesToBuy; // Number of shares to buy + + // Create a Stock object for the company stock. The + // trading symbol is XYZ and the stock is currently + // priced at $9.62 per share. + Stock xyzCompany("XYZ", 9.62); + + // Display the symbol and current share price. + cout << setprecision(2) << fixed << showpoint; + cout << "XYZ Company's trading symbol is " + << xyzCompany.getSymbol() << endl; + cout << "The stock is currently $" + << xyzCompany.getSharePrice() + << " per share.\n"; + + // Get the number of shares to purchase. + cout << "How many shares do you want to buy? "; + cin >> sharesToBuy; + + // Create a StockPurchase object for the transaction. + StockPurchase buy(xyzCompany, sharesToBuy); + + // Display the cost of the transaction. + cout << "The cost of the transaction is $" + << buy.getCost() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-5.cpp b/SourceCode/chapter 14/Pr14-5.cpp new file mode 100755 index 0000000..17669f5 --- /dev/null +++ b/SourceCode/chapter 14/Pr14-5.cpp @@ -0,0 +1,28 @@ +// This program demonstrates memberwise assignment. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + // Define two Rectangle objects. + Rectangle box1(10.0, 10.0); // width = 10.0, length = 10.0 + Rectangle box2 (20.0, 20.0); // width = 20.0, length = 20.0 + + // Display each object's width and length. + cout << "box1's width and length: " << box1.getWidth() + << " " << box1.getLength() << endl; + cout << "box2's width and length: " << box2.getWidth() + << " " << box2.getLength() << endl << endl; + + // Assign the members of box1 to box2. + box2 = box1; + + // Display each object's width and length again. + cout << "box1's width and length: " << box1.getWidth() + << " " << box1.getLength() << endl; + cout << "box2's width and length: " << box2.getWidth() + << " " << box2.getLength() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Rectangle.cpp b/SourceCode/chapter 14/Rectangle.cpp new file mode 100755 index 0000000..200f8fb --- /dev/null +++ b/SourceCode/chapter 14/Rectangle.cpp @@ -0,0 +1,46 @@ +// Implementation file for the Rectangle class. +// This version has a constructor that accepts arguments. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// The constructor accepts arguments for width and length. * +//*********************************************************** + +Rectangle::Rectangle(double w, double len) +{ + width = w; + length = len; +} + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Rectangle.h b/SourceCode/chapter 14/Rectangle.h new file mode 100755 index 0000000..ac8f474 --- /dev/null +++ b/SourceCode/chapter 14/Rectangle.h @@ -0,0 +1,25 @@ +// Specification file for the Rectangle class +// This version has a constructor. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; + double length; + public: + Rectangle(double, double); // Constructor + void setWidth(double); + void setLength(double); + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StaticDemo.cpp b/SourceCode/chapter 14/StaticDemo.cpp new file mode 100755 index 0000000..0edcd7b --- /dev/null +++ b/SourceCode/chapter 14/StaticDemo.cpp @@ -0,0 +1,50 @@ +#include +using namespace std; + +class StaticDemo +{ +private: + int instanceVariable; // Instance variable + static int staticVariable; // Static variable +public: + void setInstanceVariable(int n) + { instanceVariable = n; } + + void setStaticVariable(int n) + { staticVariable = n; } + + int getInstanceVariable() + { return instanceVariable; } + + int getStaticVariable() + { return staticVariable; } +}; + +int StaticDemo::staticVariable; + +int main() +{ + StaticDemo demo1, demo2; + + // Use demo1 to store values in the instanceVariable + // and staticVariable members. + demo1.setInstanceVariable(1); + demo1.setStaticVariable(5); + + // Use demo2 to store a value in the instanceVariable + // member, but do not store a value in staticVariable. + demo2.setInstanceVariable(100); + + // Display the values in the demo1's member variables. + cout << "demo1's members are " + << demo1.getInstanceVariable() << " and " + << demo1.getStaticVariable() << endl; + + // Display the values in the demo2's member variables, + // including staticVariable. + cout << "demo2's members are " + << demo2.getInstanceVariable() << " and " + << demo2.getStaticVariable() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Stock.h b/SourceCode/chapter 14/Stock.h new file mode 100755 index 0000000..6fd319e --- /dev/null +++ b/SourceCode/chapter 14/Stock.h @@ -0,0 +1,36 @@ +#ifndef STOCK +#define STOCK +#include +using namespace std; + +class Stock +{ +private: + string symbol; // Trading symbol of the stock + double sharePrice; // Current price per share +public: + // Default Constructor + Stock() + { set("", 0.0); } + + // Constructor + Stock(const string sym, double price) + { set(sym, price); } + + // Copy constructor + Stock(const Stock &obj) + { set(obj.symbol, obj.sharePrice); } + + // Mutator function + void set(string sym, double price) + { symbol = sym; + sharePrice = price; } + + // Accessor functions + string getSymbol() const + { return symbol; } + + double getSharePrice() const + { return sharePrice; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StockPurchase.h b/SourceCode/chapter 14/StockPurchase.h new file mode 100755 index 0000000..0a398df --- /dev/null +++ b/SourceCode/chapter 14/StockPurchase.h @@ -0,0 +1,25 @@ +#ifndef STOCK_PURCHASE +#define STOCK_PURCHASE +#include "Stock.h" + +class StockPurchase +{ +private: + Stock stock; // The stock that was purchased + int shares; // The number of shares +public: + // The default constructor sets shares to 0. The stock + // object is initialized by its default constructor. + StockPurchase() + { shares = 0; } + + // Constructor + StockPurchase(const Stock &stockObject, int numShares) + { stock = stockObject; + shares = numShares; } + + // Accessor function + double getCost() const + { return shares * stock.getSharePrice(); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Verison 1/StudentTestScores.h b/SourceCode/chapter 14/StudentTestScores Verison 1/StudentTestScores.h new file mode 100755 index 0000000..6eea4ef --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Verison 1/StudentTestScores.h @@ -0,0 +1,54 @@ +#ifndef STUDENTTESTSCORES_H +#define STUDENTTESTSCORES_H +#include +using namespace std; + +const double DEFAULT_SCORE = 0.0; + +class StudentTestScores +{ +private: + string studentName; // The student's name + double *testScores; // Points to array of test scores + int numTestScores; // Number of test scores + + // Private member function to create an + // array of test scores. + void createTestScoresArray(int size) + { numTestScores = size; + testScores = new double[size]; + for (int i = 0; i < size; i++) + testScores[i] = DEFAULT_SCORE; } + +public: + // Constructor + StudentTestScores(string name, int numScores) + { studentName = name; + createTestScoresArray(numScores); } + + // Destructor + ~StudentTestScores() + { delete [] testScores; } + + // The setTestScore function sets a specific + // test score's value. + void setTestScore(double score, int index) + { testScores[index] = score; } + + // Set the student's name. + void setStudentName(string name) + { studentName = name; } + + // Get the student's name. + string getStudentName() const + { return studentName; } + + // Get the number of test scores. + int getNumTestScores() + { return numTestScores; } + + // Get a specific test score. + double getTestScore(int index) const + { return testScores[index]; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 2/StudentTestScores.h b/SourceCode/chapter 14/StudentTestScores Version 2/StudentTestScores.h new file mode 100755 index 0000000..28a08b4 --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 2/StudentTestScores.h @@ -0,0 +1,62 @@ +#ifndef STUDENTTESTSCORES_H +#define STUDENTTESTSCORES_H +#include +using namespace std; + +const double DEFAULT_SCORE = 0.0; + +class StudentTestScores +{ +private: + string studentName; // The student's name + double *testScores; // Points to array of test scores + int numTestScores; // Number of test scores + + // Private member function to create an + // array of test scores. + void createTestScoresArray(int size) + { numTestScores = size; + testScores = new double[size]; + for (int i = 0; i < size; i++) + testScores[i] = DEFAULT_SCORE; } + +public: + // Constructor + StudentTestScores(string name, int numScores) + { studentName = name; + createTestScoresArray(numScores); } + + // Copy constructor + StudentTestScores(const StudentTestScores &obj) + { studentName = obj.studentName; + numTestScores = obj. numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = obj.testScores[i]; } + + // Destructor + ~StudentTestScores() + { delete [] testScores; } + + // The setTestScore function sets a specific + // test score's value. + void setTestScore(double score, int index) + { testScores[index] = score; } + + // Set the student's name. + void setStudentName(string name) + { studentName = name; } + + // Get the student's name. + string getStudentName() const + { return studentName; } + + // Get the number of test scores. + int getNumTestScores() + { return numTestScores; } + + // Get a specific test score. + double getTestScore(int index) const + { return testScores[index]; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 3/Pr14-6.cpp b/SourceCode/chapter 14/StudentTestScores Version 3/Pr14-6.cpp new file mode 100755 index 0000000..644019e --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 3/Pr14-6.cpp @@ -0,0 +1,41 @@ +// This program demonstrates the overloaded = operator +#include +#include "StudentTestScores.h" +using namespace std; + +// Function prototype +void displayStudent(StudentTestScores); + +int main() +{ + // Create a StudentTestScores object and + // assign test scores. + StudentTestScores student1("Kelly Thorton", 3); + student1.setTestScore(100.0, 0); + student1.setTestScore(95.0, 1); + student1.setTestScore(80, 2); + + // Create another StudentTestScore object + // with default test scores. + StudentTestScores student2("Jimmy Griffin", 5); + + // Assign the student1 object to student2 + student2 = student1; + + // Display both objects. They should + // contain the same data. + displayStudent(student1); + displayStudent(student2); + return 0; +} + +// The displayStudent function accepts a +// StudentTestScores object's data. +void displayStudent(StudentTestScores s) +{ + cout << "Name: " << s.getStudentName() << endl; + cout << "Test Scores: "; + for (int i = 0; i < s.getNumTestScores(); i++) + cout << s.getTestScore(i) << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 3/StudentTestScores.h b/SourceCode/chapter 14/StudentTestScores Version 3/StudentTestScores.h new file mode 100755 index 0000000..083d344 --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 3/StudentTestScores.h @@ -0,0 +1,71 @@ +#ifndef STUDENTTESTSCORES_H +#define STUDENTTESTSCORES_H +#include +using namespace std; + +const double DEFAULT_SCORE = 0.0; + +class StudentTestScores +{ +private: + string studentName; // The student's name + double *testScores; // Points to array of test scores + int numTestScores; // Number of test scores + + // Private member function to create an + // array of test scores. + void createTestScoresArray(int size) + { numTestScores = size; + testScores = new double[size]; + for (int i = 0; i < size; i++) + testScores[i] = DEFAULT_SCORE; } + +public: + // Constructor + StudentTestScores(string name, int numScores) + { studentName = name; + createTestScoresArray(numScores); } + + // Copy constructor + StudentTestScores(const StudentTestScores &obj) + { studentName = obj.studentName; + numTestScores = obj. numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = obj.testScores[i]; } + + // Destructor + ~StudentTestScores() + { delete [] testScores; } + + // The setTestScore function sets a specific + // test score's value. + void setTestScore(double score, int index) + { testScores[index] = score; } + + // Set the student's name. + void setStudentName(string name) + { studentName = name; } + + // Get the student's name. + string getStudentName() const + { return studentName; } + + // Get the number of test scores. + int getNumTestScores() + { return numTestScores; } + + // Get a specific test score. + double getTestScore(int index) const + { return testScores[index]; } + + // Overloaded = operator + void operator=(const StudentTestScores &right) + { delete [] testScores; + studentName = right.studentName; + numTestScores = right.numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = right.testScores[i]; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 4/Pr14-7.cpp b/SourceCode/chapter 14/StudentTestScores Version 4/Pr14-7.cpp new file mode 100755 index 0000000..fd42776 --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 4/Pr14-7.cpp @@ -0,0 +1,39 @@ +// This program demonstrates the overloaded = operator returning a value. +#include +#include "StudentTestScores.h" +using namespace std; + +// Function prototype +void displayStudent(StudentTestScores); + +int main() +{ + // Create a StudentTestScores object. + StudentTestScores student1("Kelly Thorton", 3); + student1.setTestScore(100.0, 0); + student1.setTestScore(95.0, 1); + student1.setTestScore(80, 2); + + // Create two more StudentTestScores objects. + StudentTestScores student2("Jimmy Griffin", 5); + StudentTestScores student3("Kristen Lee", 10); + + // Assign student1 to student2 and student3. + student3 = student2 = student1; + + // Display the objects. + displayStudent(student1); + displayStudent(student2); + displayStudent(student3); + return 0; +} + +// displayStudent function +void displayStudent(StudentTestScores s) +{ + cout << "Name: " << s.getStudentName() << endl; + cout << "Test Scores: "; + for (int i = 0; i < s.getNumTestScores(); i++) + cout << s.getTestScore(i) << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 4/StudentTestScores.h b/SourceCode/chapter 14/StudentTestScores Version 4/StudentTestScores.h new file mode 100755 index 0000000..624a803 --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 4/StudentTestScores.h @@ -0,0 +1,73 @@ +#ifndef STUDENTTESTSCORES_H +#define STUDENTTESTSCORES_H +#include +using namespace std; + +const double DEFAULT_SCORE = 0.0; + +class StudentTestScores +{ +private: + string studentName; // The student's name + double *testScores; // Points to array of test scores + int numTestScores; // Number of test scores + + // Private member function to create an + // array of test scores. + void createTestScoresArray(int size) + { numTestScores = size; + testScores = new double[size]; + for (int i = 0; i < size; i++) + testScores[i] = DEFAULT_SCORE; } + +public: + // Constructor + StudentTestScores(string name, int numScores) + { studentName = name; + createTestScoresArray(numScores); } + + // Copy constructor + StudentTestScores(const StudentTestScores &obj) + { studentName = obj.studentName; + numTestScores = obj. numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = obj.testScores[i]; } + + // Destructor + ~StudentTestScores() + { delete [] testScores; } + + // The setTestScore function sets a specific + // test score's value. + void setTestScore(double score, int index) + { testScores[index] = score; } + + // Set the student's name. + void setStudentName(string name) + { studentName = name; } + + // Get the student's name. + string getStudentName() const + { return studentName; } + + // Get the number of test scores. + int getNumTestScores() + { return numTestScores; } + + // Get a specific test score. + double getTestScore(int index) const + { return testScores[index]; } + + // Overloaded = operator + const StudentTestScores operator=(const StudentTestScores &right) + { delete [] testScores; + studentName = right.studentName; + numTestScores = right.numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = right.testScores[i]; + return *this; } + +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/TextBook.h b/SourceCode/chapter 14/TextBook.h new file mode 100755 index 0000000..852726e --- /dev/null +++ b/SourceCode/chapter 14/TextBook.h @@ -0,0 +1,36 @@ +#ifndef TEXTBOOK +#define TEXTBOOK +#include +#include +using namespace std; + +// TextBook class +class TextBook +{ +private: + string title; // Book title + string author; // Author name + string publisher; // Publisher name +public: + // The default constructor stores empty strings + // in the string objects. + TextBook() + { set("", "", ""); } + + // Constructor + TextBook(string textTitle, string auth, string pub) + { set(textTitle, auth, pub); } + + // set function + void set(string textTitle, string auth, string pub) + { title = textTitle; + author = auth; + publisher = pub; } + + // print function + void print() const + { cout << "Title: " << title << endl; + cout << "Author: " << author << endl; + cout << "Publisher: " << publisher << endl; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Tree.h b/SourceCode/chapter 14/Tree.h new file mode 100755 index 0000000..fbb12e6 --- /dev/null +++ b/SourceCode/chapter 14/Tree.h @@ -0,0 +1,18 @@ +// Tree class +class Tree +{ +private: + static int objectCount; // Static member variable. +public: + // Constructor + Tree() + { objectCount++; } + + // Accessor function for objectCount + int getObjectCount() const + { return objectCount; } +}; + +// Definition of the static member variable, written +// outside the class. +int Tree::objectCount = 0; \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/Automobile.h b/SourceCode/chapter 15/Automobile/Automobile.h new file mode 100755 index 0000000..11fe7ee --- /dev/null +++ b/SourceCode/chapter 15/Automobile/Automobile.h @@ -0,0 +1,45 @@ +#ifndef AUTOMOBILE_H +#define AUTOMOBILE_H +#include +using namespace std; + +// The Automobile class holds general data +// about an automobile in inventory. +class Automobile +{ +private: + string make; // The auto's make + int model; // The auto's year model + int mileage; // The auto's mileage + double price; // The auto's price + +public: + // Default constructor + Automobile() + { make = ""; + model = 0; + mileage = 0; + price = 0.0; } + + // Constructor + Automobile(string autoMake, int autoModel, + int autoMileage, double autoPrice) + { make = autoMake; + model = autoModel; + mileage = autoMileage; + price = autoPrice; } + + // Accessors + string getMake() const + { return make; } + + int getModel() const + { return model; } + + int getMileage() const + { return mileage; } + + double getPrice() const + { return price; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/Car.h b/SourceCode/chapter 15/Automobile/Car.h new file mode 100755 index 0000000..95ea88c --- /dev/null +++ b/SourceCode/chapter 15/Automobile/Car.h @@ -0,0 +1,28 @@ +#ifndef CAR_H +#define CAR_H +#include "Automobile.h" +#include +using namespace std; + +// The Car class represents a car. +class Car : public Automobile +{ +private: + int doors; + +public: + // Default constructor + Car() : Automobile() + { doors = 0; } + + // Constructor #2 + Car(string carMake, int carModel, int carMileage, + double carPrice, int carDoors) : + Automobile(carMake, carModel, carMileage, carPrice) + { doors = carDoors; } + + // Accessor for doors attribute + int getDoors() + { return doors; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/Pr15-6.cpp b/SourceCode/chapter 15/Automobile/Pr15-6.cpp new file mode 100755 index 0000000..6ae371b --- /dev/null +++ b/SourceCode/chapter 15/Automobile/Pr15-6.cpp @@ -0,0 +1,48 @@ +// This program demonstrates the Car, Truck, and SUV +// classes that are derived from the Automobile class. +#include +#include +#include "Car.h" +#include "Truck.h" +#include "SUV.h" +using namespace std; + +int main() +{ + // Create a Car object for a used 2007 BMW with + // 50,000 miles, priced at $15,000, with 4 doors. + Car car("BMW", 2007, 50000, 15000.0, 4); + + // Create a Truck object for a used 2006 Toyota + // pickup with 40,000 miles, priced at $12,000, + // with 4-wheel drive. + Truck truck("Toyota", 2006, 40000, 12000.0, "4WD"); + + // Create an SUV object for a used 2005 Volvo + // with 30,000 miles, priced at $18,000, with + // 5 passenger capacity. + SUV suv("Volvo", 2005, 30000, 18000.00, 5); + + // Display the automobiles we have in inventory. + cout << fixed << showpoint << setprecision(2); + cout << "We have the following car in inventory:\n" + << car.getModel() << " " << car.getMake() + << " with " << car.getDoors() << " doors and " + << car.getMileage() << " miles.\nPrice: $" + << car.getPrice() << endl << endl; + + cout << "We have the following truck in inventory:\n" + << truck.getModel() << " " << truck.getMake() + << " with " << truck.getDriveType() + << " drive type and " << truck.getMileage() + << " miles.\nPrice: $" << truck.getPrice() + << endl << endl; + + cout << "We have the following SUV in inventory:\n" + << suv.getModel() << " " << suv.getMake() + << " with " << suv.getMileage() << " miles and " + << suv.getPassengers() << " passenger capacity.\n" + << "Price: $" << suv.getPrice() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/SUV.h b/SourceCode/chapter 15/Automobile/SUV.h new file mode 100755 index 0000000..76959ca --- /dev/null +++ b/SourceCode/chapter 15/Automobile/SUV.h @@ -0,0 +1,28 @@ +#ifndef SUV_H +#define SUV_H +#include "Automobile.h" +#include +using namespace std; + +// The SUV class represents a SUV. +class SUV : public Automobile +{ +private: + int passengers; + +public: + // Default constructor + SUV() : Automobile() + { passengers = 0; } + + // Constructor #2 + SUV(string SUVMake, int SUVModel, int SUVMileage, + double SUVPrice, int SUVpassengers) : + Automobile(SUVMake, SUVModel, SUVMileage, SUVPrice) + { passengers = SUVpassengers; } + + // Accessor for passengers attribute + int getPassengers() + { return passengers; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/Truck.h b/SourceCode/chapter 15/Automobile/Truck.h new file mode 100755 index 0000000..0df9ea3 --- /dev/null +++ b/SourceCode/chapter 15/Automobile/Truck.h @@ -0,0 +1,28 @@ +#ifndef TRUCK_H +#define TRUCK_H +#include "Automobile.h" +#include +using namespace std; + +// The Truck class represents a truck. +class Truck : public Automobile +{ +private: + string driveType; + +public: + // Default constructor + Truck() : Automobile() + { driveType = ""; } + + // Constructor #2 + Truck(string truckMake, int truckModel, int truckMileage, + double truckPrice, string truckDriveType) : + Automobile(truckMake, truckModel, truckMileage, truckPrice) + { driveType = truckDriveType; } + + // Accessor for driveType attribute + string getDriveType() + { return driveType; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/CsStudent.cpp b/SourceCode/chapter 15/CsStudent.cpp new file mode 100755 index 0000000..40cf067 --- /dev/null +++ b/SourceCode/chapter 15/CsStudent.cpp @@ -0,0 +1,24 @@ +#include +#include "CsStudent.h" +using namespace std; + +//**************************************************** +// The CsStudent::getRemainingHours function returns * +// the number of hours remaining to be taken. * +//**************************************************** + +int CsStudent::getRemainingHours() const +{ + int reqHours, // Total required hours + remainingHours; // Remaining hours + + // Calculate the required hours. + reqHours = MATH_HOURS + CS_HOURS + GEN_ED_HOURS; + + // Calculate the remaining hours. + remainingHours = reqHours - (mathHours + csHours + + genEdHours); + + // Return the remaining hours. + return remainingHours; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/CsStudent.h b/SourceCode/chapter 15/CsStudent.h new file mode 100755 index 0000000..c9168fe --- /dev/null +++ b/SourceCode/chapter 15/CsStudent.h @@ -0,0 +1,46 @@ +// Specification file for the CsStudent class +#ifndef CSSTUDENT_H +#define CSSTUDENT_H +#include "Student.h" + +// Constants for required hours +const int MATH_HOURS = 20; // Math hours +const int CS_HOURS = 40; // Computer science hours +const int GEN_ED_HOURS = 60; // General Ed hours + +class CsStudent : public Student +{ +private: + int mathHours; // Hours of math taken + int csHours; // Hours of Computer Science taken + int genEdHours; // Hours of general education taken + +public: + // Default Constructor + CsStudent() : Student() + { mathHours = 0; + csHours = 0; + genEdHours = 0; } + + // Constructor + CsStudent(string n, string id, int year) : + Student(n, id, year) + { mathHours = 0; + csHours = 0; + genEdHours = 0; } + + // Mutator functions + void setMathHours(int mh) + { mathHours = mh; } + + void setCsHours(int csh) + { csHours = csh; } + + void setGenEdHours(int geh) + { genEdHours = geh; } + + // Overridden getRemainingHours function, + // defined in CsStudent.cpp + virtual int getRemainingHours() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Cube.h b/SourceCode/chapter 15/Cube.h new file mode 100755 index 0000000..b38fe66 --- /dev/null +++ b/SourceCode/chapter 15/Cube.h @@ -0,0 +1,26 @@ +#ifndef CUBE_H +#define CUBE_H +#include "Rectangle.h" + +class Cube : public Rectangle +{ +protected: + double height; + double volume; +public: + // Default constructor + Cube() : Rectangle() + { height = 0.0; volume = 0.0; } + + // Constructor #2 + Cube(double w, double len, double h) : Rectangle(w, len) + { height = h; + volume = getArea() * h; } + + double getHeight() const + { return height; } + + double getVolume() const + { return volume; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/CurvedActivity/CurvedActivity.h b/SourceCode/chapter 15/CurvedActivity/CurvedActivity.h new file mode 100755 index 0000000..e244d7e --- /dev/null +++ b/SourceCode/chapter 15/CurvedActivity/CurvedActivity.h @@ -0,0 +1,30 @@ +#ifndef CURVEDACTIVITY_H +#define CURVEDACTIVITY_H +#include "GradedActivity.h" + +class CurvedActivity : public GradedActivity +{ +protected: + double rawScore; // Unadjusted score + double percentage; // Curve percentage +public: + // Default constructor + CurvedActivity() : GradedActivity() + { rawScore = 0.0; percentage = 0.0; } + + // Mutator functions + void setScore(double s) + { rawScore = s; + GradedActivity::setScore(rawScore * percentage); } + + void setPercentage(double c) + { percentage = c; } + + // Accessor funtions + double getPercentage() const + { return percentage; } + + double getRawScore() const + { return rawScore; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/CurvedActivity/GradedActivity.cpp b/SourceCode/chapter 15/CurvedActivity/GradedActivity.cpp new file mode 100755 index 0000000..c0d9d57 --- /dev/null +++ b/SourceCode/chapter 15/CurvedActivity/GradedActivity.cpp @@ -0,0 +1,20 @@ +// Implementation file for the GradedActivity class +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::determineGrade * +//****************************************************** + +void GradedActivity::determineGrade() +{ + if (score > 89) + letter = 'A'; + else if (score > 79) + letter = 'B'; + else if (score > 69) + letter = 'C'; + else if (score > 59) + letter = 'D'; + else + letter = 'F'; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/CurvedActivity/GradedActivity.h b/SourceCode/chapter 15/CurvedActivity/GradedActivity.h new file mode 100755 index 0000000..985c06a --- /dev/null +++ b/SourceCode/chapter 15/CurvedActivity/GradedActivity.h @@ -0,0 +1,31 @@ +// Specification file for the GradedActivity class +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +protected: + char letter; // To hold the letter grade + double score; // To hold the numeric score + void determineGrade(); // Determines the letter grade +public: + // Default constructor + GradedActivity() + { letter = ' '; score = 0.0; } + + // Mutator function + void setScore(double s) + { score = s; + determineGrade();} + + // Accessor functions + double getScore() const + { return score; } + + char getLetterGrade() const + { return letter; } +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/CurvedActivity/Pr15-7.cpp b/SourceCode/chapter 15/CurvedActivity/Pr15-7.cpp new file mode 100755 index 0000000..9ac7ff3 --- /dev/null +++ b/SourceCode/chapter 15/CurvedActivity/Pr15-7.cpp @@ -0,0 +1,38 @@ +// This program demonstrates a class that redefines +// a base class function. +#include +#include +#include "CurvedActivity.h" +using namespace std; + +int main() +{ + double numericScore; // To hold the numeric score + double percentage; // To hold curve percentage + + // Define a CurvedActivity object. + CurvedActivity exam; + + // Get the unadjusted score. + cout << "Enter the student's raw numeric score: "; + cin >> numericScore; + + // Get the curve percentage. + cout << "Enter the curve percentage for this student: "; + cin >> percentage; + + // Send the values to the exam object. + exam.setPercentage(percentage); + exam.setScore(numericScore); + + // Display the grade data. + cout << fixed << setprecision(2); + cout << "The raw score is " + << exam.getRawScore() << endl; + cout << "The curved score is " + << exam.getScore() << endl; + cout << "The curved grade is " + << exam.getLetterGrade() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Date.h b/SourceCode/chapter 15/Date.h new file mode 100755 index 0000000..6cfb6cb --- /dev/null +++ b/SourceCode/chapter 15/Date.h @@ -0,0 +1,30 @@ +// Specification file for the Date class +#ifndef DATE_H +#define DATE_H + +class Date +{ +protected: + int day; + int month; + int year; +public: + // Default constructor + Date() + { day = 1; month = 1; year = 1900; } + + // Constructor + Date(int d, int m, int y) + { day = d; month = m; year = y; } + + // Accessors + int getDay() const + { return day; } + + int getMonth() const + { return month; } + + int getYear() const + { return year; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/DateTime.cpp b/SourceCode/chapter 15/DateTime.cpp new file mode 100755 index 0000000..10fa86b --- /dev/null +++ b/SourceCode/chapter 15/DateTime.cpp @@ -0,0 +1,35 @@ +// Implementation file for the DateTime class +#include +#include +#include "DateTime.h" +using namespace std; + +//************************************************ +// Default constructor * +// Note that this constructor does nothing other * +// than call default base class constructors. * +//************************************************ +DateTime::DateTime() : Date(), Time() +{ } + +//************************************************ +// Constructor * +// Note that this constructor does nothing other * +// than call base class constructors. * +//************************************************ +DateTime::DateTime(int dy, int mon, int yr, int hr, int mt, int sc) : + Date(dy, mon, yr), Time(hr, mt, sc) +{ } + +//************************************************ +// The showDateTime member function displays the * +// date and the time. * +//************************************************ +void DateTime::showDateTime() const +{ + // Display the date in the form MM/DD/YYYY. + cout << getMonth() << "/" << getDay() << "/" << getYear() << " "; + + // Display the time in the form HH:MM:SS. + cout << getHour() << ":" << getMin() << ":" << getSec() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/DateTime.h b/SourceCode/chapter 15/DateTime.h new file mode 100755 index 0000000..279e241 --- /dev/null +++ b/SourceCode/chapter 15/DateTime.h @@ -0,0 +1,22 @@ +// Specification file for the DateTime class +#ifndef DATETIME_H +#define DATETIME_H +#include +#include "Date.h" +#include "Time.h" +using namespace std; + +class DateTime : public Date, public Time +{ +public: + // Default constructor + DateTime(); + + // Constructor + DateTime(int, int, int, int, int, int); + + // The showDateTime function displays the + // date and the time. + void showDateTime() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.cpp b/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.cpp new file mode 100755 index 0000000..44a69d5 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.cpp @@ -0,0 +1,26 @@ +#include "FinalExam.h" + +//******************************************************** +// set function * +// The parameters are the number of questions and the * +// number of questions missed. * +//******************************************************** + +void FinalExam::set(int questions, int missed) +{ + double numericScore; // To hold the numeric score + + // Set the number of questions and number missed. + numQuestions = questions; + numMissed = missed; + + // Calculate the points for each question. + pointsEach = 100.0 / numQuestions; + + // Calculate the numeric score for this exam. + numericScore = 100.0 - (missed * pointsEach); + + // Call the inherited setScore function to set + // the numeric score. + setScore(numericScore); +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.h b/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.h new file mode 100755 index 0000000..db1fe72 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.h @@ -0,0 +1,35 @@ +#ifndef FINALEXAM_H +#define FINALEXAM_H +#include "GradedActivity.h" + +class FinalExam : public GradedActivity +{ +private: + int numQuestions; // Number of questions + double pointsEach; // Points for each question + int numMissed; // Number of questions missed +public: + // Default constructor + FinalExam() + { numQuestions = 0; + pointsEach = 0.0; + numMissed = 0; } + + // Constructor + FinalExam(int questions, int missed) + { set(questions, missed); } + + // Mutator function + void set(int, int); // Defined in FinalExam.cpp + + // Accessor functions + double getNumQuestions() const + { return numQuestions; } + + double getPointsEach() const + { return pointsEach; } + + int getNumMissed() const + { return numMissed; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.cpp b/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.cpp new file mode 100755 index 0000000..ce6216e --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.cpp @@ -0,0 +1,23 @@ +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::getLetterGrade * +//****************************************************** + +char GradedActivity::getLetterGrade() const +{ + char letterGrade; // To hold the letter grade + + if (score > 89) + letterGrade = 'A'; + else if (score > 79) + letterGrade = 'B'; + else if (score > 69) + letterGrade = 'C'; + else if (score > 59) + letterGrade = 'D'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.h b/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.h new file mode 100755 index 0000000..b214f73 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.h @@ -0,0 +1,29 @@ +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +private: + double score; // To hold the numeric score +public: + // Default constructor + GradedActivity() + { score = 0.0; } + + // Constructor + GradedActivity(double s) + { score = s; } + + // Mutator function + void setScore(double s) + { score = s; } + + // Accessor functions + double getScore() const + { return score; } + + char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/Pr15-1.cpp b/SourceCode/chapter 15/GradedActivity Version 1/Pr15-1.cpp new file mode 100755 index 0000000..9bee58a --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/Pr15-1.cpp @@ -0,0 +1,25 @@ +// This program demonstrates the GradedActivity class. +#include +#include "GradedActivity.h" +using namespace std; + +int main() +{ + double testScore; // To hold a test score + + // Create a GradedActivity object for the test. + GradedActivity test; + + // Get a numeric test score from the user. + cout << "Enter your numeric test score: "; + cin >> testScore; + + // Store the numeric score in the test object. + test.setScore(testScore); + + // Display the letter grade for the test. + cout << "The grade for that test is " + << test.getLetterGrade() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/Pr15-2.cpp b/SourceCode/chapter 15/GradedActivity Version 1/Pr15-2.cpp new file mode 100755 index 0000000..792d1fe --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/Pr15-2.cpp @@ -0,0 +1,32 @@ +// This program demonstrates a base class and a derived class. +#include +#include +#include "FinalExam.h" +using namespace std; + +int main() +{ + int questions; // Number of questions on the exam + int missed; // Number of questions missed by the student + + // Get the number of questions on the final exam. + cout << "How many questions are on the final exam? "; + cin >> questions; + + // Get the number of questions the student missed. + cout << "How many questions did the student miss? "; + cin >> missed; + + // Define a FinalExam object and initialize it with + // the values entered. + FinalExam test(questions, missed); + + // Display the test results. + cout << setprecision(2); + cout << "\nEach question counts " << test.getPointsEach() + << " points.\n"; + cout << "The exam score is " << test.getScore() << endl; + cout << "The exam grade is " << test.getLetterGrade() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.cpp b/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.cpp new file mode 100755 index 0000000..7970daf --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.cpp @@ -0,0 +1,47 @@ +#include "FinalExam.h" + +//******************************************************** +// set function * +// The parameters are the number of questions and the * +// number of questions missed. * +//******************************************************** + +void FinalExam::set(int questions, int missed) +{ + double numericScore; // To hold the numeric score + + // Set the number of questions and number missed. + numQuestions = questions; + numMissed = missed; + + // Calculate the points for each question. + pointsEach = 100.0 / numQuestions; + + // Calculate the numeric score for this exam. + numericScore = 100.0 - (missed * pointsEach); + + // Call the inherited setScore function to set + // the numeric score. + setScore(numericScore); + + // Call the adjustScore function to adjust + // the score. + adjustScore(); +} + +//***************************************************************** +// Definition of Test::adjustScore. If score is within 0.5 points * +// of the next whole point, it rounds the score up and * +// recalculates the letter grade. * +//***************************************************************** + +void FinalExam::adjustScore() +{ + double fraction = score - static_cast(score); + + if (fraction >= 0.5) + { + // Adjust the score variable in the GradedActivity class. + score += (1.0 - fraction); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.h b/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.h new file mode 100755 index 0000000..370ef7b --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.h @@ -0,0 +1,36 @@ +#ifndef FINALEXAM_H +#define FINALEXAM_H +#include "GradedActivity.h" + +class FinalExam : public GradedActivity +{ +private: + int numQuestions; // Number of questions + double pointsEach; // Points for each question + int numMissed; // Number of questions missed +public: + // Default constructor + FinalExam() + { numQuestions = 0; + pointsEach = 0.0; + numMissed = 0; } + + // Constructor + FinalExam(int questions, int missed) + { set(questions, missed); } + + // Mutator functions + void set(int, int); // Defined in FinalExam.cpp + void adjustScore(); // Defined in FinalExam.cpp + + // Accessor functions + double getNumQuestions() const + { return numQuestions; } + + double getPointsEach() const + { return pointsEach; } + + int getNumMissed() const + { return numMissed; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.cpp b/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.cpp new file mode 100755 index 0000000..ce6216e --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.cpp @@ -0,0 +1,23 @@ +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::getLetterGrade * +//****************************************************** + +char GradedActivity::getLetterGrade() const +{ + char letterGrade; // To hold the letter grade + + if (score > 89) + letterGrade = 'A'; + else if (score > 79) + letterGrade = 'B'; + else if (score > 69) + letterGrade = 'C'; + else if (score > 59) + letterGrade = 'D'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.h b/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.h new file mode 100755 index 0000000..9233cf8 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.h @@ -0,0 +1,29 @@ +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +protected: + double score; // To hold the numeric score +public: + // Default constructor + GradedActivity() + { score = 0.0; } + + // Constructor + GradedActivity(double s) + { score = s; } + + // Mutator function + void setScore(double s) + { score = s; } + + // Accessor functions + double getScore() const + { return score; } + + char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/Pr15-3.cpp b/SourceCode/chapter 15/GradedActivity Version 2/Pr15-3.cpp new file mode 100755 index 0000000..11dc1ad --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/Pr15-3.cpp @@ -0,0 +1,35 @@ +// This program demonstrates a base class with a +// protected member. +#include +#include +#include "FinalExam.h" +using namespace std; + +int main() +{ + int questions; // Number of questions on the exam + int missed; // Number of questions missed by the student + + // Get the number of questions on the final exam. + cout << "How many questions are on the final exam? "; + cin >> questions; + + // Get the number of questions the student missed. + cout << "How many questions did the student miss? "; + cin >> missed; + + // Define a FinalExam object and initialize it with + // the values entered. + FinalExam test(questions, missed); + + // Display the adjusted test results. + cout << setprecision(2) << fixed; + cout << "\nEach question counts " + << test.getPointsEach() << " points.\n"; + cout << "The adjusted exam score is " + << test.getScore() << endl; + cout << "The exam grade is " + << test.getLetterGrade() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.cpp b/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.cpp new file mode 100755 index 0000000..ce6216e --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.cpp @@ -0,0 +1,23 @@ +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::getLetterGrade * +//****************************************************** + +char GradedActivity::getLetterGrade() const +{ + char letterGrade; // To hold the letter grade + + if (score > 89) + letterGrade = 'A'; + else if (score > 79) + letterGrade = 'B'; + else if (score > 69) + letterGrade = 'C'; + else if (score > 59) + letterGrade = 'D'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.h b/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.h new file mode 100755 index 0000000..8aef331 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.h @@ -0,0 +1,29 @@ +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +protected: + double score; // To hold the numeric score +public: + // Default constructor + GradedActivity() + { score = 0.0; } + + // Constructor + GradedActivity(double s) + { score = s; } + + // Mutator function + void setScore(double s) + { score = s; } + + // Accessor functions + double getScore() const + { return score; } + + virtual char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.cpp b/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.cpp new file mode 100755 index 0000000..30b26b1 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.cpp @@ -0,0 +1,19 @@ +#include "PassFailActivity.h" + +//****************************************************** +// Member function PassFailActivity::getLetterGrade * +// This function returns 'P' if the score is passing, * +// otherwise it returns 'F'. * +//****************************************************** + +char PassFailActivity::getLetterGrade() const +{ + char letterGrade; + + if (score >= minPassingScore) + letterGrade = 'P'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.h b/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.h new file mode 100755 index 0000000..a0e5822 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.h @@ -0,0 +1,28 @@ +#ifndef PASSFAILACTIVITY_H +#define PASSFAILACTIVITY_H +#include "GradedActivity.h" + +class PassFailActivity : public GradedActivity +{ +protected: + double minPassingScore; // Minimum passing score. +public: + // Default constructor + PassFailActivity() : GradedActivity() + { minPassingScore = 0.0; } + + // Constructor + PassFailActivity(double mps) : GradedActivity() + { minPassingScore = mps; } + + // Mutator + void setMinPassingScore(double mps) + { minPassingScore = mps; } + + // Accessors + double getMinPassingScore() const + { return minPassingScore; } + + virtual char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.cpp b/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.cpp new file mode 100755 index 0000000..37e6059 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.cpp @@ -0,0 +1,26 @@ +#include "PassFailExam.h" + +//******************************************************** +// set function * +// The parameters are the number of questions and the * +// number of questions missed. * +//******************************************************** + +void PassFailExam::set(int questions, int missed) +{ + double numericScore; // To hold the numeric score + + // Set the number of questions and number missed. + numQuestions = questions; + numMissed = missed; + + // Calculate the points for each question. + pointsEach = 100.0 / numQuestions; + + // Calculate the numeric score for this exam. + numericScore = 100.0 - (missed * pointsEach); + + // Call the inherited setScore function to set + // the numeric score. + setScore(numericScore); +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.h b/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.h new file mode 100755 index 0000000..6cddc78 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.h @@ -0,0 +1,36 @@ +#ifndef PASSFAILEXAM_H +#define PASSFAILEXAM_H +#include "PassFailActivity.h" + +class PassFailExam : public PassFailActivity +{ +private: + int numQuestions; // Number of questions + double pointsEach; // Points for each question + int numMissed; // Number of questions missed +public: + // Default constructor + PassFailExam() : PassFailActivity() + { numQuestions = 0; + pointsEach = 0.0; + numMissed = 0; } + + // Constructor + PassFailExam(int questions, int missed, double mps) : + PassFailActivity(mps) + { set(questions, missed); } + + // Mutator function + void set(int, int); // Defined in PassFailExam.cpp + + // Accessor functions + double getNumQuestions() const + { return numQuestions; } + + double getPointsEach() const + { return pointsEach; } + + int getNumMissed() const + { return numMissed; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/Pr15-11.cpp b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-11.cpp new file mode 100755 index 0000000..a7e2ff5 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-11.cpp @@ -0,0 +1,36 @@ +#include +#include +#include "PassFailActivity.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity &); + +int main() +{ + // Create a PassFailActivity object. Minimum passing + // score is 70. + PassFailActivity test(70); + + // Set the score to 72. + test.setScore(72); + + // Display the object's grade data. The letter grade + // should be 'P'. What will be displayed? + displayGrade(test); + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. * +//*************************************************************** + +void displayGrade(const GradedActivity &activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity.getScore() << endl; + cout << "The activity's letter grade is " + << activity.getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/Pr15-12.cpp b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-12.cpp new file mode 100755 index 0000000..3e4d539 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-12.cpp @@ -0,0 +1,39 @@ +#include +#include +#include "PassFailExam.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity &); + +int main() +{ + // Create a GradedActivity object. The score is 88. + GradedActivity test1(88.0); + + // Create a PassFailExam object. There are 100 questions, + // the student missed 25 of them, and the minimum passing + // score is 70. + PassFailExam test2(100, 25, 70.0); + + // Display the grade data for both objects. + cout << "Test 1:\n"; + displayGrade(test1); // GradedActivity object + cout << "\nTest 2:\n"; + displayGrade(test2); // PassFailExam object + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. * +//*************************************************************** + +void displayGrade(const GradedActivity &activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity.getScore() << endl; + cout << "The activity's letter grade is " + << activity.getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/Pr15-13.cpp b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-13.cpp new file mode 100755 index 0000000..8bf77b4 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-13.cpp @@ -0,0 +1,40 @@ +#include +#include +#include "PassFailExam.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity *); + +int main() +{ + // Create a GradedActivity object. The score is 88. + GradedActivity test1(88.0); + + // Create a PassFailExam object. There are 100 questions, + // the student missed 25 of them, and the minimum passing + // score is 70. + PassFailExam test2(100, 25, 70.0); + + // Display the grade data for both objects. + cout << "Test 1:\n"; + displayGrade(&test1); // Address of the GradedActivity object + cout << "\nTest 2:\n"; + displayGrade(&test2); // Address of the PassFailExam object + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. This version of the function * +// uses a GradedActivity pointer as its parameter. * +//*************************************************************** + +void displayGrade(const GradedActivity *activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity->getScore() << endl; + cout << "The activity's letter grade is " + << activity->getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/Pr15-14.cpp b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-14.cpp new file mode 100755 index 0000000..f066711 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-14.cpp @@ -0,0 +1,47 @@ +#include +#include +#include "PassFailExam.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity *); + +int main() +{ + // Constant for the size of an array. + const int NUM_TESTS = 4; + + // tests is an array of GradedActivity pointers. + // Each element of tests is initialized with the + // address of a dynamically allocated object. + GradedActivity *tests[NUM_TESTS] = + { new GradedActivity(88.0), + new PassFailExam(100, 25, 70.0), + new GradedActivity(67.0), + new PassFailExam(50, 12, 60.0) + }; + + // Display the grade data for each element in the array. + for (int count = 0; count < NUM_TESTS; count++) + { + cout << "Test #" << (count + 1) << ":\n"; + displayGrade(tests[count]); + cout << endl; + } + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. This version of the function * +// uses a GradedActivity pointer as its parameter. * +//*************************************************************** + +void displayGrade(const GradedActivity *activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity->getScore() << endl; + cout << "The activity's letter grade is " + << activity->getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/GradedActivity.cpp b/SourceCode/chapter 15/PassFailActivity/GradedActivity.cpp new file mode 100755 index 0000000..ce6216e --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/GradedActivity.cpp @@ -0,0 +1,23 @@ +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::getLetterGrade * +//****************************************************** + +char GradedActivity::getLetterGrade() const +{ + char letterGrade; // To hold the letter grade + + if (score > 89) + letterGrade = 'A'; + else if (score > 79) + letterGrade = 'B'; + else if (score > 69) + letterGrade = 'C'; + else if (score > 59) + letterGrade = 'D'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/GradedActivity.h b/SourceCode/chapter 15/PassFailActivity/GradedActivity.h new file mode 100755 index 0000000..9233cf8 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/GradedActivity.h @@ -0,0 +1,29 @@ +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +protected: + double score; // To hold the numeric score +public: + // Default constructor + GradedActivity() + { score = 0.0; } + + // Constructor + GradedActivity(double s) + { score = s; } + + // Mutator function + void setScore(double s) + { score = s; } + + // Accessor functions + double getScore() const + { return score; } + + char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/PassFailActivity.cpp b/SourceCode/chapter 15/PassFailActivity/PassFailActivity.cpp new file mode 100755 index 0000000..30b26b1 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/PassFailActivity.cpp @@ -0,0 +1,19 @@ +#include "PassFailActivity.h" + +//****************************************************** +// Member function PassFailActivity::getLetterGrade * +// This function returns 'P' if the score is passing, * +// otherwise it returns 'F'. * +//****************************************************** + +char PassFailActivity::getLetterGrade() const +{ + char letterGrade; + + if (score >= minPassingScore) + letterGrade = 'P'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/PassFailActivity.h b/SourceCode/chapter 15/PassFailActivity/PassFailActivity.h new file mode 100755 index 0000000..becadcc --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/PassFailActivity.h @@ -0,0 +1,28 @@ +#ifndef PASSFAILACTIVITY_H +#define PASSFAILACTIVITY_H +#include "GradedActivity.h" + +class PassFailActivity : public GradedActivity +{ +protected: + double minPassingScore; // Minimum passing score. +public: + // Default constructor + PassFailActivity() : GradedActivity() + { minPassingScore = 0.0; } + + // Constructor + PassFailActivity(double mps) : GradedActivity() + { minPassingScore = mps; } + + // Mutator + void setMinPassingScore(double mps) + { minPassingScore = mps; } + + // Accessors + double getMinPassingScore() const + { return minPassingScore; } + + char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/PassFailExam.cpp b/SourceCode/chapter 15/PassFailActivity/PassFailExam.cpp new file mode 100755 index 0000000..37e6059 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/PassFailExam.cpp @@ -0,0 +1,26 @@ +#include "PassFailExam.h" + +//******************************************************** +// set function * +// The parameters are the number of questions and the * +// number of questions missed. * +//******************************************************** + +void PassFailExam::set(int questions, int missed) +{ + double numericScore; // To hold the numeric score + + // Set the number of questions and number missed. + numQuestions = questions; + numMissed = missed; + + // Calculate the points for each question. + pointsEach = 100.0 / numQuestions; + + // Calculate the numeric score for this exam. + numericScore = 100.0 - (missed * pointsEach); + + // Call the inherited setScore function to set + // the numeric score. + setScore(numericScore); +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/PassFailExam.h b/SourceCode/chapter 15/PassFailActivity/PassFailExam.h new file mode 100755 index 0000000..6cddc78 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/PassFailExam.h @@ -0,0 +1,36 @@ +#ifndef PASSFAILEXAM_H +#define PASSFAILEXAM_H +#include "PassFailActivity.h" + +class PassFailExam : public PassFailActivity +{ +private: + int numQuestions; // Number of questions + double pointsEach; // Points for each question + int numMissed; // Number of questions missed +public: + // Default constructor + PassFailExam() : PassFailActivity() + { numQuestions = 0; + pointsEach = 0.0; + numMissed = 0; } + + // Constructor + PassFailExam(int questions, int missed, double mps) : + PassFailActivity(mps) + { set(questions, missed); } + + // Mutator function + void set(int, int); // Defined in PassFailExam.cpp + + // Accessor functions + double getNumQuestions() const + { return numQuestions; } + + double getPointsEach() const + { return pointsEach; } + + int getNumMissed() const + { return numMissed; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/Pr15-10.cpp b/SourceCode/chapter 15/PassFailActivity/Pr15-10.cpp new file mode 100755 index 0000000..a7e2ff5 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/Pr15-10.cpp @@ -0,0 +1,36 @@ +#include +#include +#include "PassFailActivity.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity &); + +int main() +{ + // Create a PassFailActivity object. Minimum passing + // score is 70. + PassFailActivity test(70); + + // Set the score to 72. + test.setScore(72); + + // Display the object's grade data. The letter grade + // should be 'P'. What will be displayed? + displayGrade(test); + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. * +//*************************************************************** + +void displayGrade(const GradedActivity &activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity.getScore() << endl; + cout << "The activity's letter grade is " + << activity.getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/Pr15-9.cpp b/SourceCode/chapter 15/PassFailActivity/Pr15-9.cpp new file mode 100755 index 0000000..273d261 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/Pr15-9.cpp @@ -0,0 +1,39 @@ +// This program demonstrates the PassFailExam class. +#include +#include +#include "PassFailExam.h" +using namespace std; + +int main() +{ + int questions; // Number of questions + int missed; // Number of questions missed + double minPassing; // The minimum passing score + + // Get the number of questions on the exam. + cout << "How many questions are on the exam? "; + cin >> questions; + + // Get the number of questions the student missed. + cout << "How many questions did the student miss? "; + cin >> missed; + + // Get the minimum passing score. + cout << "Enter the minimum passing score for this test: "; + cin >> minPassing; + + // Define a PassFailExam object. + PassFailExam exam(questions, missed, minPassing); + + // Display the test results. + cout << fixed << setprecision(1); + cout << "\nEach question counts " + << exam.getPointsEach() << " points.\n"; + cout << "The minimum passing score is " + << exam.getMinPassingScore() << endl; + cout << "The student's exam score is " + << exam.getScore() << endl; + cout << "The student's grade is " + << exam.getLetterGrade() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-15.cpp b/SourceCode/chapter 15/Pr15-15.cpp new file mode 100755 index 0000000..2edeb35 --- /dev/null +++ b/SourceCode/chapter 15/Pr15-15.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +// Animal is a base class. +class Animal +{ +public: + // Constructor + Animal() + { cout << "Animal constructor executing.\n"; } + + // Destructor + ~Animal() + { cout << "Animal destructor executing.\n"; } +}; + +// The Dog class is derived from Animal +class Dog : public Animal +{ +public: + // Constructor + Dog() : Animal() + { cout << "Dog constructor executing.\n"; } + + // Destructor + ~Dog() + { cout << "Dog destructor executing.\n"; } +}; + +//************************************************* +// main function * +//************************************************* + +int main() +{ + // Create a Dog object, referenced by an + // Animal pointer. + Animal *myAnimal = new Dog; + + // Delete the dog object. + delete myAnimal; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-16.cpp b/SourceCode/chapter 15/Pr15-16.cpp new file mode 100755 index 0000000..408fc7d --- /dev/null +++ b/SourceCode/chapter 15/Pr15-16.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +// Animal is a base class. +class Animal +{ +public: + // Constructor + Animal() + { cout << "Animal constructor executing.\n"; } + + // Destructor + virtual ~Animal() + { cout << "Animal destructor executing.\n"; } +}; + +// The Dog class is derived from Animal +class Dog : public Animal +{ +public: + // Constructor + Dog() : Animal() + { cout << "Dog constructor executing.\n"; } + + // Destructor + ~Dog() + { cout << "Dog destructor executing.\n"; } +}; + +//************************************************* +// main function * +//************************************************* + +int main() +{ + // Create a Dog object, referenced by an + // Animal pointer. + Animal *myAnimal = new Dog; + + // Delete the dog object. + delete myAnimal; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-17.cpp b/SourceCode/chapter 15/Pr15-17.cpp new file mode 100755 index 0000000..0b95fcc --- /dev/null +++ b/SourceCode/chapter 15/Pr15-17.cpp @@ -0,0 +1,30 @@ +// This program has a subtle error in the virtual functions. +#include +using namespace std; + +class Base +{ +public: + virtual void functionA(int arg) const + { cout << "This is Base::functionA" << endl; } +}; + +class Derived : public Base +{ +public: + virtual void functionA(long arg) const + { cout << "This is Derived::functionA" << endl; } +}; + +int main() +{ + // Allocate instances of the Derived class. + Base *b = new Derived(); + Derived *d = new Derived(); + + // Call functionA with the two pointers. + b->functionA(99); + d->functionA(99); + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-18.cpp b/SourceCode/chapter 15/Pr15-18.cpp new file mode 100755 index 0000000..cf9f0f7 --- /dev/null +++ b/SourceCode/chapter 15/Pr15-18.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the override key word. +#include +using namespace std; + +class Base +{ +public: + virtual void functionA(int arg) const + { cout << "This is Base::functionA" << endl; } +}; + +class Derived : public Base +{ +public: + virtual void functionA(int arg) const override + { cout << "This is Derived::functionA" << endl; } +}; + +int main() +{ + // Allocate instances of the Derived class. + Base *b = new Derived(); + Derived *d = new Derived(); + + // Call functionA with the two pointers. + b->functionA(99); + d->functionA(99); + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-19.cpp b/SourceCode/chapter 15/Pr15-19.cpp new file mode 100755 index 0000000..c6f868d --- /dev/null +++ b/SourceCode/chapter 15/Pr15-19.cpp @@ -0,0 +1,24 @@ +// This program demonstrates the CsStudent class, which is +// derived from the abstract base class, Student. +#include +#include "CsStudent.h" +using namespace std; + +int main() +{ + // Create a CsStudent object for a student. + CsStudent student("Jennifer Haynes", "167W98337", 2006); + + // Store values for Math, Computer Science, and General + // Ed hours. + student.setMathHours(12); // Student has taken 12 Math hours + student.setCsHours(20); // Studeht has taken 20 CS hours + student.setGenEdHours(40); // Student has taken 40 Gen Ed hours + + // Display the number of remaining hours. + cout << "The student " << student.getName() + << " needs to take " << student.getRemainingHours() + << " more hours to graduate.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-20.cpp b/SourceCode/chapter 15/Pr15-20.cpp new file mode 100755 index 0000000..7efba25 --- /dev/null +++ b/SourceCode/chapter 15/Pr15-20.cpp @@ -0,0 +1,21 @@ +// This program demonstrates a class with multiple inheritance. +#include "DateTime.h" +using namespace std; + +int main() +{ + // Define a DateTime object and use the default + // constructor to initialize it. + DateTime emptyDay; + + // Display the object's date and time. + emptyDay.showDateTime(); + + // Define a DateTime object and initialize it + // with the date 2/4/1960 and the time 5:32:27. + DateTime pastDay(2, 4, 1960, 5, 32, 27); + + // Display the object's date and time. + pastDay.showDateTime(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-4.cpp b/SourceCode/chapter 15/Pr15-4.cpp new file mode 100755 index 0000000..b0979fe --- /dev/null +++ b/SourceCode/chapter 15/Pr15-4.cpp @@ -0,0 +1,46 @@ +// This program demonstrates the order in which base and +// derived class constructors and destructors are called. +#include +using namespace std; + +//******************************** +// BaseClass declaration * +//******************************** + +class BaseClass +{ +public: + BaseClass() // Constructor + { cout << "This is the BaseClass constructor.\n"; } + + ~BaseClass() // Destructor + { cout << "This is the BaseClass destructor.\n"; } +}; + +//******************************** +// DerivedClass declaration * +//******************************** + +class DerivedClass : public BaseClass +{ +public: + DerivedClass() // Constructor + { cout << "This is the DerivedClass constructor.\n"; } + + ~DerivedClass() // Destructor + { cout << "This is the DerivedClass destructor.\n"; } +}; + +//******************************** +// main function * +//******************************** + +int main() +{ + cout << "We will now define a DerivedClass object.\n"; + + DerivedClass object; + + cout << "The program is now going to end.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-5.cpp b/SourceCode/chapter 15/Pr15-5.cpp new file mode 100755 index 0000000..62f9986 --- /dev/null +++ b/SourceCode/chapter 15/Pr15-5.cpp @@ -0,0 +1,36 @@ +// This program demonstrates passing arguments to a base +// class constructor. +#include +#include "Cube.h" +using namespace std; + +int main() +{ + double cubeWidth; // To hold the cube's width + double cubeLength; // To hold the cube's length + double cubeHeight; // To hold the cube's height + + // Get the width, length, and height of + // the cube from the user. + cout << "Enter the dimensions of a Cube:\n"; + cout << "Width: "; + cin >> cubeWidth; + cout << "Length: "; + cin >> cubeLength; + cout << "Height: "; + cin >> cubeHeight; + + // Define a Cube object and use the dimensions + // entered by the user. + Cube myCube(cubeWidth, cubeLength, cubeHeight); + + // Display the Cube object's properties. + cout << "Here are the Cube's properties:\n"; + cout << "Width: " << myCube.getWidth() << endl; + cout << "Length: " << myCube.getLength() << endl; + cout << "Height: " << myCube.getHeight() << endl; + cout << "Base area: " << myCube.getArea() << endl; + cout << "Volume: " << myCube.getVolume() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-8.cpp b/SourceCode/chapter 15/Pr15-8.cpp new file mode 100755 index 0000000..041383d --- /dev/null +++ b/SourceCode/chapter 15/Pr15-8.cpp @@ -0,0 +1,30 @@ +// This program demonstrates that when a derived class function +// overrides a base class function, objects of the base class +// still call the base class version of the function. +#include +using namespace std; + +class BaseClass +{ +public: + void showMessage() + { cout << "This is the Base class.\n"; } +}; + +class DerivedClass : public BaseClass +{ +public: + void showMessage() + { cout << "This is the Derived class.\n"; } +}; + +int main() +{ + BaseClass b; + DerivedClass d; + + b.showMessage(); + d.showMessage(); + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Rectangle.h b/SourceCode/chapter 15/Rectangle.h new file mode 100755 index 0000000..709561a --- /dev/null +++ b/SourceCode/chapter 15/Rectangle.h @@ -0,0 +1,29 @@ +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ +private: + double width; + double length; +public: + // Default constructor + Rectangle() + { width = 0.0; + length = 0.0; } + + // Constructor #2 + Rectangle(double w, double len) + { width = w; + length = len; } + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Student.h b/SourceCode/chapter 15/Student.h new file mode 100755 index 0000000..07c72d9 --- /dev/null +++ b/SourceCode/chapter 15/Student.h @@ -0,0 +1,43 @@ +// Specification file for the Student class +#ifndef STUDENT_H +#define STUDENT_H +#include +using namespace std; + +class Student +{ +protected: + string name; // Student name + string idNumber; // Student ID + int yearAdmitted; // Year student was admitted +public: + // Default constructor + Student() + { name = ""; + idNumber = ""; + yearAdmitted = 0; } + + // Constructor + Student(string n, string id, int year) + { set(n, id, year); } + + // The set function sets the attribute data. + void set(string n, string id, int year) + { name = n; // Assign the name + idNumber = id; // Assign the ID number + yearAdmitted = year; } // Assign year admitted + + // Accessor functions + const string getName() const + { return name; } + + const string getIdNum() const + { return idNumber; } + + int getYearAdmitted() const + { return yearAdmitted; } + + // Pure virtual function + virtual int getRemainingHours() const = 0; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Time.h b/SourceCode/chapter 15/Time.h new file mode 100755 index 0000000..8941d08 --- /dev/null +++ b/SourceCode/chapter 15/Time.h @@ -0,0 +1,30 @@ +// Specification file for the Time class +#ifndef TIME_H +#define TIME_H + +class Time +{ +protected: + int hour; + int min; + int sec; +public: + // Default constructor + Time() + { hour = 0; min = 0; sec = 0; } + + // Constructor + Time(int h, int m, int s) + { hour = h; min = m; sec = s; } + + // Accessor functions + int getHour() const + { return hour; } + + int getMin() const + { return min; } + + int getSec() const + { return sec; } +}; +#endif \ No newline at end of file