- Why do we need structs?
“Structs” are needed to represent more than one variable in order for an object. So, structs allows us to group variables of mixed data types together in a single unit.
- What are members in a struct?
Members (fields) are a group of variables.
- How do you access a member inside a struct?
We access a member inside a struct by using a “member selection operator; which is a period, but since struct member variables are not initialized, they must be initialized manually.
- What is a nested struct?
A nested struct is a struct within a struct. This means that once you have created one struct, it can be used to an existing struct field.
QUIZ
#include <iostream>
struct Advertising
{
int adsShown;
double clickThroughRatePercentage;
double averageEarningsPerClick;
};
Advertising getAdvertising()
{
Advertising temp;
std::cout << "How many ads were shown today? ";
std::cin >> temp.adsShown;
std::cout << "What percentage of users clicked on the ads? ";
std::cin >> temp.clickThroughRatePercentage;
std::cout << "What was the average earnings per click? ";
std::cin >> temp.averageEarningsPerClick;
return temp;
}
void printAdvertising(Advertising ad)
{
std::cout << "Number of ads shown: " << ad.adsShown << ‘\n’;
std::cout << "Click through rate: " << ad.clickThroughRatePercentage << ‘\n’;
std::cout << “Average earnings per click: $” << ad.averageEarningsPerClick << ‘\n’;
std::cout << "Total Earnings: $" <<
(ad.adsShown * ad.clickThroughRatePercentage / 100 * ad.averageEarningsPerClick) << ‘\n’;
}
int main()
{
Advertising ad = getAdvertising();
printAdvertising(ad);
return 0;
}
QUIZ #2
#include <iostream>
struct Fraction
{
int numerator;
int denominator;
};
Fraction getFraction()
{
Fraction temp;
std::cout << "Enter a value for numerator: ";
std::cin >> temp.numerator;
std::cout << "Enter a value for denominator: ";
std::cin >> temp.denominator;
std::cout << "\n";
return temp;
}
void multiply(Fraction f1, Fraction f2)
{
std::cout << static_cast<float>(f1.numerator * f2.numerator) /
(f1.denominator* f2.denominator);
}
int main()
{
Fraction f1 = getFraction();
Fraction f2 = getFraction();
multiply(f1, f2);
return 0;
}