[go: up one dir, main page]

0% found this document useful (0 votes)
13 views77 pages

OOP Assignment f2023266160 Abdullah Farooq

Uploaded by

hifadi1393
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views77 pages

OOP Assignment f2023266160 Abdullah Farooq

Uploaded by

hifadi1393
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

UMT

OOP Assignment

Submitted to DR Nadeem AShraf

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.

2. Does a structure declaration cause a structure variable to be created ?

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.

4. Look at the following structure declaration.

struct Point {

int x; int y;

};

Write statements that

A) define a Point structure variable named center

B) assign 12 to the x member of center

C) assign 7 to the y member of center

D) display the contents of the x and y members of center


5. Look at the following structure declaration.

struct FullName {

char lastName[26];

char middleName[26];

char firstName[26];

};

Write statements that

A) Define a FullName structure variable named info

B) Assign your last, middle, and first name to the members of the info variable

C) Display the contents of the members of the info variable

Solution :

Code :

6. Look at the following 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 :

7. Look at the following code.

struct Town {

char townName[51];

char countyName[51];

double population;

double elevation;

};

Town t = { "Canton", "Haywood", 9478 };

A) What value is stored in t.townName?

t.townName=”Canton”;

B) What value is stored in t.countyName?

c.countyName=”Haywood”;

C) What value is stored in t.population?

t.population=9478;

D) What value is stored in t.elevation?

0
8. Look at the following code.
structure Rectangle {

int length;

int width;

};

Rectangle *r;

Write statements that

A) Dynamically allocate a Rectangle structure variable and use r to point to it.

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).

12. Look at the following declaration.


enum Person { BILL, JOHN, CLAIRE, BOB };

Person p;

Indicate whether each of the following statements or expressions is valid or invalid.

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++;

Invalid. Incrementing an enum variable directly is not allowed in C++.

C) BILL > BOB


Valid. Comparing enum values is allowed in C++. The result will depend on their underlying integer
values, which are assigned automatically by the compiler. In this case, BILL will be less than BOB since
BILL has the value 0 and BOB has the value 3.

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;

Valid. Enumerators can be implicitly converted to integers.

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.

G) cout<< CLAIRE <<endl;

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.

14. TheStructureTag is the name of the structure type.

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.

18. The Dot (.)operator allows you to access structure members.

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>

using namespace std;

struct car{

char carMake[20];

char carModel [20];

int yearModel;

double cost;

};

