OOP Assignment f2023266160 Abdullah Farooq
OOP Assignment f2023266160 Abdullah Farooq
OOP Assignment
ABDULLAH FAROOQ
F2023266160
Struct Practice Question from Tony Gaddis :
Short Question :
1. What is a primitive data type ?
Primitive data types are the fundamental building blocks of data in a programming language. They
are simple, predefined data types that are directly supported by the language. Examples include
integers (whole numbers), floating-point numbers (decimal numbers), characters, and Boolean
values.
Similarly, a structure declaration tells you what a structure will contain, but it doesn't actually
create a structure variable. You need to use the declaration to create structure variables in your
program, just like you use the cake recipe to actually bake a cake.
3. Both arrays and structures are capable of storing multiple values. What is the difference between
an array and a structure?
Arrays are like rows of boxes, each box containing something similar, like all your socks in one row.
Structures are like a single box with compartments, where you can put different things together, like
socks, shirts, and shoes all in one box, but each in its own section.
Arrays have a fixed size, like a fixed number of boxes in a row, while structures can change in size
depending on what you put in them.
struct Point {
int x; int y;
};
struct FullName {
char lastName[26];
char middleName[26];
char firstName[26];
};
B) Assign your last, middle, and first name to the members of the info variable
Solution :
Code :
struct PartData {
char partName[51];
int idNumber;
};
PartDatainventory[100];
Write a statement that displays the contents of the partName member of element 49 of the
inventory array.
Code :
struct Town {
char townName[51];
char countyName[51];
double population;
double elevation;
};
t.townName=”Canton”;
c.countyName=”Haywood”;
t.population=9478;
0
8. Look at the following code.
structure Rectangle {
int length;
int width;
};
Rectangle *r;
B) Assign 10 to the structure’s length member and 14 to the structure’s width member.
9. What is the difference between a union and a structure?
The main difference between a union and a structure lies in how
they organize and store data:
1. Structure :
A structure is a composite data type that allows you to group
together variables of different data types under a single name.
Each member of a structure has its own memory location, and the
total memory occupied by a structure is the sum of the memory
occupied by each of its members.
You can access each member of a structure independently.
2. Union :
A union is also a composite data type that allows you to group
together variables of different data types under a single name.
However, unlike a structure, all members of a union share the same
memory location. This means that a union occupies only as much
memory as its largest member.
When you assign a value to one member of a union, it overwrites
the values of all other members.
Unions are useful when you need to store different types of data in
the same memory location, and you only need to access one
member at a time.
10. Look at the following code.
union Values {
int ivalue;
double dvalue;
};
Values v;
Assuming that an int uses four bytes and a double uses eight bytes, how much memory does the
variable v use?
So, the memory allocated for the union Values would be 8 bytes, the size of the largest member
(double dvalue).
Person p;
A) p = BOB;
Valid. BOB is an enumerator of the enum type Person, so it can be assigned to a variable of type
Person.
B) p++;
D) p = 0;
Invalid. While 0 is a valid value for an enum type, directly assigning an integer to an enum variable is
not allowed without a cast.
E) int x = BILL;
F) p = static_cast<Person>(3);
Valid. This statement casts the integer value 3 to the enum type Person. It's a safe way to assign an
integer value to an enum variable.
Valid. Enumerators can be used directly in output statements like this. It will print the integer value
associated with CLAIRE, which is 2.
Fill-in-the-Blank :
13. Before a structure variable can be created, the structure must be Defined.
15. The variables declared inside a structure declaration are called Member.
16. A(n) Semicolonis required after the closing brace of a structure declaration.
17. In the definition of a structure variable, the Structure Tag is placed before the variable name,
just like the data type of a regular variable is placed before its name.
Algorithm Workbench :
19 :
struct Car {
char carMake[20];
char carModel[20];
int yearModel;
double cost;
};
Write a definition statement that defines a Car structure variable initialized with the following
data: Make: Ford Model: Mustang Year Model: 1997 Cost: $20,000.
#include<iostream>
#include<cstring>
struct car{
char carMake[20];
int yearModel;
double cost;
};
int main(){
car c;
strcpy(c.carMake,"Ford");
strcpy(c.carModel,"Mustang");
c.yearModel=1997;
c.cost= 20000;
#include<cstring>
struct car{
char carMake[20];
char carModel [20];
int yearModel;
double cost;
};
int main(){
car c[25];
strcpy(c[0].carMake,"Ford");
strcpy(c[0].carModel,"Mustang");
c[0].yearModel=1997;
c[0].cost= 20000;
Make
Model
Year
Cost
(Ford Taurus 1997 $21,000 Honda Accord 1992 $11,000 Lamborghini Countach 1997 $200,000).
#include<iostream>
#include<cstring>
struct car{
char carMake[20];
int yearModel;
double cost;
};
int main(){
car cars[25];
strcpy(cars[0].carMake,"Ford");
strcpy(cars[0].carModel,"Taurus");
cars[0].yearModel=1997;
cars[0].cost= 21000;
strcpy(cars[1].carMake,"Honda");
strcpy(cars[1].carModel,"Accord");
cars[1].yearModel=1994;
cars[1].cost= 1100;
strcpy(cars[2].carMake,"Lamborghini");
strcpy(cars[2].carModel,"Countach");
cars[2].yearModel=1997;
cars[2].cost= 200,000;
return 0;
22. Write a loop that will step through the array you defined in
Question 21, displaying the contents of each element.
#include<iostream>
#include<cstring>
struct Car {
char carMake[20];
char carModel[20];
int yearModel;
double cost;
};
int main() {
Car cars[25];
strcpy(cars[i].carMake, "Ford");
strcpy(cars[i].carModel, "Mustang");
cars[i].yearModel = 1997;
cars[i].cost = 20000.0;
return 0;
fahrenheit: a double
centigrade: a double
an int humidity:
a double temperature:
struct TempScale {
double fahrenheit;
double centigrade;
};
struct Reading {
int windSpeed;
double humidity;
TempScale temperature;
};
int main() {
Reading currentReading;
currentReading.windSpeed = 10;
currentReading.humidity = 0.5;
currentReading.temperature.fahrenheit = 75.0;
return 0;}
24. Write statements that will store the following data in the variable you defined in Question 23.
Humidity: 32%;
struct TempScale {
double fahrenheit;
double centigrade;
};
struct Reading {
int windSpeed;
double humidity;
TempScale temperature;
};
int main() {
Reading currentReading;
currentReading.windSpeed = 37;
currentReading.humidity = 0.32;
currentReading.temperature.fahrenheit = 32.0;3
return 0; }
;
25 :Write a function called showReading. It should accept a Reading structure variable (see
Question 23) as its argument. The function should display the contents of the variable on
the screen.
#include<iostream>
struct TempScale {
double fahrenheit;
double centigrade;
};
struct Reading {
int windSpeed;
double humidity;
TempScale temperature;
};
void showReading(Reading r) {
int main() {
Reading currentReading;
currentReading.windSpeed = 37;
currentReading.humidity = 0.32;
currentReading.temperature.fahrenheit = 32.0;
showReading(currentReading);
return 0; }
26. Write a function called findReading. It should use a Reading structure reference
variable (see Question 23) as its parameter. The function should ask the user to enter
values for each member of the structure.
#include <iostream>
struct TempScale {
double fahrenheit;
double centigrade;
};
struct Reading {
int windSpeed;
double humidity;
TempScale temperature;
};
void findReading(Reading& r) {
cin>>r.windSpeed;
cin>>r.humidity;
cin>>r.temperature.fahrenheit;
int main() {
Reading currentReading;
findReading(currentReading);
return 0; }
27. Write a function called getReading, which returns a Reading structure (see Question 23). The
function should ask the user to enter values for each member of a Reading structure, then return
the structure.
#include <iostream>
struct TempScale {
double fahrenheit;
double centigrade;
};
struct Reading {
int windSpeed;
double humidity;
TempScale temperature;
};
Reading getReading() {
Reading r;
cin>>r.windSpeed;
cin>>r.humidity;
cin>>r.temperature.fahrenheit;
return r;
int main() {
return 0;
}
28. Write a function called recordReading. It should use a Reading structure pointer
variable (see Question 23) as its parameter. The function should ask the user to enter
values for each member of the structure pointed to by the parameter.
#include <iostream>
struct TempScale {
double fahrenheit;
double centigrade;
};
struct Reading {
int windSpeed;
double humidity;
TempScale temperature;
};
void recordReading(Reading* r) {
cin>> (*r).windSpeed;
cin>> (*r).humidity;
cin>> (*r).temperature.fahrenheit;
int main() {
Reading currentReading;
recordReading(¤tReading);
cout<< "\nCurrent Reading:\n";
return 0;
29. Rewrite the following statement using the structure pointer operator:
(*rptr).windSpeed = 50;
#include <iostream>
struct Reading {
int windSpeed;
};
int main() {
(*rptr).windSpeed = 50;
return 0;
}
30. Rewrite the following statement using the structure pointer operator:
*(*strPtr).num = 10;
#include <iostream>
struct Structure {
int num;
};
int main() {
(*strPtr).num= 10;
return 0;
}
True or False
36. A semicolon is required after the closing brace of a structure or
union declaration(F ).
37.A structure declaration does not define a variable F.
38. The contents of a structure variable can be displayed by passing
the structure variable to the cout object T.
39.Structure variables may not be initialized T.
40. In a structure variable’s initialization list, you do not have to
provide initializers for all the members F.
41.You may skip members in a structure’s initialization list T.
42. The following expression refers to the element 5 in the array
carInfo: carInfo.model[5] F.
43. An array of structures may be initialized T.
44. A structure variable may not be a member of another structure F.
45. A structure member variable may be passed to a function as an
argument T.
46. An entire structure may not be passed to a function as an
argumentF.
47. A function may return a structureT.
48. When a function returns a structure, it is always necessary for
the function to have a local structure variable to hold the member
values that are to be returnedF.
49. The indirection operator has higher precedence than the dot
operatorF.
50. The structure pointer operator does not automatically
dereference the structure pointer on its leftF.
Find the Errors
Each of the following declarations, programs, and program segments has errors. Locate as many as
you can.
int a, b;
};
int main () {
TwoVals.a = 10;
TwoVals.b = 20;
return 0;
#include<iostream>
struct ThreeVals {
int a, b, c;
};
int main() {
cout<<vals<<endl;
return 0;
struct names {
char first[20];
char last[20];
};
int main () {
cout<<names.first<<endl; cout<<names.last<<endl;
return 0;
int a, b, c, d;
};
int main () {
return 0;
63. #include<iostream>
struct TwoVals {
int a = 5;
int b = 10;
};
int main(){
return 0;
}
64:
struct TwoVals {
int a;
int b;
};
int main() {
TwoValsvarray[10];
varray[0].a = 1; // Corrected
return 0;
int a;
int b;
};
TwoValsgetVals() {
TwoVals.a = TwoVals.b = 0;
int a, b, c;
};
int main () {
TwoVals s, *sptr;
sptr = &s;
*sptr.a = 1;
sptr->a = 1; // Corrected
return 0; }
Programming Challenges:
1. Movie Data
#include <iostream>
using namespace std;
struct MovieData {
string title;
string director;
int yearReleased;
int runningTime;
};
void displayMovieInfo(MovieData movie) {
cout<< "Title: "<<movie.title<<endl;
cout<< "Director: "<<movie.director<<endl;
cout<< "Year Released: "<<movie.yearReleased<<endl;
cout<< "Running Time: "<<movie.runningTime<< " minutes"<<endl;
cout<<endl;
}
int main() {
MovieData movie1 = {"Inception", "Christopher Nolan", 2010, 148};
MovieData movie2 = {"The Shawshank Redemption", "Frank Darabont", 1994,
142};
displayMovieInfo(movie1);
displayMovieInfo(movie2);
return 0;
}
2. Movie Profit
#include <iostream>
using namespace std;
struct MovieData {
string title;
string director;
int yearReleased;
int runningTime;
double productionCost;
double firstYearRevenue;
};
void displayMovieInfo(MovieData movie) {
double profitOrLoss=movie.firstYearRevenue-movie.productionCost;
cout<< "Title: "<<movie.title<<endl;
cout<< "Director: "<<movie.director<<endl;
cout<< "Year Released: "<<movie.yearReleased<<endl;
cout<< "Running Time: "<<movie.runningTime<< " minutes"<<endl;
cout<< "First Year Profit/Loss:$" <<profitOrLoss<<endl;
cout<<std::endl;
}
int main() {
MovieData movie1 = {"Inception", "Christopher Nolan", 2010, 148,160000000,
825532764};
MovieData movie2 = {"The Shawshank Redemption", "Frank Darabont", 1994,
142, 25000000, 28341469};
displayMovieInfo(movie1);
displayMovieInfo(movie2);
return 0;
}
int main() {
DivisionData east = {"East"};
DivisionData west = {"West"};
DivisionData north = {"North"};
DivisionData south = {"South"};
getDivisionSales(east);
getDivisionSales(west);
getDivisionSales(north);
getDivisionSales(south);
calculateSales(east);
calculateSales(west);
calculateSales(north);
calculateSales(south);
displayDivisionSales(east);
displayDivisionSales(west);
displayDivisionSales(north);
displayDivisionSales(south);
return 0;
}
4. Weather Statistics
#include <iostream>
using namespace std;
struct WeatherData {
double totalRainfall;
double highTemperature;
double lowTemperature;
double averageTemperature;
};
double calculateAverageTemperature(double highTemp, double lowTemp) {
return (highTemp + lowTemp) / 2.0;
}
int main() {
const int numMonths = 12;
WeatherDatayearlyData[numMonths];
double totalYearlyRainfall = 0.0;
double highestTemp = -1000.0;
double lowestTemp = 1000.0;
double totalAverageTemperature = 0.0;
for (int i = 0; i<numMonths; ++i) {
cout<< "Enter weather data for month " << i+1 << ":" <<endl;
cout<< "Total Rainfall (in inches): ";
cin>>yearlyData[i].totalRainfall;
totalYearlyRainfall += yearlyData[i].totalRainfall;
cout<< "High Temperature (in Fahrenheit): ";
cin>>yearlyData[i].highTemperature;
if (yearlyData[i].highTemperature>highestTemp) {
highestTemp = yearlyData[i].highTemperature;
}
cout<< "Low Temperature (in Fahrenheit): ";
cin>>yearlyData[i].lowTemperature;
if (yearlyData[i].lowTemperature<lowestTemp) {
lowestTemp = yearlyData[i].lowTemperature;
}
yearlyData[i].averageTemperature =
calculateAverageTemperature(yearlyData[i].highTemperature,
yearlyData[i].lowTemperature);
totalAverageTemperature += yearlyData[i].averageTemperature;
}
double averageMonthlyRainfall = totalYearlyRainfall / numMonths;
double averageOfAverageTemperatures = totalAverageTemperature /
numMonths;
cout<< "\nWeather Summary:" <<endl;
cout<< "Average Monthly Rainfall: " <<averageMonthlyRainfall<< " inches"
<<endl;
cout<< "Total Yearly Rainfall: " <<totalYearlyRainfall<< " inches" <<endl;
cout<< "Highest Temperature for the Year: " <<highestTemp<< " Fahrenheit"
<<endl;
cout<< "Lowest Temperature for the Year: " <<lowestTemp<< " Fahrenheit"
<<endl;
cout<< "Average of Monthly Average Temperatures: "
<<averageOfAverageTemperatures<< " Fahrenheit" <<std::endl;
return 0;
}
6.Soccer Scores
#include <iostream>
#include <string>
using namespace std;
// Function prototypes
void inputData(Player players[], int size);
void displayData(const Player players[], int size);
int calculateTotalPoints(const Player players[], int size);
int findMaxPointsPlayer(const Player players[], int size);
int main() {
const int teamSize = 12;
Player players[teamSize];
return 0;
}
// Function prototypes
void inputData(CustomerAccount accounts[], int size);
void displayData(const CustomerAccount accounts[], int size);
void modifyAccount(CustomerAccount accounts[], int size);
int main() {
const int arraySize = 20;
CustomerAccount accounts[arraySize];
int choice;
do {
cout<< "\nCustomer Account Management System\n";
cout<< "1. Enter new account data\n";
cout<< "2. Display all account data\n";
cout<< "3. Modify account\n";
cout<< "4. Exit\n";
cout<< "Enter your choice: ";
cin>> choice;
switch (choice) {
case 1:
inputData(accounts, arraySize);
break;
case 2:
displayData(accounts, arraySize);
break;
case 3:
modifyAccount(accounts, arraySize);
break;
case 4:
cout<< "Exiting program.\n";
break;
default:
cout<< "Invalid choice. Please enter a number between 1 and 4.\n";
}
} while (choice != 4);
return 0;
}
// Function prototypes
void inputData(CustomerAccount accounts[], int size);
void displayData(const CustomerAccount accounts[], int size);
void modifyAccount(CustomerAccount accounts[], int size);
void searchAccount(const CustomerAccount accounts[], int size, const
string&partialName);
int main() {
const int arraySize = 20;
CustomerAccount accounts[arraySize];
int choice;
do {
cout<< "\nCustomer Account Management System\n";
cout<< "1. Enter new account data\n";
cout<< "2. Display all account data\n";
cout<< "3. Modify account\n";
cout<< "4. Search for account by name\n";
cout<< "5. Exit\n";
cout<< "Enter your choice: ";
cin>> choice;
switch (choice) {
case 1:
inputData(accounts, arraySize);
break;
case 2:
displayData(accounts, arraySize);
break;
case 3:
modifyAccount(accounts, arraySize);
break;
case 4: {
string partialName;
cout<< "Enter part of the customer's name to search: ";
cin>>partialName;
searchAccount(accounts, arraySize, partialName);
break;
}
case 5:
cout<< "Exiting program.\n";
break;
default:
cout<< "Invalid choice. Please enter a number between 1 and 5.\n";
}
} while (choice != 5);
return 0;
}
// Function prototypes
void inputData(Speaker speakers[], int size);
void displayData(const Speaker speakers[], int size);
void modifySpeaker(Speaker speakers[], int size);
int main() {
const int arraySize = 10;
Speaker speakers[arraySize];
int choice;
do {
cout<< "\nSpeakers' Bureau Management System\n";
cout<< "1. Enter new speaker data\n";
cout<< "2. Display all speaker data\n";
cout<< "3. Modify speaker data\n";
cout<< "4. Exit\n";
cout<< "Enter your choice: ";
cin>> choice;
switch (choice) {
case 1:
inputData(speakers, arraySize);
break;
case 2:
displayData(speakers, arraySize);
break;
case 3:
modifySpeaker(speakers, arraySize);
break;
case 4:
cout<< "Exiting program.\n";
break;
default:
cout<< "Invalid choice. Please enter a number between 1 and 4.\n";
}
} while (choice != 4);
return 0;
}
// Function prototypes
void inputData(Speaker speakers[], int size);
void displayData(const Speaker speakers[], int size);
void modifySpeaker(Speaker speakers[], int size);
void searchByTopic(const Speaker speakers[], int size, const string& keyword);
int main() {
const int arraySize = 10;
Speaker speakers[arraySize];
int choice;
do {
cout<< "\nSpeakers' Bureau Management System\n";
cout<< "1. Enter new speaker data\n";
cout<< "2. Display all speaker data\n";
cout<< "3. Modify speaker data\n";
cout<< "4. Search for speaker by topic\n";
cout<< "5. Exit\n";
cout<< "Enter your choice: ";
cin>> choice;
switch (choice) {
case 1:
inputData(speakers, arraySize);
break;
case 2:
displayData(speakers, arraySize);
break;
case 3:
modifySpeaker(speakers, arraySize);
break;
case 4: {
string keyword;
cout<< "Enter a keyword to search for in speaking topics: ";
cin>> keyword;
searchByTopic(speakers, arraySize, keyword);
break;
}
case 5:
cout<< "Exiting program.\n";
break;
default:
cout<< "Invalid choice. Please enter a number between 1 and 5.\n";
}
} while (choice != 5);
return 0;
}
// Function prototypes
void enterExpenses(MonthlyBudget& budget);
void displayReport(const MonthlyBudget& budget);
int main() {
MonthlyBudget budget;
return 0;
}
// Function prototypes
void inputStudentData(Student* students, int numStudents, int numTests);
void calculateAverage(Student* students, int numStudents, int numTests);
void calculateGrade(Student* students, int numStudents);
void displayStudentData(const Student* students, int numStudents);
int main() {
int numStudents, numTests;
// Calculate grade
calculateGrade(students, numStudents);
// Deallocate memory
for (int i = 0; i<numStudents; ++i) {
delete[] students[i].tests; // Deallocate the dynamically allocated array inside
each struct
}
delete[] students; // Deallocate the array of structures
return 0;
}
do {
displayMenu(drinks);
cout<< "Enter the number of the drink you want to purchase (1-5), or 0 to quit:
";
cin>> choice;
return 0;
}
// Function to initialize drinks with initial data
void initializeDrinks(Drink drinks[]) {
string names[] = {"Cola", "Root Beer", "Lemon-Lime", "Grape Soda",
"Cream Soda"};
double costs[] = {0.75, 0.75, 0.75, 0.80, 0.80};
int quantities[] = {20, 20, 20, 20, 20};
if (drinks[index].quantity<= 0) {
cout<< "Sorry, " << drinks[index].name << " is sold out.\n";
} else if (change < 0) {
cout<< "Insufficient amount. Please insert $" <<totalCost<< " or more.\n";
} else {
drinks[index].quantity--;
cout<< "You purchased a " << drinks[index].name << ". Your change is $" <<
change << ".\n";
return totalCost;
}
return 0.0;
}
if (numToAddOrRemove> 0) {
addParts(bins, selectedBin, numToAddOrRemove);
} else if (numToAddOrRemove< 0) {
removeParts(bins, selectedBin, -numToAddOrRemove);
}
} else if (choice != 0) {
cout<< "Invalid input. Please enter a number between 1 and 10, or 0 to quit.\n";
}
return 0;
}
void initializeBins(InventoryBin bins[]) {
string descriptions[] = {"Valve", "Bearing", "Bushing", "Coupling", "Flange",
"Gear", "Gear Housing", "Vacuum Gripper", "Cable",
"Rod"};
int initialCounts[] = {10, 5, 15, 21, 7, 5, 5, 25, 18, 12};
22.3:
a. struct Part{
int partNumber;
char partName[25];
};
b. typedef part * partptr
c. Part a;
Part b[ 10 ];
Part *ptr;
d. cin>>a.partNumber>>a.partName;
e. b[ 3 ] = a;
f. ptr = b;
g. cout<<( ptr + 3 )->partNumber<< ' '
cout<<( ptr + 3 )->partName<<endl;
----------------------------------------------------------------------------------------------