Sie sind auf Seite 1von 10

OBJECT: TO

BECOME FAMILIAR WITH

STRUCTURES.

Structures The structure is the collection of simple variables. There can be any number of variables in an structure. In an structure the variables can of different data types unlike an array in which all the elements have the same data type. The data items in an structure are referred as the members of the structure. In C++ structures are the continent way to understand the two fundamental building blocks of C++ the class and the object. But the difference is only that the structure is the collection of variables whereas the class is the collection of data and the functions. Declaring the structure As we know that in C++ every thing defined by the user must be declared so the compiler makes sense to it. The declaration provides the blueprint for the compiler so when ever such things appear in front of the compiler it does not worry about it. To declare an structure the keyword struct is used at the starting and then the structure name follows. The structure name is also refereed as the tag. Then in the curly braces the variables with their data types are declared and these variables are known as the members of the structure. And at the last the structure is terminated by the semicolon. The syntax for the simple structure is as,
Keyword

struct
Structure name/tag

struct car {
Braces delimit structure members

int modelnumber; float maxspeed; float price; };


Note: semicolon here Structure members

In above declaration the structure named car is declared with three members one of type int (i.e. modelnumber) and two of type float (i.e. maxspeed, price) delimited by the curly braces and the structure is terminated at the end by the semicolon. It should be noted that the declaration does not set a side the memory for the member it just provides the blue print for the compiler.

Defining Structure Variables As in above when the structure is declared now it will behave as the new data type i.e. the structure name (car) will be the data type and the variables attached to it will have the data type of type car. To define the structure variables we declare the variables following the structure name as, (car MercedesBenz). You can define as many structure variables as you can. The syntax for the structure variable definition is as,

StructureName variable_1, variable_2, . . . . . . , variable_n; Defining structure variable Example, struct car { int modelnumber; char color[10]; int model; }; car Bedford, Mercedes, MercedesBenz, Ferrari;
In the above example the structure variables Bedford, Mercedes, MercedesBenz and Ferrari of structure car are defined and it should be noted each structure variable will contain entire structure members. The definition of the structure variables set aside the memory for the variables. The amount of memory depends up on the number and type of the members of the structure. In the above structure the variables Bedford, Mercedes, MercedesBenz and Ferrari will occupy 18 bytes of memory (4 bytes of int modelnumber, 10 bytes of char color[10]; and 4 bytes of int model). Combining Declaration and Definition As above we declared the structure first and then we defined its variable in separate statement but the C++ also offers the feature that you can combine the structure declaration and definition. To do this we eliminate the structure name/tag and the structure variable is place between the closing brace of the structure and the semicolon that terminates the structure but what it lacks is that in this method we can only define a single structure variable so it is less flexible and is not recommended as the standard way to declare and define the structure.

Combined Declaration and Definition Example, struct { int modelnumber; char color[10]; int model; }Bedford;
Accessing and Assigning Structure Members Once the structure is declared and the structure variables are defined now you can access the structure member with the help of dot operator . actually known as member access operator. To access the structure members first we use the structure variable name then the dot operator and finally the structure member name e.g. (Bedford.modelnumber). You can also assign certain values to the member like, Bedford.modelnumber=2007; but it should be noted that the value assigned to the member should match with the data type declared for that member in the structure.

Program (struct1.cpp)
#include <iostream.h> #include <conio.h> struct car
{

int modelnumber; float maxspeed; float price; }; void main() { car Bedford; Bedford.modelnumber=2007; Bedford.maxspeed=500.0; Bedford.price=4500000.0; cout<<Model Number: <<Bedford.modelnumber<<endl; cout<<Top Speed: <<Bedford.maxspeed<<endl; cout<<Total Price: <<Bedford.price<< Pak rupees; getch(); }

Initializing Structure Variables Like other variables you can also initialize the structure variables. To do this the values to be assigned to the structure members are placed in the curly braces and separated by the commas following the structure variable and equal to sign. It should be noted that the values placed in the curly braces should be of same data type that the structure members contain and also the sequence must be same as,

car Bedford={2007, 500.0, 4500000.0}; car Mercedes={2007, 600.0, 6000000.0}; car MercedesBenz={2007, 800.0, 9000000.0};
In above initializations the first value in the curly braces is to be assigned to the first structure member, second to the second structure member and third to the third structure member. You can also assign the same values of one structure variable to the other structure variable of same structure like,

Bedford=Mercedes; Mercedes=MercedesBenz;

//All values assigned to the Mercedes //All values assigned to the MercedesBenz

Program (struct2.cpp)
#include <iostream.h> #include <conio.h> struct car
{

int modelnumber; float maxspeed; float price; }; void main() { car Bedford={2007, 500.0, 450000.0}; car Mercedes=Bedford; cout<<Bedford:<<endl<<endl; cout<<Model Number: <<Bedford.modelnumber<<endl; cout<<Top Speed: <<Bedford.maxspeed<<endl; cout<<Total Price: <<Bedford.price<< Pak rupees<<endl; cout<<endl<<Mercedes:<<endl<<endl; cout<<Model Number: <<Mercedes.modelnumber<<endl;

cout<<Top Speed: <<Mercedes.maxspeed<<endl; cout<<Total Price: <<Mercedes.price<< Pak rupees<<endl; getch(); }