int main(){

car c;

strcpy(c.carMake,"Ford");

strcpy(c.carModel,"Mustang");

c.yearModel=1997;

c.cost= 20000;

cout<< "Car Make: " <<c.carMake<<endl;

cout<< "Car Model: " <<c.carModel<<endl;

cout<< "Year Model: " <<c.yearModel<<endl;

cout<< "Cost : $" <<c.cost<<endl;

20 :Define an array of 25 of the Car structure variables (the structure is declared in


Question 19).
#include<iostream>

#include<cstring>

using namespace std;

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;

cout<< "Car Make : " << c[0].carMake<<endl;

cout<< "Car Model : " << c[0].carModel<<endl;

cout<< "Year Model : " << c[0].yearModel<<endl;

cout<< "Cost : $" << c[0].cost <<endl;

21. Define an array of 35 of the Car structure variables.

Initialize the first three elements with the following data:

Make

Model

Year

Cost

(Ford Taurus 1997 $21,000 Honda Accord 1992 $11,000 Lamborghini Countach 1997 $200,000).
#include<iostream>

#include<cstring>

using namespace std;

struct car{

char carMake[20];

char carModel [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;

cout<<"For 2nd car "<<endl;

strcpy(cars[1].carMake,"Honda");

strcpy(cars[1].carModel,"Accord");

cars[1].yearModel=1994;

cars[1].cost= 1100;

cout<<"For 3rd car "<<endl;

strcpy(cars[2].carMake,"Lamborghini");

strcpy(cars[2].carModel,"Countach");

cars[2].yearModel=1997;

cars[2].cost= 200,000;

cout<< "Car Make : " << cars[0].carMake<<endl;

cout<< "Car Model : " << cars[0].carModel<<endl;

cout<< "Year Model : " << cars[0].yearModel<<endl;

cout<< "Cost : $"<< cars[0].cost <<endl;

cout<<"For 2nd car "<<endl;


cout<< "Car Make : " << cars[1].carMake<<endl;

cout<< "Car Model : " << cars[1].carModel<<endl;

cout<< "Year Model : " << cars[1].yearModel<<endl;

cout<< "Cost : $"<< cars[1].cost <<endl;

cout<<"For 3rd car "<<endl;

cout<< "Car Make : " << cars[2].carMake<<endl;

cout<< "Car Model : " << cars[2].carModel<<endl;

cout<< "Year Model : " << cars[2].yearModel<<endl;

cout<< "Cost : $"<< cars[2].cost <<endl;

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>

using namespace std;

struct Car {

char carMake[20];

char carModel[20];
int yearModel;

double cost;

};

int main() {

Car cars[25];

for (int i = 0; i< 25; ++i) {

strcpy(cars[i].carMake, "Ford");

strcpy(cars[i].carModel, "Mustang");

cars[i].yearModel = 1997;

cars[i].cost = 20000.0;

for (int i = 0; i< 25; ++i) {

cout<< "Car " <<i + 1 <<":\n";

cout<< "Car Make: " << cars[i].carMake<<endl;

cout<< "Car Model: " << cars[i].carModel<<endl;

cout<< "Year Model: " << cars[i].yearModel<<endl;

cout<< "Cost: $" << cars[i].cost<<endl<<endl;

return 0;

23. Declare a structure named TempScale , with the following members:

fahrenheit: a double

centigrade: a double

Next, declare a structure named Reading, with the following members:


windSpeed:

an int humidity:

a double temperature:

a TempScale structure variable Next define a Reading structure variable.


#include<iostream>

using namespace std;

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;

currentReading.temperature.centigrade = (currentReading.temperature.fahrenheit - 32.0) * 5.0 / 9.0;

cout<< "Current Reading:\n";

cout<< "Wind Speed: " <<currentReading.windSpeed<< " mph\n";

cout<< "Humidity: " <<currentReading.humidity<< "\n";

cout<< "Temperature (Fahrenheit): " <<currentReading.temperature.fahrenheit<< " \n";

cout<< "Temperature (Centigrade): " <<currentReading.temperature.centigrade<< " \n";

return 0;}
24. Write statements that will store the following data in the variable you defined in Question 23.

Wind Speed: 37 mph;

Humidity: 32%;

Fahrenheit temperature: 32 degrees;

Centigrade temperature: 0 degrees;


#include<iostream>

using namespace std;

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

currentReading.temperature.centigrade = (currentReading.temperature.fahrenheit - 32.0) * 5.0 / 9.0;

cout<< "Current Reading:\n";

cout<< "Wind Speed: " <<currentReading.windSpeed<< " mph\n";

cout<< "Humidity: " <<currentReading.humidity<< "\n";

cout<< "Temperature (Fahrenheit): " <<currentReading.temperature.fahrenheit<< " F\n";

cout<< "Temperature (Centigrade): " <<currentReading.temperature.centigrade<< " C\n";

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>

using namespace std;

struct TempScale {

double fahrenheit;

double centigrade;

};

struct Reading {

int windSpeed;

double humidity;

TempScale temperature;

};

void showReading(Reading r) {

cout<< "Wind Speed: " <<r.windSpeed<< " mph\n";

cout<< "Humidity: " <<r.humidity * 100 << "%\n";

cout<< "Temperature (Fahrenheit): " <<r.temperature.fahrenheit<< " F\n";

cout<< "Temperature (Centigrade): " <<r.temperature.centigrade<< " C\n";

int main() {

Reading currentReading;

currentReading.windSpeed = 37;

currentReading.humidity = 0.32;

currentReading.temperature.fahrenheit = 32.0;

currentReading.temperature.centigrade = (currentReading.temperature.fahrenheit - 32.0) * 5.0 / 9.0;

cout<< "Current Reading:\n";

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>

using namespace std;

struct TempScale {

double fahrenheit;

double centigrade;

};

struct Reading {

int windSpeed;

double humidity;

TempScale temperature;

};

void findReading(Reading& r) {

cout<< "Enter Wind Speed (mph): ";

cin>>r.windSpeed;

cout<< "Enter Humidity (%): ";

cin>>r.humidity;

cout<< "Enter Temperature (Fahrenheit): ";

cin>>r.temperature.fahrenheit;

r.temperature.centigrade = (r.temperature.fahrenheit - 32.0) * 5.0 / 9.0;

int main() {

Reading currentReading;

findReading(currentReading);

cout<< "\nCurrent Reading:\n";

cout<< "Wind Speed: " <<currentReading.windSpeed<< " mph\n";

cout<< "Humidity: " <<currentReading.humidity<< "%\n";

cout<< "Temperature (Fahrenheit): " <<currentReading.temperature.fahrenheit<< " F\n";

cout<< "Temperature (Centigrade): " <<currentReading.temperature.centigrade<< " C\n";

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>

using namespace std;

struct TempScale {

double fahrenheit;

double centigrade;

};

struct Reading {

int windSpeed;

double humidity;

TempScale temperature;

};

Reading getReading() {

Reading r;

cout<< "Enter Wind Speed (mph): ";

cin>>r.windSpeed;

cout<< "Enter Humidity (%): ";

cin>>r.humidity;

cout<< "Enter Temperature (Fahrenheit): ";

cin>>r.temperature.fahrenheit;

r.temperature.centigrade = (r.temperature.fahrenheit - 32.0) * 5.0 / 9.0;

return r;

int main() {

Reading currentReading = getReading();

cout<< "\nCurrent Reading:\n";

cout<< "Wind Speed: " <<currentReading.windSpeed<< " mph\n";

cout<< "Humidity: " <<currentReading.humidity<< "%\n";

cout<< "Temperature (Fahrenheit): " <<currentReading.temperature.fahrenheit<< " F\n";

cout<< "Temperature (Centigrade): " <<currentReading.temperature.centigrade<< " C\n";

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>

using namespace std;

struct TempScale {

double fahrenheit;

double centigrade;

};

struct Reading {

int windSpeed;

double humidity;

TempScale temperature;

};

void recordReading(Reading* r) {

cout<< "Enter Wind Speed (mph): ";

cin>> (*r).windSpeed;

cout<< "Enter Humidity (%): ";

cin>> (*r).humidity;

cout<< "Enter Temperature (Fahrenheit): ";

cin>> (*r).temperature.fahrenheit;

(*r).temperature.centigrade = ((*r).temperature.fahrenheit - 32.0) * 5.0 / 9.0;

int main() {

Reading currentReading;

recordReading(&currentReading);
cout<< "\nCurrent Reading:\n";

cout<< "Wind Speed: " <<currentReading.windSpeed<< " mph\n";

cout<< "Humidity: " <<currentReading.humidity<< "%\n";

cout<< "Temperature (Fahrenheit): " <<currentReading.temperature.fahrenheit<< " F\n";

cout<< "Temperature (Centigrade): " <<currentReading.temperature.centigrade<< " C\n";

return 0;

29. Rewrite the following statement using the structure pointer operator:
(*rptr).windSpeed = 50;
#include <iostream>

using namespace std;

struct Reading {

int windSpeed;

};

int main() {

Reading* rptr = new Reading;

(*rptr).windSpeed = 50;

cout<< "Wind Speed: " << (*rptr).windSpeed<< " mph\n";

return 0;

}
30. Rewrite the following statement using the structure pointer operator:
*(*strPtr).num = 10;
#include <iostream>

using namespace std;

struct Structure {

int num;

};

int main() {

Structure* strPtr = new Structure;

(*strPtr).num= 10;

cout<< "Number: " << (*strPtr).num <<endl;

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.

57. struct { int x; float y; };

(Missing struct name)

58. struct Values { char name[30]; int age; }

Missing semicolon after structure definition.

59. struct TwoVals {

int a, b;

};

int main () {

TwoVals.a = 10;

TwoVals.b = 20;

return 0;

Incorrect usage of structure member access.


60.

#include<iostream>

using namespace std;

struct ThreeVals {

int a, b, c;

};

int main() {

ThreeValsvals = {1, 2, 3};

cout<<vals<<endl;

cout<<vals.a<< " " <<vals.b<< " " <<vals.c<<endl; // Corrected

return 0;

Attempting to output the entire structure using cout directly


61. #include<iostream>

using namespace std;

struct names {

char first[20];

char last[20];

};

int main () {

names customer = "Smith", "Orley";

cout<<names.first<<endl; cout<<names.last<<endl;

Names customer = {"Smith", "Orley"}; // Corrected

return 0;

62. struct FourVals {

int a, b, c, d;

};

int main () {

FourValsnums = {1, 2, , 4};

FourValsnums = {1, 2, 3, 4}; // Corrected

return 0;

63. #include<iostream>

using namespace std;

struct TwoVals {

int a = 5;

int b = 10;

};

int main(){

TwoVals v = {5, 10}; // Corrected

TwoVals v; cout<<v.a<< " " <<v.b;

return 0;
}

64:

struct TwoVals {

int a;

int b;

};

int main() {

TwoValsvarray[10];

varray[0].a = 1; // Corrected

return 0;

65. struct TwoVals {

int a;

int b;

};

TwoValsgetVals() {

TwoVals.a = TwoVals.b = 0;

return temp; // Corrected

66. struct ThreeVals {

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;
}

3. Corporate Sales Data


#include <iostream>
using namespace std;
struct DivisionData {
string divisionName;
double firstQuarterSales;
double secondQuarterSales;
double thirdQuarterSales;
double fourthQuarterSales;
double totalAnnualSales;
double averageQuarterlySales;
};
void calculateSales(DivisionData&division) {
division.totalAnnualSales = division.firstQuarterSales +
division.secondQuarterSales +
division.thirdQuarterSales + division.fourthQuarterSales;
division.averageQuarterlySales = division.totalAnnualSales / 4.0;
}
void getDivisionSales(DivisionData&division) {
cout<< "Enter sales figures for the " <<division.divisionName<< " division:"
<<endl;
cout<< "First Quarter Sales: ";
cin>>division.firstQuarterSales;
cout<< "Second Quarter Sales: ";
cin>>division.secondQuarterSales;
cout<< "Third Quarter Sales: ";
cin>>division.thirdQuarterSales;
cout<< "Fourth Quarter Sales: ";
cin>>division.fourthQuarterSales;
if (division.firstQuarterSales< 0 || division.secondQuarterSales< 0 ||
division.thirdQuarterSales< 0 || division.fourthQuarterSales< 0) {
cout<< "Error: Sales figures cannot be negative." <<endl;
}
}
void displayDivisionSales(DivisionData&division) {
cout<< "Division Name: " <<division.divisionName<<endl;
cout<< "First Quarter Sales: $" <<division.firstQuarterSales<<endl;
cout<< "Second Quarter Sales: $" <<division.secondQuarterSales<<endl;
cout<< "Third Quarter Sales: $" <<division.thirdQuarterSales<<endl;
cout<< "Fourth Quarter Sales: $" <<division.fourthQuarterSales<<endl;
cout<< "Total Annual Sales: $" <<division.totalAnnualSales<<endl;
cout<< "Average Quarterly Sales: $"
<<division.averageQuarterlySales<<endl;
cout<<endl;
}

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;

// Structure for soccer player


struct Player {
string name;
int number;
int pointsScored;
};

// 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];

// Input data for each player


inputData(players, teamSize);

// Display data for each player


displayData(players, teamSize);

// Calculate and display total points earned by the team


int totalPoints = calculateTotalPoints(players, teamSize);
cout<< "Total points earned by the team: " <<totalPoints<<endl;

// Find and display the player with the most points


int maxPointsPlayerIndex = findMaxPointsPlayer(players, teamSize);
cout<< "Player with the most points:\n";
cout<< "Name: " << players[maxPointsPlayerIndex].name <<endl;
cout<< "Number: " << players[maxPointsPlayerIndex].number<<endl;
cout<< "Points Scored: " <<
players[maxPointsPlayerIndex].pointsScored<<endl;

return 0;
}

// Function to input data for each player


void inputData(Player players[], int size) {
for (int i = 0; i< size; ++i) {
cout<< "Enter details for player " << i+1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, players[i].name);
cout<< "Number: ";
cin>> players[i].number;
while (players[i].number< 0) {
cout<< "Please enter a non-negative number: ";
cin>> players[i].number;
}
cout<< "Points Scored: ";
cin>> players[i].pointsScored;
while (players[i].pointsScored< 0) {
cout<< "Please enter a non-negative number: ";
cin>> players[i].pointsScored;
}
cout<<endl;
}
}

// Function to display data for each player


void displayData(const Player players[], int size) {
cout<< "Player Number\tPlayer Name\tPoints Scored\n";
for (int i = 0; i< size; ++i) {
cout<< players[i].number<< "\t\t" << players[i].name << "\t\t" <<
players[i].pointsScored<<endl;
}
cout<<endl;
}

// Function to calculate total points earned by the team


int calculateTotalPoints(const Player players[], int size) {
int totalPoints = 0;
for (int i = 0; i< size; ++i) {
totalPoints += players[i].pointsScored;
}
return totalPoints;
}

// Function to find the player with the most points


int findMaxPointsPlayer(const Player players[], int size) {
int maxPoints = players[0].pointsScored;
int maxPointsIndex = 0;
for (int i = 1; i< size; ++i) {
if (players[i].pointsScored>maxPoints) {
maxPoints = players[i].pointsScored;
maxPointsIndex = i;
}
}
return maxPointsIndex;
}
7. Customer Accounts
#include <iostream>
#include <string>

using namespace std;

// Structure for customer account


struct CustomerAccount {
string name;
string address;
string cityStateZIP;
string telephoneNumber;
double accountBalance;
string dateOfLastPayment;
};

// 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 to input data for a new account


void inputData(CustomerAccount accounts[], int size) {
for (int i = 0; i< size; ++i) {
cout<< "\nEnter details for account " <<i + 1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, accounts[i].name);
cout<< "Address: ";
getline(cin>>ws, accounts[i].address);
cout<< "City, State, ZIP: ";
getline(cin>>ws, accounts[i].cityStateZIP);
cout<< "Telephone Number: ";
getline(cin>>ws, accounts[i].telephoneNumber);
cout<< "Account Balance: $";
cin>> accounts[i].accountBalance;
while (accounts[i].accountBalance< 0) {
cout<< "Please enter a non-negative account balance: $";
cin>> accounts[i].accountBalance;
}
cout<< "Date of Last Payment: ";
getline(cin>>ws, accounts[i].dateOfLastPayment);
}
}
// Function to display all account data
void displayData(const CustomerAccount accounts[], int size) {
cout<< "\nCustomer Account Data:\n";
cout<< "---------------------------------------------\n";
for (int i = 0; i< size; ++i) {
cout<< "Account " <<i + 1 <<":\n";
cout<< "Name: " << accounts[i].name <<endl;
cout<< "Address: " << accounts[i].address<<endl;
cout<< "City, State, ZIP: " << accounts[i].cityStateZIP<<endl;
cout<< "Telephone Number: " << accounts[i].telephoneNumber<<endl;
cout<< "Account Balance: $" << accounts[i].accountBalance<<endl;
cout<< "Date of Last Payment: " << accounts[i].dateOfLastPayment<<endl;
cout<< "---------------------------------------------\n";
}
}

// Function to modify account data


void modifyAccount(CustomerAccount accounts[], int size) {
int accountNumber;
cout<< "Enter the account number to modify (1-" << size << "): ";
cin>>accountNumber;
if (accountNumber< 1 || accountNumber> size) {
cout<< "Invalid account number.\n";
return;
}
accountNumber--; // Adjust index
cout<< "Enter new details for account " <<accountNumber + 1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, accounts[accountNumber].name);
cout<< "Address: ";
getline(cin>>ws, accounts[accountNumber].address);
cout<< "City, State, ZIP: ";
getline(cin>>ws, accounts[accountNumber].cityStateZIP);
cout<< "Telephone Number: ";
getline(cin>>ws, accounts[accountNumber].telephoneNumber);
cout<< "Account Balance: $";
cin>> accounts[accountNumber].accountBalance;
while (accounts[accountNumber].accountBalance< 0) {
cout<< "Please enter a non-negative account balance: $";
cin>> accounts[accountNumber].accountBalance;
}
cout<< "Date of Last Payment: ";
getline(cin>>ws, accounts[accountNumber].dateOfLastPayment);
}
8. Search Function for Customer Accounts Program
#include <iostream>
#include <string>

using namespace std;

// Structure for customer account


struct CustomerAccount {
string name;
string address;
string cityStateZIP;
string telephoneNumber;
double accountBalance;
string dateOfLastPayment;
};

// 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 to input data for a new account


void inputData(CustomerAccount accounts[], int size) {
for (int i = 0; i< size; ++i) {
cout<< "\nEnter details for account " <<i + 1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, accounts[i].name);
cout<< "Address: ";
getline(cin>>ws, accounts[i].address);
cout<< "City, State, ZIP: ";
getline(cin>>ws, accounts[i].cityStateZIP);
cout<< "Telephone Number: ";
getline(cin>>ws, accounts[i].telephoneNumber);
cout<< "Account Balance: $";
cin>> accounts[i].accountBalance;
while (accounts[i].accountBalance< 0) {
cout<< "Please enter a non-negative account balance: $";
cin>> accounts[i].accountBalance;
}
cout<< "Date of Last Payment: ";
getline(cin>>ws, accounts[i].dateOfLastPayment);
}
}

// Function to display all account data


void displayData(const CustomerAccount accounts[], int size) {
cout<< "\nCustomer Account Data:\n";
cout<< "---------------------------------------------\n";
for (int i = 0; i< size; ++i) {
cout<< "Account " <<i + 1 <<":\n";
cout<< "Name: " << accounts[i].name <<endl;
cout<< "Address: " << accounts[i].address<<endl;
cout<< "City, State, ZIP: " << accounts[i].cityStateZIP<<endl;
cout<< "Telephone Number: " << accounts[i].telephoneNumber<<endl;
cout<< "Account Balance: $" << accounts[i].accountBalance<<endl;
cout<< "Date of Last Payment: " << accounts[i].dateOfLastPayment<<endl;
cout<< "---------------------------------------------\n";
}
}

// Function to modify account data


void modifyAccount(CustomerAccount accounts[], int size) {
int accountNumber;
cout<< "Enter the account number to modify (1-" << size << "): ";
cin>>accountNumber;
if (accountNumber< 1 || accountNumber> size) {
cout<< "Invalid account number.\n";
return;
}
accountNumber--; // Adjust index
cout<< "Enter new details for account " <<accountNumber + 1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, accounts[accountNumber].name);
cout<< "Address: ";
getline(cin>>ws, accounts[accountNumber].address);
cout<< "City, State, ZIP: ";
getline(cin>>ws, accounts[accountNumber].cityStateZIP);
cout<< "Telephone Number: ";
getline(cin>>ws, accounts[accountNumber].telephoneNumber);
cout<< "Account Balance: $";
cin>> accounts[accountNumber].accountBalance;
while (accounts[accountNumber].accountBalance< 0) {
cout<< "Please enter a non-negative account balance: $";
cin>> accounts[accountNumber].accountBalance;
}
cout<< "Date of Last Payment: ";
getline(cin>>ws, accounts[accountNumber].dateOfLastPayment);
}

// Function to search for an account by partial name match


void searchAccount(const CustomerAccount accounts[], int size, const
string&partialName) {
bool found = false;
cout<< "\nMatching Accounts:\n";
cout<< "---------------------------------------------\n";
for (int i = 0; i< size; ++i) {
if (accounts[i].name.find(partialName) != string::npos) {
cout<< "Account " <<i + 1 <<":\n";
cout<< "Name: " << accounts[i].name <<endl;
cout<< "Address: " << accounts[i].address<<endl;
cout<< "City, State, ZIP: " << accounts[i].cityStateZIP<<endl;
cout<< "Telephone Number: " << accounts[i].telephoneNumber<<endl;
cout<< "Account Balance: $" << accounts[i].accountBalance<<endl;
cout<< "Date of Last Payment: " << accounts[i].dateOfLastPayment<<endl;
cout<< "---------------------------------------------\n";
found = true;
}
}
if (!found) {
cout<< "No accounts match the search criteria.\n";
}
}
9. Speakers’ Bureau
#include <iostream>
#include <string>

using namespace std;

// Structure for speaker


struct Speaker {
string name;
string telephoneNumber;
string speakingTopic;
double feeRequired;
};

// 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 to input data for a new speaker


void inputData(Speaker speakers[], int size) {
for (int i = 0; i< size; ++i) {
cout<< "\nEnter details for speaker " <<i + 1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, speakers[i].name);
cout<< "Telephone Number: ";
getline(cin>>ws, speakers[i].telephoneNumber);
cout<< "Speaking Topic: ";
getline(cin>>ws, speakers[i].speakingTopic);
cout<< "Fee Required: $";
cin>> speakers[i].feeRequired;
while (speakers[i].feeRequired< 0) {
cout<< "Please enter a non-negative fee: $";
cin>> speakers[i].feeRequired;
}
}
}

// Function to display all speaker data


void displayData(const Speaker speakers[], int size) {
cout<< "\nSpeaker Data:\n";
cout<< "---------------------------------------------\n";
for (int i = 0; i< size; ++i) {
cout<< "Speaker " <<i + 1 <<":\n";
cout<< "Name: " << speakers[i].name <<endl;
cout<< "Telephone Number: " << speakers[i].telephoneNumber<<endl;
cout<< "Speaking Topic: " << speakers[i].speakingTopic<<endl;
cout<< "Fee Required: $" << speakers[i].feeRequired<<endl;
cout<< "---------------------------------------------\n";
}
}

// Function to modify speaker data


void modifySpeaker(Speaker speakers[], int size) {
int speakerNumber;
cout<< "Enter the speaker number to modify (1-" << size << "): ";
cin>>speakerNumber;
if (speakerNumber< 1 || speakerNumber> size) {
cout<< "Invalid speaker number.\n";
return;
}
speakerNumber--; // Adjust index
cout<< "Enter new details for speaker " <<speakerNumber + 1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, speakers[speakerNumber].name);
cout<< "Telephone Number: ";
getline(cin>>ws, speakers[speakerNumber].telephoneNumber);
cout<< "Speaking Topic: ";
getline(cin>>ws, speakers[speakerNumber].speakingTopic);
cout<< "Fee Required: $";
cin>> speakers[speakerNumber].feeRequired;
while (speakers[speakerNumber].feeRequired< 0) {
cout<< "Please enter a non-negative fee: $";
cin>> speakers[speakerNumber].feeRequired;
}
}

10. Search Function for the Speakers’ Bureau Program


#include <iostream>
#include <string>

using namespace std;


// Structure for speaker
struct Speaker {
string name;
string telephoneNumber;
string speakingTopic;
double feeRequired;
};

// 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 to input data for a new speaker


void inputData(Speaker speakers[], int size) {
for (int i = 0; i< size; ++i) {
cout<< "\nEnter details for speaker " <<i + 1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, speakers[i].name);
cout<< "Telephone Number: ";
getline(cin>>ws, speakers[i].telephoneNumber);
cout<< "Speaking Topic: ";
getline(cin>>ws, speakers[i].speakingTopic);
cout<< "Fee Required: $";
cin>> speakers[i].feeRequired;
while (speakers[i].feeRequired< 0) {
cout<< "Please enter a non-negative fee: $";
cin>> speakers[i].feeRequired;
}
}
}

// Function to display all speaker data


void displayData(const Speaker speakers[], int size) {
cout<< "\nSpeaker Data:\n";
cout<< "---------------------------------------------\n";
for (int i = 0; i< size; ++i) {
cout<< "Speaker " <<i + 1 <<":\n";
cout<< "Name: " << speakers[i].name <<endl;
cout<< "Telephone Number: " << speakers[i].telephoneNumber<<endl;
cout<< "Speaking Topic: " << speakers[i].speakingTopic<<endl;
cout<< "Fee Required: $" << speakers[i].feeRequired<<endl;
cout<< "---------------------------------------------\n";
}
}

// Function to modify speaker data


void modifySpeaker(Speaker speakers[], int size) {
int speakerNumber;
cout<< "Enter the speaker number to modify (1-" << size << "): ";
cin>>speakerNumber;
if (speakerNumber< 1 || speakerNumber> size) {
cout<< "Invalid speaker number.\n";
return;
}
speakerNumber--; // Adjust index
cout<< "Enter new details for speaker " <<speakerNumber + 1 <<":\n";
cout<< "Name: ";
getline(cin>>ws, speakers[speakerNumber].name);
cout<< "Telephone Number: ";
getline(cin>>ws, speakers[speakerNumber].telephoneNumber);
cout<< "Speaking Topic: ";
getline(cin>>ws, speakers[speakerNumber].speakingTopic);
cout<< "Fee Required: $";
cin>> speakers[speakerNumber].feeRequired;
while (speakers[speakerNumber].feeRequired< 0) {
cout<< "Please enter a non-negative fee: $";
cin>> speakers[speakerNumber].feeRequired;
}
}

// Function to search for speakers by topic


void searchByTopic(const Speaker speakers[], int size, const string& keyword)
{
bool found = false;
cout<< "\nMatching Speakers:\n";
cout<< "---------------------------------------------\n";
for (int i = 0; i< size; ++i) {
if (speakers[i].speakingTopic.find(keyword) != string::npos) {
cout<< "Speaker " <<i + 1 <<":\n";
cout<< "Name: " << speakers[i].name <<endl;
cout<< "Telephone Number: " << speakers[i].telephoneNumber<<endl;
cout<< "Speaking Topic: " << speakers[i].speakingTopic<<endl;
cout<< "Fee Required: $" << speakers[i].feeRequired<<endl;
cout<< "---------------------------------------------\n";
found = true;
}
}
if (!found) {
cout<< "No speakers match the search criteria.\n";
}
}

11. Monthly Budge


#include <iostream>
#include <string>

using namespace std;

// Structure for monthly budget


struct MonthlyBudget {
double housing;
double utilities;
double householdExpenses;
double transportation;
double food;
double medical;
double insurance;
double entertainment;
double clothing;
double miscellaneous;
};

// Function prototypes
void enterExpenses(MonthlyBudget& budget);
void displayReport(const MonthlyBudget& budget);

int main() {
MonthlyBudget budget;

// Prompt the user to enter expenses


enterExpenses(budget);

// Display the report


displayReport(budget);

return 0;
}

// Function to enter expenses


void enterExpenses(MonthlyBudget& budget) {
cout<< "Enter the amounts spent in each budget category during the month:\n";
cout<< "Housing: ";
cin>>budget.housing;
cout<< "Utilities: ";
cin>>budget.utilities;
cout<< "Household Expenses: ";
cin>>budget.householdExpenses;
cout<< "Transportation: ";
cin>>budget.transportation;
cout<< "Food: ";
cin>>budget.food;
cout<< "Medical: ";
cin>>budget.medical;
cout<< "Insurance: ";
cin>>budget.insurance;
cout<< "Entertainment: ";
cin>>budget.entertainment;
cout<< "Clothing: ";
cin>>budget.clothing;
cout<< "Miscellaneous: ";
cin>>budget.miscellaneous;
}

// Function to display the report


void displayReport(const MonthlyBudget& budget) {
double totalBudget = budget.housing + budget.utilities +
budget.householdExpenses +
budget.transportation + budget.food + budget.medical +
budget.insurance + budget.entertainment + budget.clothing +
budget.miscellaneous;
double totalExpenses = budget.housing + budget.utilities +
budget.householdExpenses +
budget.transportation + budget.food + budget.medical +
budget.insurance + budget.entertainment + budget.clothing +
budget.miscellaneous;

cout<< "\nBudget Report:\n";


cout<< "----------------------------------------------\n";
cout<< "Category Budget Expenses\n";
cout<< "----------------------------------------------\n";
cout<< "Housing $500.00 $" <<budget.housing<<endl;
cout<< "Utilities $150.00 $" <<budget.utilities<<endl;
cout<< "Household Expenses $65.00 $"
<<budget.householdExpenses<<endl;
cout<< "Transportation $50.00 $" <<budget.transportation<< endl;
cout<< "Food $250.00 $" <<budget.food<<endl;
cout<< "Medical $30.00 $" <<budget.medical<<endl;
cout<< "Insurance $100.00 $" <<budget.insurance<<endl;
cout<< "Entertainment $150.00 $" <<budget.entertainment<<endl;
cout<< "Clothing $75.00 $" <<budget.clothing<<endl;
cout<< "Miscellaneous $50.00 $" <<budget.miscellaneous<<endl;
cout<< "----------------------------------------------\n";
cout<< "Total Monthly Budget: $" <<totalBudget<<endl;
cout<< "Total Monthly Expenses: $" <<totalExpenses<<endl;
double difference = totalExpenses - totalBudget;
if (difference >= 0) {
cout<< "You are over budget by: $" << difference <<endl;
} else {
cout<< "You are under budget by: $" << -difference <<endl;
}
cout<< "----------------------------------------------\n";
}

12. Course Grade


#include <iostream>
#include <string>

using namespace std;

// Structure for student


struct Student {
string name;
int idNum;
int* tests;
double average;
char grade;
};

// 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;

cout<< "Enter the number of students: ";


cin>>numStudents;

cout<< "Enter the number of tests: ";


cin>>numTests;

// Dynamically allocate an array of structures


Student* students = new Student[numStudents];

// Input student data


inputStudentData(students, numStudents, numTests);
// Calculate average test score
calculateAverage(students, numStudents, numTests);

// Calculate grade
calculateGrade(students, numStudents);

// Display student data


displayStudentData(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;
}

// Function to input student data


void inputStudentData(Student* students, int numStudents, int numTests) {
for (int i = 0; i<numStudents; ++i) {
cout<< "\nEnter details for student " <<i + 1 <<":\n";
cout<< "Name: ";
cin>> students[i].name;
cout<< "ID Number: ";
cin>> students[i].idNum;
// Dynamically allocate an array for tests
students[i].tests = new int[numTests];

// Input test scores


for (int j = 0; j <numTests; ++j) {
do {
cout<< "Enter test " << j + 1 << " score (positive integer): ";
cin>> students[i].tests[j];
} while (students[i].tests[j] < 0);
}
}
}

// Function to calculate average test score


void calculateAverage(Student* students, int numStudents, int numTests) {
for (int i = 0; i<numStudents; ++i) {
int sum = 0;
for (int j = 0; j <numTests; ++j) {
sum += students[i].tests[j];
}
students[i].average = static_cast<double>(sum) / numTests;
}
}

// Function to calculate grade


void calculateGrade(Student* students, int numStudents) {
for (int i = 0; i<numStudents; ++i) {
if (students[i].average>= 91) {
students[i].grade = 'A';
} else if (students[i].average>= 81) {
students[i].grade = 'B';
} else if (students[i].average>= 71) {
students[i].grade = 'C';
} else if (students[i].average>= 61) {
students[i].grade = 'D';
} else {
students[i].grade = 'F';
}
}
}

// Function to display student data


void displayStudentData(const Student* students, int numStudents) {
cout<< "\nStudent Data:\n";
cout<< "-----------------------------------------------\n";
cout<< "Name\tID Number\tAverage\tGrade\n";
cout<< "-----------------------------------------------\n";
for (int i = 0; i<numStudents; ++i) {
cout<< students[i].name << "\t" << students[i].idNum<< "\t\t";
cout<< students[i].average<< "\t" << students[i].grade <<endl;
}
cout<< "-----------------------------------------------\n";
}
13. Drink Machine Simulator
#include <iostream>
#include <iomanip>
using namespace std;
// Structure for drinks
struct Drink {
string name;
double cost;
int quantity;
};
// Function prototypes
void initializeDrinks(Drink drinks[]);
void displayMenu(const Drink drinks[]);
double processPurchase(Drink drinks[], int choice, double amountInserted);
int main() {
Drink drinks[5];
double totalRevenue = 0.0;
double amountInserted;
int choice;
initializeDrinks(drinks);

do {
displayMenu(drinks);
cout<< "Enter the number of the drink you want to purchase (1-5), or 0 to quit:
";
cin>> choice;

if (choice >= 1 && choice <= 5) {


cout<< "Enter the amount of money you want to insert (up to $1.00): ";
cin>>amountInserted;

if (amountInserted< 0 || amountInserted> 1.00) {


cout<< "Invalid amount. Please enter a value between 0 and 1.00.\n";
} else {
totalRevenue += processPurchase(drinks, choice, amountInserted);
}
} else if (choice != 0) {
cout<< "Invalid choice. Please enter a number between 1 and 5, or 0 to quit.\n";
}

} while (choice != 0);

cout<< fixed <<setprecision(2);


cout<< "Total revenue earned: $" <<totalRevenue<<endl;

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};

for (int i = 0; i< 5; ++i) {


drinks[i].name = names[i];
drinks[i].cost = costs[i];
drinks[i].quantity = quantities[i];
}
}

// Function to display the drink menu


void displayMenu(const Drink drinks[]) {
cout<< "Soft Drink Machine Menu:\n";
for (int i = 0; i< 5; ++i) {
cout<< i+1 << ". " << drinks[i].name << " - $" << drinks[i].cost<< " (" <<
drinks[i].quantity << " available)\n";
}
}

// Function to process a purchase


double processPurchase(Drink drinks[], int choice, double amountInserted) {
int index = choice - 1;
double totalCost = drinks[index].cost;
double change = amountInserted - totalCost;

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;
}

14. Inventory Bins.


#include <iostream>
using namespace std;
struct InventoryBin {
string description;
int numParts;
};
void initializeBins(InventoryBin bins[]);
void displayBins(const InventoryBin bins[]);
void addParts(InventoryBin bins[], int binIndex, int numToAdd);
void removeParts(InventoryBin bins[], int binIndex, int numToRemove);
int main() {
InventoryBinbins[10];
int choice;
int selectedBin;
int numToAddOrRemove;
initializeBins(bins);
do {
cout<< "Current Inventory:\n";
displayBins(bins);
cout<< "Enter the number of the bin to add/remove parts (1-10), or 0 to quit: ";
cin>> choice;

if (choice >= 1 && choice <= 10) {


selectedBin = choice - 1;
cout<< "Enter the number of parts to add (positive) or remove (negative): ";
cin>>numToAddOrRemove;

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";
}

} while (choice != 0);

cout<< "Exiting program.\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};

for (int i = 0; i< 10; ++i) {


bins[i].description = descriptions[i];
bins[i].numParts = initialCounts[i];
}
}
void displayBins(const InventoryBin bins[]) {
cout<< "Bin\tDescription\t\tNum Parts\n";
for (int i = 0; i< 10; ++i) {
cout<< i+1 << "\t" << bins[i].description<< "\t\t\t" << bins[i].numParts<<endl;
}
}
void addParts(InventoryBin bins[], int binIndex, int numToAdd) {
if (bins[binIndex].numParts + numToAdd> 30) {
cout<< "Cannot add more parts than the bin can hold.\n";
} else {
bins[binIndex].numParts += numToAdd;
cout<< "Added " <<numToAdd<< " parts to " << bins[binIndex].description<<
" bin.\n";
}
}
void removeParts(InventoryBin bins[], int binIndex, int numToRemove) {
if (bins[binIndex].numParts - numToRemove< 0) {
cout<< "Cannot remove more parts than are in the bin.\n";
} else {
bins[binIndex].numParts -= numToRemove;
cout<< "Removed " <<numToRemove<< " parts from " <<
bins[binIndex].description<< " bin.\n";
}
}
Exercise (Deitel and Deitel)
22.1:Fill in the blanks:
a. Structure
c. data members
e. struct
i. dot operator(.) or arrow operator (->)

22.2: True or False:


a. F b. F d. F

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;

22.4: Error Finding:


a. The parentheses that should enclose *cPtr have been omitted, causing the
order of evaluation of the expression to be incorrect.
b. The array subscript has been omitted. The expression should be hearts
[10].face.
c. A semicolon is required to end a structure definition.
d. Variables of different structure types cannot be assigned to one another.

22.6: Definition of Structures:


a. struct Inventory {
char partName[30];
int partNumber;
float price;
int stock;
int reorder;
};
b. struct Address {
char streetAddress[25];
char city[20];
char state[3];
char zipCode[6];
};
c. struct Student {
char firstName[15];
char lastName[15];
Address homeAddress;
};
22.7:
a. customerRecord.lastName
b. customerPtr->lastName
c. customerRecord.firstName
d. customerPtr->firstName
e. customerRecord.customerNumber
f. customerPtr->customerNumber
g. customerRecord.personal.phoneNumber
h. customerPtr->personal.phoneNumber
i. customerRecord.personal.address
j. customerPtr->personal.address
k. customerRecord.personal.city
l. customerPtr->personal.city
m. customerRecord.personal.state
n. customerPtr->personal.state
o. customerRecord.personal.zipCode
p. customerPtr->personal.zipCode

----------------------------------------------------------------------------------------------

You might also like