Why do we need structs?
it is much easier to use structs to deal with situations with multiple and repetitive variables
What are members in a struct?
variables in a struct
How do you access a member inside a struct?
structInstantiation.member
What is a nested struct?
when a struct is a member of another struct
Quiz
1) You are running a website, and you are trying to keep track of how much money you make per day from advertising. Declare an advertising struct that keeps track of how many ads you’ve shown to readers, what percentage of ads were clicked on by users, and how much you earned on average from each ad that was clicked. Read in values for each of these fields from the user. Pass the advertising struct to a function that prints each of the values, and then calculates how much you made for that day (multiply all 3 fields together).
#include <iostream>
#include <iomanip>
using namespace std;
struct Advertising
{
double adsShown=0;
double adsClickedPercentage=0;
double averageEarningPerAd=0;
};
void advertisingData(Advertising month) {
cout << "Ads shown: " << month.adsShown << endl;
cout << "Percentage of ads clicked: " << month.adsClickedPercentage << endl;
cout << "Average earnings per ad: " << month.averageEarningPerAd << endl;
cout << "Profit " << month.averageEarningPerAd * month.adsClickedPercentage * month.adsShown << endl;
}
int main()
{
Advertising january;
cout << "Enter ads shown." << endl;
cin >> january.adsShown;
cout << "Enter percentage of ads clicked." << endl;
cin >> january.adsClickedPercentage;
cout << "Enter average earnings per ad." << endl;
cin >> january.averageEarningPerAd;
advertisingData(january);
}
2) Create a struct to hold a fraction. The struct should have an integer numerator and an integer denominator member. Declare 2 fraction variables and read them in from the user. Write a function called multiply that takes both fractions, multiplies them together, and prints the result out as a decimal number. You do not need to reduce the fraction to its lowest terms.
#include <iostream>
#include <iomanip>
using namespace std;
struct Fraction
{
int denominator=1;
int numerator=1;
};
void multiply(Fraction fraction1, Fraction fraction2) {
double total = 0;
double first = (static_cast<double>(fraction1.numerator)/static_cast<double>(fraction1.denominator));
double second = (static_cast<double>(fraction2.numerator)/static_cast<double>(fraction2.denominator));
total = first*second;
cout << "Fraction1 * fraction2 = " << total << endl;
}
int main()
{
Fraction one;
cout << "Enter numerator for fraction1" << endl;
cin >> one.numerator;
cout << "Enter denominator for fraction1" << endl;
cin >> one.denominator;
Fraction two;
cout << "Enter numerator for fraction2" << endl;
cin >> two.numerator;
cout << "Enter denominator for fraction2" << endl;
cin >> two.denominator;
multiply(one, two);
}