Вы находитесь на странице: 1из 3

CS125: Programming Fundamentals

Lab No. 8 Structures


Objective
1. 2. 3. 4. 5. 6. Structure Declaration Defining a Structure Variable Accessing Structures members Array of Structures Pointers to Structures Get and Set Functions.

Programming Practices Declaring the Structures


The structure declaration tells how the structure is organized: It specifies what members the structure will have. Here it is:
struct part { int modelnumber; int partnumber; float cost; };

Defining a Structure Variable


The first statement in main(),
int main() { part part1; }

defines a variable, called part1, of type structure part. This definition reserves space in memory for part1. How much space?

Exercise:
Use sizeof() to check the size of part1 variable.

Accessing Structure Members


int main() { part part1; part1.modelnumber = 6244; part1.partnumber=1234; part1.cost=1200.99; }

Lab No. 8: Structures

CS125: Programming Fundamentals

Initializing Structure members


int main() { //initialize variable part part1 = { 6244, 373, 217.55F }; part part2; //define variable //display first variable cout << "Model " << part1.modelnumber; cout << " part " << part1.partnumber; cout << " costs $" << part1.cost << endl; part2 = part1; //assign first variable to second

//display second variable cout << "Model " << part2.modelnumber; cout << " part " << part2.partnumber; cout << " costs " << part2.cost << endl; return 0; }

Compile the Above code and check what the difference is. If not any difference then Explain why?

Exercise
Create a structure Students with Attributes Full name, Registration No and Marks. Keep record of three students Take input Full name, Registration no and marks from user. Print the values on screen of all 3 students.

Array of Structures
int main() { part part1[10]; part1[0].partnumber=1240; part1[0].modelnumber=6427; part1[0].cost=98.99; return 0; }

Exercise
Modify the Student structure and keeps record of 10 students and take input for each members of part from user. And print with data of Student with all members.

Lab No. 8: Structures

CS125: Programming Fundamentals

Pointer to Structure
int main() { part* part1; part1->partnumber=1234; part1->modelnumber=2007; part1->cost=129.75; return 0; }

Using Get and Set Functions


struct part { int modelnumber; int partnumber; float cost; void set(int mn, int pn, float c) { modelnumber=mn; partnumber=pn; cost=c; } int getModelNumber() { return modelnumber; } int getPartNumber() { return partnumber; } int getCost() { return cost; } }; int main() { part part1; part1.set(1234,7657,22.3); cout<<" Model Number : "<<part1.getModelNumber()<<endl; cout<<" Part Number : "<<part1.getPartNumber()<<endl; cout<<" Cost : "<<part1.getCost()<<endl; return 0; }

Modify your Student Structure to get the value using get function and assign value using set Function.

Checked By:

Date: July 15, 2013

Lab No. 8: Structures

Вам также может понравиться