2.2. C++ Tutorials¶
This page follows the C++ tutorials “Up and Running with C++” by Peggy Fisher:
2.2.1. Print to Screen¶
/*
File name: greetings.cpp
Date: 9 Dec 2016
Author: Andrew Roberts
*/
// to allow cin and cout:
#include <iostream>
// standard namespaces (avoids typing std:: cout etc):
using namespace std;
// main function:
int main()
{
// screen output:
cout << "Hello, and welcome to Up and Running with C++" << endl;
// return zero:
return 0;
}
2.2.2. Input and Output Values from Screen¶
/*
File name: travel_cost.cpp
Date: 9 Dec 2016
Author: Andrew Roberts
*/
// to allow cin, cout, fixed:
#include <iostream>
// to allow setprecision:
#include <iomanip>
// standard namespaces:
using namespace std;
// main function:
int main()
{
// variables:
double mpg, distance, gallons, pricePerGallon, totalCost;
// input mpg:
cout << "Enter mpg" << endl;
cin >> mpg;
// input distance:
cout << "Enter distance in miles: " << endl;
cin >> distance;
// input price per gallon:
cout << "Enter price for one gallon of gas: " << endl;
cin >> pricePerGallon;
// calculate gallons needed:
gallons = distance/mpg;
// calculate total cost:
totalCost = gallons * pricePerGallon;
// output total cost to screen:
// fixed point notation, with a precision of 2, e.g. 1000.00 not 1e3:
cout << "Total trip cost: $" << fixed << setprecision(2) << totalCost << endl;
return 0;
}
2.2.3. Data Types¶
/*
File name: data_types.cpp
Date: 9 Dec 2016
Author: Andrew Roberts
*/
// allows cin, cout:
#include <iostream>
// standard namespaces:
using namespace std;
// main program:
int main()
{
// parameters:
char letter = 'a';
short age = 10;
int count = 575;
long numStars = 985467528;
float pi = 3.14;
double price = 89.65;
string season = "summer";
// output:
cout << "Letter: " << letter << endl;
cout << "Age: " << age << endl;
cout << "Count: " << count << endl;
cout << "Number of stars in the sky: " << numStars << endl;
cout << "Pi: " << pi << endl;
cout << "Price: " << price << endl;
cout << "Season: " << season << endl;
// return integer:
return 0;
}
2.2.4. Convert Numbers to Characters¶
/*
File name: ascii_table.cpp
Date: 9 Dec 2016
Author: Andrew Roberts
*/
// cin, cout:
#include <iostream>
// standard namespaces:
using namespace std;
// main function:
int main()
{
// declare temperature
char character;
// loop between 0 and 127
for(int num = 0; num < 128; num++)
{
// set the number equal to the character:
character = num;
// output the number and character:
cout << num << " : " << character << endl;
}
// return integer:
return 0;
}
2.2.5. Static Casting¶
/*
File name: dollars_and_cents.cpp
Date: 9 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// variables:
int dollars, cents;
double price, convert;
// implicit conversion:
char dollar_sign = 36;
// input price:
cout << "Enter price in dollars and cents: " << endl;
cin >> price;
// round down price to dollars:
dollars = static_cast<int>(floor(price));
// convert price to cents and round cents up:
convert = price * 100 - static_cast<double>(dollars * 100);
cents = static_cast<int>(ceil(convert));
// output to screen:
cout << "Total dollars: " << dollar_sign << dollars << " cents: " << cents << endl;
return 0;
}
2.2.6. Expressions¶
/*
File name: expressions.cpp
Date: 11 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
int main()
{
// variables:
int length, width, area, perimeter;
int radius, circleArea, circumference;
string firstName, lastName, fullName;
// area and perimeter rectangle:
cout<<"Enter the length and width of a rectangle"<<endl;
cin>>length;
cin>>width;
area = length*width;
perimeter = 2*length + 2*width;
cout<<"The area of the rectangle is: "<<area<<endl;
cout<<"The perimeter of the rectangle is: "<<perimeter<<endl;
// area and circumference of circle:
cout<<"Enter the radius of a circle:"<<endl;
cin>>radius;
circleArea = 3.14 * radius * radius;
circumference = 2 * 3.14 * radius;
cout<<"The area of the circle is: "<<circleArea<<endl;
cout<<"The circumference of the circle is: "<<circumference<<endl;
// add two strings:
cout<<"Enter the first and last name"<<endl;
cin>>firstName;
cin>>lastName;
fullName = firstName + " " +lastName;
cout<<"The full name is: "<<fullName<<endl;
return 0;
}
2.2.7. Conditional Statements¶
/*
File name: shipping.cpp
Date: 11 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double price, shipping;
cout<<"enter the total price of the order: "<<endl;
cin>>price;
if(price > 75)
shipping = 0;
else if(price > 50)
shipping = 5;
else if(price > 25)
shipping = 10;
else if(price > 0)
shipping = 15;
cout<<"Total price including shipping is: "<<fixed<<setprecision(2)<<price + shipping<<endl;
return 0;
}
2.2.8. While Loops¶
/*
File name: loan.cpp
Date: 11 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
int main()
{
int months = 0;
double balance = 5000;
double payment = 150;
while(balance > 0)
{
months=months+1; //or months++;
balance = balance - payment; //or balance -= payment
}
cout<<"It will take you "<<months<<" months to pay off your loan"<<endl;
}
2.2.9. Do-While Loops¶
/*
File name: membership.cpp
Date: 11 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int menuChoice;
int months;
double totalCharges;
//declare constant variables for membership costs
const double ADULT = 40.0;
const double CHILD = 30.0;
const double FAMILY = 100.0;
//setup the output formatting
cout<<fixed<<setprecision(2)<<showpoint;
do{
//Print out the menu:
cout<<"Please choose the type of membership"<<endl;
cout<<"1. Adult Membership ($40/month)"<<endl;
cout<<"2. Child Membership ($30/month)"<<endl;
cout<<"3. Family Membership ($100/month)"<<endl;
cout<<"4. Exit"<<endl;
cin>>menuChoice;
//validate the users menu choice using a while loop
while(menuChoice < 1 || menuChoice > 4)
{
cout<<"Invalid choice, please re-enter menu item"<<endl;
cin>>menuChoice;
}
if (menuChoice == 4)
break; //this allows us to exit our do/while loop
//ask the user for duration in months of membership
cout<<"Enter the number of months:"<<endl;
cin>>months;
//validate number of months
while(months <1 || months > 24)
{
cout<<"Memberships must be between 1 month and 2 years (24 months), please enter a valid number"<<endl;
cin>>months;
}
switch(menuChoice)
{
case 1:
totalCharges = months * ADULT;
break;
case 2:
totalCharges = months * CHILD;
break;
case 3:
totalCharges = months * FAMILY;
break;
default:
break;
}
cout<<"Based on your choice, your total charges will be $"<<totalCharges<<endl<<endl;
} while(menuChoice != 4); //this allows the user to enter various membership options
cout<<"Thanks for choosing our gym"<<endl;
return 0;
}
2.2.10. For Loops¶
/*
File name: print_odds.cpp
Date: 11 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
int main()
{
for(int num = 1; num <= 100; num++)
{
if(num %2 != 0)
cout<<num<<endl;
}
return 0;
}
2.2.11. Random Numbers 1¶
/*
File name: random.cpp
Date: 14 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
for(int i = 0;i<10;i++)
{
cout<<rand()<<endl;
}
return 0;
}
2.2.12. Random Numbers 2¶
/*
File name: snake_eyes.cpp
Date: 14 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
int main()
{
srand(time(0));
int count = 0;
for (int i = 0;i<100;i++)
{
int die1 = rand()%6 + 1;
int die2 = rand()%6 + 1;
cout<<setw(6)<<die1<<setw(6)<<die2;
if(die1 == 1 && die2 == 1)
{
cout<<" Snake Eyes";
count ++;
}
cout<<endl;
}
cout<<"There were "<<count<<" snake eyes"<<endl;
}
2.2.13. User Defined Functions 1¶
/*
File name: distance.cpp
Date: 16 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <cmath>
using namespace std;
double getDistance(int x1, int y1, int x2, int y2)
{
double distance;
distance = sqrt(pow((x2-x1),2) + pow((y2 - y1), 2));
return distance;
}
int main()
{
int x1, x2, y1, y2;
cout<<"Please enter the first point x1, then y1"<<endl;
cin>>x1;
cin>>y1;
cout<<"Now enter the second point"<<endl;
cin>>x2;
cin>>y2;
cout<<"The distance between these two points is: "<<
getDistance(x1,y1,x2,y2)<<endl;
return 0;
}
2.2.14. User Defined Functions 2¶
/*
File name: bool_function.cpp
Date: 16 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
/*
* display a message
*/
int number;
bool guess(int);
int main()
{
int usernum;
srand(time(0));
number = rand() % 50 + 1;
cout<<"Guess a number between 1 and 50:"<<endl;
cin>>usernum;
while(guess(usernum) != true)
{
cout<<"Try again:"<<endl;
cin>>usernum;
}
cout<<"You guessed it!!! "<<endl;
return 0;
}
bool guess(int num)
{
if(num == number)
return true;
if(num > number)
cout<<"Too high"<<endl;
else
cout<<"Too low"<<endl;
return false;
}
2.2.15. Call by Value¶
/*
File name: call_by_value.cpp
Date: 16 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
/*
* this function adds 5 to a and b temporarily since they are call by value arguments
* @param int a, int b
*/
void addfive(int a, int b)
{
cout<<"entering addfive function"<<endl;
cout<<"a and b before adding 5: a="<<a<<" b="<<b<<endl<<endl;
a += 5;
b += 5;
cout<<"a and b after adding 5: a="<<a<<" b="<<b<<endl;
cout<<"leaving addfive function"<<endl<<endl;
}
int main()
{
int a = 10, b = 15;
cout<<"a and b before calling addfive function: a="<<a<<" b="<<b<<endl<<endl;
addfive(a,b);
cout<<"a and b after calling addfive function: a="<<a<<" b="<<b<<endl;
return 0;
}
2.2.16. Call by Reference¶
/*
File name: call_by_reference.cpp
Date: 16 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
/*
* this function adds 5 to a and b temporarily since they are call by value arguments
* @param int a, int b
*/
void addfive(int& a, int& b)
{
cout<<"entering addfive function"<<endl;
cout<<"a and b before adding 5: a="<<a<<" b="<<b<<endl<<endl;
a += 5;
b += 5;
cout<<"a and b after adding 5: a="<<a<<" b="<<b<<endl;
cout<<"leaving addfive function"<<endl<<endl;
}
int main()
{
int a = 10, b = 15;
cout<<"a and b before calling addfive function: a="<<a<<" b="<<b<<endl<<endl;
addfive(a,b);
cout<<"a and b after calling addfive function: a="<<a<<" b="<<b<<endl;
return 0;
}
2.2.17. Default Arguments¶
/*
File name: default_arguments.cpp
Date: 16 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
/*
* This function calculates the perimeter of any rectangle
* @param length, width
*/
int findPerimeter(int length = 20, int width = 30);
int main()
{
//call function with no arguments
int p = findPerimeter();
cout<<"perimeter value for findPerimeter() call: "<<p<<endl;
//call function with two arguments
p = findPerimeter(5,10);
cout<<"perimeter value for findPerimeter(5,10) call: "<<p<<endl;
//call function with only one argument
p = findPerimeter(10);
cout<<"perimeter value for findPerimeter(10) call: "<<p<<endl;
return 0;
}
int findPerimeter(int length, int width)
{
return 2*length + 2 * width;
}
2.2.18. Function Overloading¶
/*
File name: hospital_stay.cpp
Date: 16 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
double calculateCharges(int, double, double, double);
double calculateCharges(double, double);
int main()
{
int days;
double dailyRate, medCharges, labCharges, totalDue;
bool inpatient = false;
char answer;
cout<<"Is this an inpatient stay?"<<endl;
cin>>answer;
while(answer != 'y' && answer != 'n')
{
cout<<"Please enter y/n"<<endl;
cin>>answer;
}
if(answer == 'y')
inpatient = true;
else
inpatient = false;
cout<<"Enter the total medication charges: "<<endl;
cin>>medCharges;
cout<<"Enter the total lab charges: "<<endl;
cin>>labCharges;
if(inpatient == true)
{
cout<<"please enter days spent in the hospital: "<<endl;
cin>>days;
cout<<"please enter the daily rate: "<<endl;
cin>>dailyRate;
//call the function that takes 4 parameters
totalDue = calculateCharges(days, dailyRate,
medCharges, labCharges);
}
else
{
//call the function that takes 2 parameters
totalDue = calculateCharges(medCharges, labCharges);
}
cout<<"The total cost is: $"<<totalDue<<endl;
return 0;
}
double calculateCharges(int d, double r, double m, double l)
{
return d*r+m+l;
}
double calculateCharges(double m, double l)
{
return m+l;
}
2.2.19. Challenge (Call by Reference)¶
/*
File name: challenge_change.cpp
Date: 16 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
// function prototypes
void get_items(string&);
void get_price_and_paid(int&, int&, int&, int&);
void set_change(int&, int, int, int, int);
void set_coins(int&, int&, int&, int&, int&, int&);
void print_coins(int&, int&, int&, int&, int&, int&);
int main()
{
int price_dollars, price_cents, paid_dollars, paid_cents;
int dollars, quarters, dimes, nickels, pennies;
string items;
int change = 0; // initialises change to zero
cout << "-----------------------" << endl;
cout << "Welcome to the store!!!" << endl;
cout << "-----------------------" << endl;
get_items(items);
while (items == "y")
{
get_price_and_paid(price_dollars, price_cents, paid_dollars, paid_cents);
set_change(change, price_dollars, price_cents, paid_dollars, paid_cents);
while (change < 0)
{
cout << "I'm sorry, the price is wrong, or the customer has not paid the full amount!" << endl;
get_price_and_paid(price_dollars, price_cents, paid_dollars, paid_cents);
set_change(change, price_dollars, price_cents, paid_dollars, paid_cents);
}
set_coins(change, dollars, quarters, dimes, nickels, pennies);
print_coins(change, dollars, quarters, dimes, nickels, pennies);
get_items(items);
}
cout << "-------------------------------" << endl;
cout << "Thank you, please come again!!!" << endl;
cout << "-------------------------------" << endl;
return 0;
}
void get_items(string& items)
{
cout << "Do you have any items to pay for? (y or n):" << endl;
cin >> items;
while (items != "y" && items != "n")
{
cout << "I'm sorry, please enter y or n if you have items:" << endl;
cin >> items;
}
}
void get_price_and_paid(int& price_dollars, int& price_cents, int& paid_dollars, int& paid_cents)
{
cout << "Please enter the price of the item (in dollars): " << endl;
cin >> price_dollars;
cout << "Please enter the price of the item (in cents): " << endl;
cin >> price_cents;
cout << "Please enter the amount the customer paid (in dollars):" << endl;
cin >> paid_dollars;
cout << "Please enter the amount the customer paid (in cents):" << endl;
cin >> paid_cents;
}
void set_change(int& change, int price_dollars, int price_cents, int paid_dollars, int paid_cents)
{
change = 100*(paid_dollars-price_dollars) + (paid_cents-price_cents);
}
void set_coins(int& change, int& dollars, int& quarters, int& dimes, int& nickels, int& pennies)
{
cout << "The change in pennies is: " << change << endl;
dollars = change / 100;
quarters = (change % 100) / 25;
dimes = (change % 100 % 25) / 10;
nickels = (change % 100 % 25 % 10) / 5;
pennies = (change % 100 % 25 % 10 % 5) / 1;
change = change - (dollars * 100) - (quarters * 25) - (dimes * 10) - (nickels * 5) - (pennies * 1);
}
void print_coins(int& change, int& dollars, int& quarters, int& dimes, int& nickels, int& pennies)
{
cout << "The number of dollars in the change is: " << dollars << endl;
cout << "The number of quarters in the change is: " << quarters << endl;
cout << "The number of dimes in the change is: " << dimes << endl;
cout << "The number of nickels in the change is: " << nickels << endl;
cout << "The number of pennies in the change is: " << pennies << endl;
cout << "The change in pennies is now: " << change << endl;
}
2.2.20. Classes, Header File¶
/*
File name: House.h
Date: 17 Dec 2016
Author: Andrew Roberts
*/
#ifndef HOUSE_H_
#define HOUSE_H_
#include <string>
using namespace std;
class House {
private:
string houseColor;
int numBathrooms;
int numBedrooms;
double squareFeet;
public:
//constructors
House();
House(string, int, int, double);
//destructor
~House();
//accessor methods
string getColor();
int getNumBath();
int getNumBed();
double getSqft();
//mutator methods
void setColor(string);
void setNumBath(int);
void setNumBed(int);
void setSqft(double);
};
#endif /* HOUSE_H_ */
2.2.21. Classes, Body of Header File¶
/*
File name: House.cpp
Date: 17 Dec 2016
Author: Andrew Roberts
*/
#include "House.h"
#include <iostream>
using namespace std;
//default constructor
House::House()
{
houseColor = "Blue";
numBathrooms = 2;
numBedrooms = 3;
squareFeet = 1200;
}
House::House(string color, int numBath, int numBed, double sqft)
{
houseColor = color;
numBathrooms = numBath;
numBedrooms = numBed;
squareFeet = sqft;
}
//destructor method
House::~House()
{
//cout<<"I'm in the destructor"<<endl;
}
//accessor methods
string House::getColor()
{
return houseColor;
}
int House::getNumBath()
{
return numBathrooms;
}
int House::getNumBed()
{
return numBedrooms;
}
double House::getSqft()
{
return squareFeet;
}
//mutator methods
void House::setColor(string c)
{
houseColor = c;
}
void House::setNumBath(int bath)
{
numBathrooms = bath;
}
void House::setNumBed(int bed)
{
numBedrooms = bed;
}
void House::setSqft(double sqft)
{
squareFeet = sqft;
}
2.2.22. Classes, Main Function, Instantiation¶
/*
File name: houses.cpp
Date: 17 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include "House.h"
#include <string>
using namespace std;
void printHouse(House);
int main()
{
//Create an instance of the House class
//using the default constructor
House house1;
//Create a second instance
//provide values for color, bed, bath, and sqft
House house2("Tan", 3, 2, 2500);
//print house information
printHouse(house1);
printHouse(house2);
house2.setColor("White");
house2.setNumBath(3);
house2.setNumBed(4);
house2.setSqft(3500);
printHouse(house2);
return 0;
}
void printHouse(House house)
{
//print the house information using
//the dot operator
cout<<"House Color: "<<house.getColor()
<<"\nNumber Bathrooms: "
<<house.getNumBath()
<<"\nNumberBedrooms: "
<<house.getNumBed()<<endl;
cout<<"Total Square feet: "
<<house.getSqft()<<endl;
cout<<endl<<endl;
//since it is a void function,
//I do not need a return statement
}
2.2.23. Challenge (Classes), Header File¶
/*
File name: Movie.h
Date: 18 Dec 2016
Author: Andrew Roberts
*/
#ifndef MOVIE_H_
#define MOVIE_H_
#include <string>
using namespace std;
class Movie
{
private:
string name;
int year;
string rating;
public:
// constructors
Movie();
Movie(string, int, string);
// destructor
~Movie();
string get_name();
int get_year();
string get_rating();
void set_name(string);
void set_year(int);
void set_rating(string);
};
#endif /* MOVIE_H_ */
2.2.24. Challenge (Classes), Body of Header File¶
/*
File name: Movie.cpp
Date: 18 Dec 2016
Author: Andrew Roberts
*/
#include "Movie.h"
#include <iostream>
using namespace std;
// default constructor:
Movie::Movie()
{
name = "Star Wars";
year = 1977;
rating = "PG";
}
// constructor:
Movie::Movie(string name, int year, string rating)
{
this->name = name;
this->year = year;
this->rating = rating;
}
// destructor:
Movie::~Movie()
{
}
// accessor methods
string Movie::get_name()
{
return name;
}
int Movie::get_year()
{
return year;
}
string Movie::get_rating()
{
return rating;
}
// mutator methods
void Movie::set_name(string name)
{
this->name = name;
}
void Movie::set_year(int year)
{
while(year < 1950 || year > 2016)
{
cout << "Sorry, please enter movie year between 1950 and 2016: ";
cin >> year;
cin.ignore(); // needed so the getline function does not use the return as input
}
this->year = year;
}
void Movie::set_rating(string rating)
{
this->rating = rating;
}
2.2.25. Challenge (Classes), Main Function¶
/*
File name: movies.cpp
Date: 18 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include "Movie.h"
#include <string>
#include <cctype>
using namespace std;
void print_movie(Movie);
void set_movie(Movie&);
int main()
{
cout << "Please enter your three favourite movies: " << endl;
Movie movie_one;
set_movie(movie_one);
Movie movie_two;
set_movie(movie_two);
Movie movie_three;
set_movie(movie_three);
print_movie(movie_one);
print_movie(movie_two);
print_movie(movie_three);
return 0;
}
void print_movie(Movie movie)
{
cout << "Movie name: " << movie.get_name() << endl;
cout << "Movie year: " << movie.get_year() << endl;
cout << "Movie rating: " << movie.get_rating() << endl;
cout << "" << endl;
}
void set_movie(Movie& new_movie)
{
string new_name;
int new_year;
string new_rating;
cout << "Enter movie name: ";
getline(cin, new_name);
new_movie.set_name(new_name);
cout << "Enter movie year: ";
cin >> new_year;
cin.ignore(); // needed so the getline function does not use the return as input
new_movie.set_year(new_year);
cout << "Enter movie rating: ";
getline(cin, new_rating);
new_movie.set_rating(new_rating);
cout << "" << endl;
}
2.2.26. Arrays 1¶
/*
File name: arrays.cpp
Date: 21 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
//array declarations
string seasons[4];
int numbers[10];
for(int i = 0;i<10;i++)
{
numbers[i] = rand();
}
//declare and initialize the array
string weekdays[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
//change the value of an array
seasons[0] = "summer";
seasons[1] = "fall";
seasons[2] = "winter";
seasons[3] = "spring";
cout<<seasons<<endl;
cout<<seasons[0]<<endl;
cout<<seasons[1]<<endl;
cout<<seasons[2]<<endl;
cout<<seasons[3]<<endl;
cout<<numbers[0]<<endl;
return 0;
}
2.2.27. Arrays 2¶
/*
File name: heights.cpp
Date: 21 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <string>
using namespace std;
void getWeights(double[], int);
double findAverage(double[], int);
double findHeaviest(double[], int);
int main()
{
double weights[10];
getWeights(weights, 10);
cout<<"The average weight of all students is: "
<<findAverage(weights, 10)<<" pounds"<<endl;
cout<<"The heaviest student is: "
<<findHeaviest(weights, 10)<<" pounds"<<endl;
return 0;
}
void getWeights(double h[], int size)
{
for(int i = 0; i<size; i++)
{
cout<<"Enter student weight in pounds: \n";
cin>>h[i];
}
}
double findAverage(double h[], int size)
{
int count = 0;
double total = 0;
for(int i = 0; i<size; i++)
{
count++;
total += h[i];
}
return total/count;
}
double findHeaviest(double h[], int size)
{
double heaviest = h[0];
for(int i = 1; i<size; i++)
{
if(h[i] > heaviest)
{
heaviest = h[i];
}
}
return heaviest;
}
2.2.28. Abstract Data Types¶
/*
File name: employees.cpp
Date: 23 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
//define the new data structure
struct Address
{
char houseNum[5];
char streetName[30];
char city[30];
char state[3];
int zipcode;
};
struct DateOfBirth
{
int month;
int day;
int year;
};
struct Employee
{
char firstName[30];
char lastName[30];
int eeNumber;
double hourlyWage;
Address homeAddress;
DateOfBirth dob;
};
//printEes prototype
void printEes(Employee[],int);
int main()
{
int numEmployees;
cout<<"How many employees do you have? \n";
cin>>numEmployees;
//create an array of type Employee
Employee employees[numEmployees];
//loop for creating new employee data structure variables
for(int i = 0;i < numEmployees;i++)
{
cout<<"Please enter first name: \n";
cin>>employees[i].firstName;
cout<<"Enter last name: \n";
cin>>employees[i].lastName;
cout<<"Enter employee id: \n";
cin>>employees[i].eeNumber;
cout<<"Enter hourly wage: \n";
cin>>employees[i].hourlyWage;
cout<<"Enter house number: \n";
cin>>employees[i].homeAddress.houseNum;
cin.ignore();
cout<<"Enter street name: \n";
cin.getline(employees[i].homeAddress.streetName, 30);
cout<<"Enter city: \n";
cin>>employees[i].homeAddress.city;
cout<<"Enter state: \n";
cin>>employees[i].homeAddress.state;
cout<<"Enter zipcode: \n";
cin>>employees[i].homeAddress.zipcode;
cout<<"Enter birth month, day and year: \n";
cin>>employees[i].dob.month;
cin>>employees[i].dob.day;
cin>>employees[i].dob.year;
}
printEes(employees,numEmployees);
}
void printEes(Employee employees[], int size)
{
for(int i = 0; i < size; i++)
{
cout<<employees[i].firstName <<" "
<<employees[i].lastName<<endl;
cout<<employees[i].homeAddress.houseNum<<" "
<<employees[i].homeAddress.streetName<<endl;
cout<<employees[i].homeAddress.city<<", "
<<employees[i].homeAddress.state<<" "
<<employees[i].homeAddress.zipcode<<endl;
cout<<"Hourly wage: "<<employees[i].hourlyWage;
cout<<endl;
cout<<"Date of Birth: ";
switch(employees[i].dob.month)
{
case 1:
cout<<"January ";
break;
case 2:
cout<<"February ";
break;
case 3:
cout<<"March ";
break;
case 4:
cout<<"April ";
break;
case 5:
cout<<"May ";
break;
case 6:
cout<<"June ";
break;
case 7:
cout<<"July ";
break;
case 8:
cout<<"August ";
break;
case 9:
cout<<"September ";
break;
case 10:
cout<<"October ";
break;
case 11:
cout<<"November ";
break;
case 12:
cout<<"December ";
break;
default:
cout<<"Invalid Month";
break;
};
cout<<employees[i].dob.day<<", ";
cout<<employees[i].dob.year<<endl;
}
}
2.2.29. Pointers¶
/*
File name: pointers.cpp
Date: 24 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
int main()
{
/*
int JohnsAcct = 12345;
int* acctPtr = &JohnsAcct;
cout<<"Johns acct number: "<<JohnsAcct<<" is at: "<<acctPtr<<endl;
cout<<"acctPtr points to this value: *acctPtr:"<<*acctPtr<<endl;
*/
//another example
cout<<endl<<"Next example, declares num = 95:"<<endl;
int num = 95;
cout<<"Address to find num value: "<<&num<<endl;
cout<<"size of num value based on datatype: "<<sizeof(num)<<endl;
cout<<"value at this location: "<<num<<endl;
cout<<endl<<"Next example, add numPtr:"<<endl;
//lets add a pointer to hold the address of num
int* numPtr = #
//lets change the value of num using the pointer
cout<<"add 5 to num using the pointer and not the variable:"<<endl;
*numPtr += 5; //num value is now 100
cout<<"Num is now: "<<num<<endl;
cout<<"Num location is still the same: "<<&num<<endl;
cout<<"Location of numPtr is: "<<numPtr<<endl;
cout<<"Value of numPtr is: "<<*numPtr<<endl;
cout<<endl<<"Next example, using characters"<<endl;
char letter = 'A';
cout<<"size of letter value based on datatype: "<<
sizeof(letter)<<endl;
cout<<"value at this location: "<<letter<<endl;
//lets add a pointer to hold the address of letter
char* letterPtr = &letter;
//lets change the value of letter using the pointer
cout<<"\nadd 25 to letter:"<<endl;
*letterPtr += 25; //letter value is now Z
cout<<"Letter is now: "<<letter<<endl;
return 0;
}
2.2.30. Vectors¶
/*
File name: vectors.cpp
Date: 24 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
//create three vectors
//carVins contains the vin of each car on a showroom floor
//(note: carVins starts as an empty vector)
vector<int> carVins;
//num contains 10 integer values
vector<int> num(10);
//prices contains 5 prices that are initially zero
vector<double> prices(5,0.0);
int numCars;
int vin;
cout<<"How many cars are in the showroom?\n";
cin>>numCars;
for(int i = 0; i<numCars; i++)
{
cout<<"Enter the vin for car "<<i+1<<" :";
cin>>vin;
//add the new vin to the end of the vector
carVins.push_back(vin);
}
//print the vins:
cout<<"\nVin numbers for cars in showroom:\n";
for(int i = 0; i<carVins.size();i++)
{
cout<<carVins[i]<<endl;
}
//add 10 random integers to the num vector
int randomNum;
for(int i = 0; i < num.size(); i++)
{
num[i] = rand();
}
//print the random numbers:
cout<<"\n10 random integers: \n";
for(int i = 0; i<num.size();i++)
{
cout<<num[i]<<endl;
}
//Other vector functions include:
//.at returns the value located at element 0
int value = num.at(0);
//.capacity() returns the max number of elements
//that may be stored
//without adding additional memory
int value2 = num.capacity();
//.pop_back removes the last element from a vector
num.pop_back();
//.clear() is used to clear a vector of all elements
num.clear();
//.empty() returns true if vector is empty
if(num.empty()==true)
cout<<"vector num is empty\n";
//.swap(vector2) swaps the contents
}
2.2.31. Sorting, Binary Search¶
/*
File name: binary_search.cpp
Date: 24 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
bool search(int[], int, int);
int main()
{
srand(time(0));
int nums[10];
for(int i = 0;i<10;i++)
{
nums[i] = rand()%100 + 1;
}
cout<<"Array before sort"<<endl;
for(int i = 0; i<10;i++)
cout<<nums[i]<<" ";
cout<<endl;
//sort the array using a selection sort
for(int j=0; j<10; j++)
{
int index = j;
for(int k=j; k<10; k++)
{
if(nums[index]>nums[k])
{
index = k;
}
}
int temp = nums[j];
nums[j] = nums[index];
nums[index] = temp;
}
cout<<"Array after sort"<<endl;
for(int i = 0; i<10;i++)
cout<<nums[i]<<" ";
cout<<endl;
int value;
cout<<"Enter a number between 1 and 100: "<<endl;
cin>>value;
if(search(nums, 10, value)== true)
{
cout<<"Value "<<value<<" was found\n";
}
else
{
cout<<"Value "<<value<<" was not found\n";
}
}
bool search(int numbers[], int size, int value)
{
//to use a binary search, the array must
//already be in sorted order
bool found = false;
int low = 0;
int high = size - 1;
int pos = 0;
while(low <= high && !found)
{
pos = (low + high)/2;
if(numbers[pos] == value)
{
found = true;
}
else if(numbers[pos] < value)
{
low = pos+1;
}
else
{
high = pos - 1;
}
}
return found;
}
2.2.32. Challenge (Search)¶
/*
File name: challenge_lunch_menu.cpp
Date: 24 Dec 2016
Author: Andrew Roberts
*/
#include <iostream>
#include <string>
//#include <algorithm>
#include <vector>
// to allow setprecision:
#include <iomanip>
using namespace std;
//int findNumber(string array[], int size, string target);
int search(string[], int, string);
void print_total_cost(int[], double[], int[], double);
void get_choices(int, string[], int[], int, string[]);
void get_quantities(int, string[], int[]);
int main()
{
string menu[] = {"hotdog", "hamburger", "french fries", "salad", "exit"};
double prices[] = {1.20, 3.34, 0.99, 1.11, 0.00};
string choices[] = {"exit", "exit", "exit", "exit"};
int quantities[] = {0, 0, 0, 0};
int positions[] = {4, 4, 4, 4};
int arraysize = 5;
double cost = 0.0;
for(int i=0; i<4; i++)
{
get_choices(i, choices, positions, arraysize, menu);
while(positions[i] == -1)
{
cout << "Invalid choice." << endl;
get_choices(i, choices, positions, arraysize, menu);
}
if (choices[i].compare("exit") == 0)
{
break;
}
get_quantities(i, choices, quantities);
}
print_total_cost(quantities, prices, positions, cost);
return 0;
}
void get_choices(int i, string choices[], int positions[], int arraysize, string menu[])
{
cout << "Please enter choice number " << i+1 << " (hotdog, hamburger, french fries, salad or exit)." << endl;
getline(cin, choices[i]);
positions[i] = search(menu, arraysize, choices[i]);
}
void get_quantities(int i, string choices[], int quantities[])
{
cout << "Please enter quantity of " << choices[i] << endl;
cin >> quantities[i];
cin.ignore();
}
void print_total_cost(int quantities[], double prices[], int positions[], double cost)
{
cout << "This is the total cost:" << endl;
for(int i=0; i<4; i++)
{
cost += quantities[i]*prices[positions[i]];
}
cout << "$" << fixed << setprecision(2) << cost << endl;
}
int search(string numbers[], int size, string value)
{
bool exit = false;
int pos = 0;
while(!exit)
{
if(numbers[pos] == value)
{
exit = true;
}
else if(pos + 1 == size)
{
pos = -1;
exit = true;
}
else
{
pos = pos + 1;
}
}
return pos;
}
2.2.33. File Operations 1¶
/*
File name: fortune_teller.cpp
Date: 13 Jan 2017
Author: Andrew Roberts
*/
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream> // reading, writing and creating files
#include <ctime>
using namespace std;
string getRandomReply(string [], int);
int main()
{
ifstream inputfile;
//declare an input file
inputfile.open("replies.txt", ios::in);
char answer[30];
string answers[20];
int pos = 0;
//read from the file until end of file (eof)
while(!inputfile.eof())
{
inputfile.getline(answer, 30);
answers[pos] = answer;
pos ++;
}
cout<<"Think of a question for the fortune teller, "
"\npress enter for the answer "<<endl;
cin.ignore();
cout<<getRandomReply(answers,20)<<endl;
}
string getRandomReply(string replies[],int size)
{
srand(time(0));
int randomNum = rand()%20;
return replies[randomNum];
}
2.2.34. File Operations 2¶
/*
File name: mailing_addresses.cpp
Date: 13 Jan 2017
Author: Andrew Roberts
*/
#include <iostream>
#include <fstream>
using namespace std;
//create a new datatype for holding addresses
struct Address
{
string fullName;
char houseNum[5];
char streetName[30];
char city[30];
char state[3];
int zipcode;
};
void writeToFile(Address m[], int size);
int main()
{
int numees;
string fullname;
string fname, lname;
cout<<"How many employees do you have? \n";
cin>>numees;
Address mailing[numees];
for(int i = 0;i < numees;i++)
{
cout<<"Please enter first name: \n";
cin>>fname;
cout<<"Enter last name: \n";
cin>>lname;
fullname = fname + " " + lname;
mailing[i].fullName = fullname;
cout<<"Enter house number: \n";
cin>>mailing[i].houseNum;
cin.ignore();
cout<<"Enter street name: \n";
cin.getline(mailing[i].streetName, 30);
cout<<"Enter city: \n";
cin>>mailing[i].city;
cout<<"Enter state: \n";
cin>>mailing[i].state;
cout<<"Enter zipcode: \n";
cin>>mailing[i].zipcode;
}
writeToFile(mailing,numees);
}
void writeToFile(Address m[], int size)
{
ofstream output;
output.open("mailingaddress.txt", ios::out);
for(int i = 0; i < size; i++)
{
output<<m[i].fullName<<endl;
output<<m[i].houseNum<<" "<<m[i].streetName<<endl;
output<<m[i].city<<", "<<m[i].state<<" " <<m[i].zipcode<<endl;
output<<endl;
}
}
2.2.35. Error Handling¶
/*
File name: error_handling.cpp
Date: 13 Jan 2017
Author: Andrew Roberts
*/
#include <iostream>
using namespace std;
int main()
{
int errorcode= 10;
int numerator;
int denominator;
do{
cout<<"Enter numerator: ";
cin>>numerator;
cout<<"Enter denominator: ";
cin>>denominator;
try
{
if(denominator == 0)
throw errorcode;
else
cout<<"The ratio is: "<<numerator/denominator<<endl;
}
catch(int error)
{
if(error == errorcode)
{
cout<<"\nDivide by zero error!! \n ";
}
}
}while(denominator != 0);
return 0;
}
2.2.36. Challenge (Error Handling and File Operations)¶
/*
File name: challenge_file_read.cpp
Date: 14 Jan 2017
Author: Andrew Roberts
*/
#include <iostream>
#include <fstream> // reading, writing and creating files
#include <iomanip> // setprecision
#include <vector>
#include <stdlib.h>
#include <numeric>
using namespace std;
int add_columns(vector<int>, vector<int>);
double average_column(vector<int>);
int error_code=666;
int main()
{
ifstream inputfile;
try
{
inputfile.open("numbers.txt", ios::in);
if(inputfile.fail())
{
throw error_code;
}
}
catch(int error_number)
{
if(error_number==error_code)
{
cout << "File reading error." << endl;
exit(1);
}
}
int number_1;
int number_2;
vector<int> column_1;
vector<int> column_2;
while(!inputfile.eof())
{
inputfile >> number_1;
column_1.push_back(number_1);
inputfile >> number_2;
column_2.push_back(number_2);
}
int total = add_columns(column_1, column_2);
cout << "Total: " << total << endl;
double average_1 = average_column(column_1);
cout << "Average column 1: " << fixed << setprecision(2) << average_1 << endl;
double average_2 = average_column(column_2);
cout << "Average column 2: " << fixed << setprecision(2) << average_2 << endl;
}
int add_columns(vector<int> column_1, vector<int> column_2)
{
double total_1 = accumulate(column_1.begin(), column_1.end(), 0.0);
double total_2 = accumulate(column_2.begin(), column_2.end(), 0.0);
return total_1+total_2;
}
double average_column(vector<int> column_1)
{
double average = accumulate(column_1.begin(), column_1.end(), 0.0)/column_1.size();
return average;
}
2.2.37. Challenge - Simple (Error Handling and File Operations)¶
/*
File name: challenge_file_read_simple.cpp
Date: 16 Jan 2017
Author: Andrew Roberts
*/
#include <iostream>
#include <fstream> // reading, writing and creating files
#include <stdlib.h> // exit
using namespace std;
double column_1 = 0.0;
double column_2 = 0.0;
double column_1_total = 0.0;
double column_2_total = 0.0;
int count = 0;
int error_signal=666;
int main()
{
ifstream inputfile;
try
{
inputfile.open("numbers.txt", ios::in);
if(inputfile.fail())
{
throw error_signal;
}
}
catch(int error_number)
{
if(error_number==error_signal)
{
cout << "File reading error." << endl;
exit(1);
}
}
while(!inputfile.eof())
{
inputfile >> column_1;
column_1_total += column_1;
inputfile >> column_2;
column_2_total += column_2;
count++;
}
cout << "Average of column 1: " << column_1_total/count << endl;
cout << "Average of column 2: " << column_2_total/count << endl;
}