1- There are many instances in programming where we need more than one variable in order to represent an object. A struct allows us to group variables of mixed data types together into a single unit.
2- variables that are part of the struct are called members (or fields).
3- In order to access the individual members, we use the member selection operator.for example :
struct Students{
short id;
int age;
double grade;
};
Students student1;
student1.age=14;
4- Structs can contain other structs and have variables of that type.For example :
struct Employee
{
short id;
int age;
double wage;
};
struct Company
{
Employee CEO; // Employee is a struct within the Company struct
int numberOfEmployees;
};
In this example CEO is a variable of other struct type called Employee.
Quiz)
1-
#include
using namespace std;
struct Advertising
{
int numberOfAdvertizes;
double percentageClicked;
double averageEarned;
};
double printAdvertizingData(Advertising advert)
{
double totalIncome;
cout<<"Number of Ads: " <<advert.numberOfAdvertizes<<endl;
cout<<"Percentage of ads clicked on by users : " <<advert.percentageClicked<<endl;
cout<<"Average of earnings from each ad: " <<advert.averageEarned<<endl;
totalIncome= advert.numberOfAdvertizes * advert.percentageClicked * advert.averageEarned;
return totalIncome;
}
int main()
{
int noa=0;
double poc=0;
double aoa=0;
cout<<“Enter the number of ads”<<endl;
cin>>noa;
cout<<"Enter the Percentage of ads clicked on by users : "<<endl;
cin>>poc;
cout<<“Enter the Average of earnings from each ad :”<<endl;
cin>>aoa;
Advertising adv;
adv.numberOfAdvertizes=noa;
adv.percentageClicked=poc;
adv.averageEarned=aoa;
cout<<"The total income is " <<printAdvertizingData(adv)<<" $"<<endl;
return 0;
}
2-
#include
using namespace std;
struct Fraction
{
int numerator;
int denominator;
};
double multiply(Fraction fraction1, Fraction fraction2)
{
return static_cast<double>(fraction1.numerator * fraction2.numerator) /
(fraction1.denominator* fraction2.denominator);
}
int main()
{
Fraction fraction1;
Fraction fraction2;
cout << "Enter the numerator: ";
cin >> fraction1.numerator;
cout << "Enter the denominator: ";
cin >> fraction1.denominator;
cout << "Enter the numerator: ";
cin >> fraction2.numerator;
cout << "Enter the denominator: ";
cin >> fraction2.denominator;
cout<<"The fraction in decimal is "<<multiply(fraction1,fraction2)<<endl;
return 0;
}