Nested Structures The mechanism obtained after putting one structure with in another structure is called the nested structure. As in the nested loops we write one loop in the body of another loop but here the criteria different, the nested structure does not mean that we have to put the body of one structure in to another structure. In the nested structure the data type of the members of the second structure will be the name of the first structure and the data type of the members of the third structure will be the name of the second structure and so on hence the depth is created that is responsible for nesting the structures. See the below example,

====================== struct student { int Rollno; int AC; int BEE; int ITC; }; ====================== struct university { student CS; student SW; student ES; student TL; student BM; student EL; }; ======================
In above example the first structure student is declared which has four members (Rollno, AC, BEE, and ITC), each having data type of type int. And the second structure university is nested in the first structure and its members (CS, SW, ES, TL, BM and EL) contain the data type of type student, which is the name of the first structure. So the above example illustrates the concept of nested structures.

Accessing nested structure members and Initializing nested structures As in the nested structure one structure is nested in to another structure therefore to access the members in the inner structure we have to first go through the outer structure then to the inner structure. To access the nested structure member we have to use the dot operator multiple number of time. If there are three nested structure then to access the inner structure member we have to use the dot operator three times. As in the above example the structure student is nested in to the structure university. So to access the student structure member, Suppose if we initialize the department structure variable MUET;

MUET.CS.Rollno; MUET.CS.AC; MUET.CS.BEE; MUET.CS.ITC;

MUET.SW.Rollno; MUET.SW.AC; MUET.SW.BEE; MUET.SW.ITC;

MUET.TL.Rollno; MUET.TL.AC; MUET.TL.BEE; MUET.TL.ITC;

The procedure of initializing the nested structure is same as initializing the simple structure. But here multiple numbers of braces are used as,

CS

SW

ES

university MUET={{10,80,85,90},{95,80,81,82},{11,87,84,81}, {45,85,84,83},{65,75,74,85},{21,87,89,88} }; TL BM EL

{10,80,85,90}

Here the four values in the first inner braces are initialized to the four members of the nested structure CS, second to the SW, third to the ES, fourth to TL , fifth to the BM and sixth to the EL.

EXERCISE
1. Create a structure called volume that uses three variables of type Distance (structure) to model the volume of a room. Initialize a variable of type volume to
specific dimensions, and then calculate the volume it represent and print out the result.

2. Create a structure a type date that contains three members: the day, the month, the year, all of type int. Here the user enter a date in the format 10/9/2007, store it in a variable of type date, then retrieve the value form the variable and print them
out in the same format.

3. Create a structure called time. Its three members, all of type int, should be called hours, minutes, and seconds. Write a program that prompts the user to enter a

time value in hours, minutes, and seconds. This can be in 12:30:50 format. The program then stores the time in a variable of type time, and finally prints out the total number of seconds. 4. Write a program that calculates the number of possible arguments for any number of guests and any number of chairs. (Assume there will never be fewer guests than chairs). A simple for loop should do it. For example the possible arrangement of six guests in four chairs is 360.

5. Write a program that stores the numerator and denominator of two numbers in

fraction, after adding them the result is also stored into fraction format. Use structure fraction to store these numbers and their result. (Both numerator and denominator should be of type int).

EXERCISE SOLUTIONS
===================================================

Program # 01
#include <constream.h> struct Distance { int feet; float inches; }; struct Volume { Distance length; Distance width; Distance breadth; }; void main() { Volume Room; Room.length.feet=7; Room.length.inches=5.7; Room.width.feet=4; Room.width.inches=15.2; Room.breadth.feet=6; Room.breadth.inches=4.5; float l=Room.length.feet+Room.length.inches; float w=Room.width.feet+Room.width.inches; float b=Room.breadth.feet+Room.breadth.inches; cout<<"The Volume of the Room is: "<<(l*w*b)<<" cubic feet"; getch(); } ===============================================================

===================================================

Program # 02
#include <constream.h> struct date { int day; int month; int year; }; void main() { date D1; char dummych; cout<<"Enter the date (dd/mm/yy): "; cin>>D1.day>>dummych>>D1.month>>dummych>>D1.year; cout<<"You entered date is: "; cout<<D1.day<<'\/'<<D1.month<<'\/'<<D1.year; getch(); }
===================================================

Program # 03
#include <constream.h> struct time { int hours; int minutes; int seconds; }; void main() { time T1; char dummych; int total_sec=0; cout<<"Enter the time (hh:mm:ss): ";

cin>>T1.hours>>dummych>>T1.minutes>>dummych>>T1.seconds; total_sec=T1.seconds+(T1.minutes*60)+(T1.hours*3600); cout<<"Total Seconds are: "<<total_sec; getch(); }


===================================================

Program # 05
#include <constream.h> struct fraction { int Num; int Deno; int AnsNum; int AnsDeno; }; void main() { fraction f1, f2; char dummych; cout<<"Enter first fraction: "; cin>>f1.Num>>dummych>>f1.Deno; cout<<"Enter second fraction: "; cin>>f2.Num>>dummych>>f2.Deno; f1.AnsNum=(f1.Num*f2.Deno)+(f2.Num*f1.Deno); f1.AnsDeno=(f1.Deno*f2.Deno); cout<<"Addition of two fractions is: " <<f1.AnsNum<<dummych <<f1.AnsDeno; getch(); }
===================================================

Das könnte Ihnen auch gefallen