c++lang chap6

Upload: samaan

Post on 03-Jun-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 C++Lang chap6

    1/31

    CHAPTER 6

    Structures in C++

    6.1 INTRODUCTIONA variable holds one piece of information or data at a given time. Arrays hold a number of piecesof information or data of the same type. These two data types can solve a great variety of prob-lems. But when you want to process many data items of different types together as a unit, thenthese two types of definitions of data types are not sufficient. For example, when you want aprogram dealing with data concerning employees in an organization, then you may want to storethe employees name (a character array), department number (an integer), salary (a floating pointnumber), etc. together as a unit. This is not possible using an array type of data structure, becausethis array stores data of the same type. This is also not possible using multidimensional arrays.Hence, we would need to use several different types of arrays a character array for names, afloating point array for salary, etc. This approach although possible, is a tedious one. Moreover,

    this approach hides the fact that you are dealing with a group of characteristics relating to a singleperson, namely the employee. In order to solve such types of problems, C++ provides a specialdata type, called structure .

    6.2 STRUCTURE DEFINITIONThe data type structure consists of a number of data items grouped together but unlike arrays,each data item in the group need not be of the same type . Thus, for example, a structure may con-tain employees data encompassing employees_name, employees_number, salary, and any otherrelevant information about the employee. A structure can hold as many of these items as we need.Figure 6.1 shows the differences between a simple variable, an array and a structure.

    A structure date may be graphically represented as shown in Figure 6.2. A structure definitionis specified by the keyword struct followed by the user given name (also called tag). It is then fol-lowed by the opening brace. Then it encloses the members of the structure followed by the closingbrace and the semicolon. The syntax of the structure is given below:struct user_given_name

    {data_type member1;data_type member2;:

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    2/31

    Part I Structures in C++ 127

    :data_type membern;

    };

    Figure 6.1

    Simple vari-able, array andstructure

    41

    Simple variable:single data item

    Array:many data items

    104

    19

    22

    41

    63

    many data itemsStructure:

    S

    41

    2 4 , 5 6 6 . 5 0

    K

    RA

    E

    H

    of the same type

    of different types

    Figure 6.2

    Graphicalrepresentationof structurecalled date

    Based on the above, the structure date may be defined as shown below:struct date

    {int day;int month;int year;

    };

    date

    day

    month

    year

    struct

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    3/31

    128 Programming in C++ Part I

    6.2.1 A Simple StructureFigure 6.3(a) shows a structure simple containing two data items an integer variable num and acharacter variable ch . The program segment is shown in Figure 6.3(b).

    The program demonstrates the three fundamental aspects of using structures, namely:(a) Declaring the structure type(b) Declaring structure variables(c) Accessing elements of the structure

    Figure 6.3(a)Format of structuresimple

    De c la ring the Struc ture Typ e The following statement declares the structure type with a tag simple . [Read the program shown inFigure 6.3(b).]

    Struct simple{

    int num;char ch;

    };

    The above statement defines struct data type with the tag simple . It consists of two elements:an integer variable called num , and a character variable called ch . This statement just tells thecompiler what the struct data type named simple looks like.

    Program shown in Figure 6.3(b) uses struct simple for declaring variable ez1 and ez2 to be of type simple .

    Structures are useful, not only because they can hold different types of variables, but alsobecause they can form the basis for more complex structures.

    struct simple

    {

    int num;

    char ch;

    };

    Elementssurroundedby braces

    Semicolon terminatesentire statement

    KeywordThis name is

    called the " tag "

    Elements(or " members ")of the structure

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    4/31

    Part I Structures in C++ 129

    /*program demonstrating use of structure*/#include

    main(){struct simple /* definition of data type struct simple */{int num;char ch;};struct simple ez1; /* declares ez1 of data type simple */

    ez1.num = 2; /* accessing elements of ez1 */ez1.ch = z;cout

  • 8/11/2019 C++Lang chap6

    5/31

    130 Programming in C++ Part I

    Figure 6.4

    Structure ez1stored in mainmemory of thecomputer

    Use o f Struc ture The structure is used to store a "record" that may contain different data types. For example, anemployee record may contain the name (string variable), the department code (character variable),etc. All such data items can be put together in one structure using the keyword struct . These canthen be accessed as a single unit using the tag given to the record as a whole. The following pro-gram segment shows the declaration of the tag employee.

    struct employee{

    char name[31];char dept[4];

    char SSN[12];float pay_rate;};

    This template or tag defining employee can be used in a program as if it were another datatype . For example, you may declare a variable "employee_record" using the following declaration:

    struct employee employee_record;

    ez1

    Structure variableez1

    num

    ch

    Structurestored in memoryof structure

    Symbolic representation

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    6/31

    Part I Structures in C++ 131

    Here employee_record is declared as the data type employee which indicates that structemployee is functioning as if it is of a data type. Thus the general form of the structure definitionis:

    struct structure_name{member_declaration;member_declaration;

    } variable list;

    The variable "emplyee_record" is of the type struct employee. Right after the declaration aportion of the main memory is reserved for the variable "employee_record". This variable takes a

    size of 51 bytes for different structure members as follows:(a) 31 bytes for "name"(b) 4 bytes for "dept" code(c) 12 bytes for "SSN"(d) 4 bytes for the "pay_rate"

    In the case of string variables, there is an extra byte allowed for NULL (/o) character. Thismeans 30 characters for name and one character for NULL (/o). Similarly, 3 characters for "dept"code, and one for NULL. In the same way, 11 characters for the "SSN" and one for NULL. HereSSN is the short form of Special Service Number. Each character takes one byte of memory space.

    You can process the structure as a single unit for the following purposes.(a) Initializing a structure(b) Accessing the members of a structure(c) Accessing the address of a structure(d) Assigning one structure to another structure

    Ac c e ssing Struc ture Ele m e nts A member of the structure can be accessed using the structure variable name and the member name separated by the dot operator (.) as shown below:

    employee_record.name;employee_record.pay_rate;

    You will notice that the dot operator (.) provides a powerful and clear way to specify membersof a structure. An expression like employee_record.pay_rate is easier to understand thanemployee[29]. The variable employee[29] refers to 30th element of the array employee becausethe first element of the array employee is employee[0].

    To assign the numerical value 23.5 to the pay_rate, you may use the statement:

    employee_record.pay_rate = 23.5;

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    7/31

    132 Programming in C++ Part I

    If you have more than one structure variable, (such as "employee_in" and "employee_out"),you can move the data from one variable to the other. For example, you can assign one member tothe other like this:

    employee_out.pay_rate = employee_in.pay_rate

    You can also assign one structure variable to another:

    employee_out = employee_in

    By assigning this way, all the corresponding members of two structure variables become iden-tical.

    If the structure variables are declared and initialized inside a function, their storage classmust be static. The dot operator (.) connects a structure variable name with a member of the structure.

    For example, in Figure 6.5, ez1.num gets member num from the structure ez1 . Similarlyez2.num gets member num from structure ez2 .

    While accessing a structure member, note that before the dot, there must always be astructure variable and after the dot there must always be a structure element.

    6.2.2 Multiple Structure Variables of the Same Type

    There can be more than one variable of a given structure type in a program. For example, in theprogram shown in Figure 6.5, there are two variables, ez1 and ez2 , both of the type struct simple .

    /*program demonstrating the use of two structure variables*/#include

    main(){struct simple /* definition of data type struct simple */{int num;char ch;};

    struct simple ez1; /* declares ez1 to be of type simple */struct simple ez2; /* declares ez2 to be of type simple */ez1.num = 2; /* accessing elements of ez1 */ez1.ch = z;ez2.num = 3; /* accessing elements of ez2 */

    (Contd... )

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    8/31

    Part I Structures in C++ 133

    ez2.ch = Y;cout

  • 8/11/2019 C++Lang chap6

    9/31

    134 Programming in C++ Part I

    struct book{

    char name[10];float price;int pages;

    };struct book b1 = {"Maths",130.00,500};struct book b2 = {"Science",150.80,700};

    In the above program segment, b1 and b2 are of the type book containing three members each.The initial value for b1.name is Maths, b1.price is 130.00 and b1.pages is 500. Similarly, b2.name

    is Science, b2.price is 150.80 and b2.pages is 700.6.2.3 Entering Data into StructuresFigure 6.6 shows a program to construct a database for a typical employee category.

    /*program demonstrating entering and accessing data for employees*/#include

    main(){struct personnel /* definition of data structure */{char name[30]; /* employee name*/

    int numb; /* employee number */};struct personnel emp1; /* declares structure variable emp1 */struct personnel emp2; /* declares structure variable emp2 */cout

  • 8/11/2019 C++Lang chap6

    10/31

    Part I Structures in C++ 135

    and

    cin >>emp1.numb;

    In the same way, the cout statements print out the contents of the database.

    In the program shown in Figure 6.6, the database stores two items of information about eachemployee. The name of the employee is represented by a string (character array) and the employeenumber is represented by an integer. This information is entered into the program by the user. Theprogram reads and prints this information.

    Figure 6.7 illustrates the method of storing each element of the structure emp1 in the mainmemory of the computer. The element name[30] containing a string of maximum size 29 charac-

    Figure 6.7

    Structure emp1stored in themain memoryof thecomputer

    ters is stored in the consecutive locations in the main memory of the computer. (See right side of Figure 1.7.) Similarly, the numb having 3 digits is stored consecutively in the main memory of thecomputer.

    Structure emp1

    Structurestored in memoryof structure

    Symbolic representation

    H a r i

    0 1 2 3 28 29name[30]

    102

    Hari

    102

    numb

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    11/31

    136 Programming in C++ Part I

    Ex a m p le 1

    The program in Figure 6.8(a) shows a structure house_tag for the use of property dealers to storedata regarding various houses. The members of the structure are of different data types.

    /* program demonstrating the definition and use structure */#include #define NULL_STRING_TERMINATOR 1#define MAX_VALID_CHARS 65struct house_tag { char owner [ MAX_VALID_CHARS + NULL_STRING_TERMINATOR],

    street[ MAX_VALID_CHARS + NULL_STRING_TERMINATOR], city [ MAX_VALID_CHARS + NULL_STRING_TERMINATOR]; int bedrooms; float price;} A_House;void main(void) { cout > A_House.owner; cout > A_House.street; cout > A_House.city;

    cout > A_House.bedrooms; cout > A_House.price; cout

  • 8/11/2019 C++Lang chap6

    12/31

    Part I Structures in C++ 137

    Figure 6.8 (b) Typical run of the programgiven in Fig-ure 6.8 (a)

    6.2.4 Assignment Statements used with StructuresIt is possible to assign the value of one structure variable to another variable of the same type using

    a simple assignment statement. That is if the structure of employee1 and employee2 are exactlythe same, you may use the statement employee2 = employee1;

    The value of one structure variable can be assigned to another structure variable of thesame type.

    6.2.5 Initialization of a StructureA structure can be initialized by specifying the values of the data members just after the declara-tion of the structure as shown in the program of Figure 6.9(a). The output is shown in Figure6.9(b).

    6.2.6 Local Scope for Data Members of a StructureA field or member of a structure is a unique name for the particular structure. The same field or

    Who currently owns the house? S.C.Jain

    The house is on which street? C4F/271,

    The house is in which city? Janakpuri,New-Delhi

    The house has how many bedrooms? 3

    What is the selling price? 120000

    ================ HOUSE 1 ================Owner: S.C.Jain

    Street: C4F/271,

    City: Janakpuri,New-Delhi

    Bedrooms: 3

    Price: 120000

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    13/31

  • 8/11/2019 C++Lang chap6

    14/31

    Part I Structures in C++ 139

    /* program demonstrating two structure declaration */#includestruct first { int a; float b; char c; } one;struct second {

    int a; float b; char c; } two; void main (void) { one.a = 22; one.b = 34.98; one.c = f; two.a = 14; two.b = 56.98; two.c = m; cout

  • 8/11/2019 C++Lang chap6

    15/31

    140 Programming in C++ Part I

    };struct personnel emp[MAXNUMB];

    In order to declare an array-of-structures, we used the following statement after the declarationof the structure personnel :

    struct personnel emp[MAXNUMB];

    An array-of-structures creates space in the main memory for storing data and accessing data of a maximum of employees given in the variable MAXNUMB.

    The above statement sets space equal to as many as MAXNUMB times of a single structureand assigns this space to the structure of type personnel .

    Figure 6.11 shows conceptually the array-of-structures as stored in the main memory of thecomputer. The program using an array-of-structures is shown in Figure 6.12.

    Figure 6.11

    Array-of-struc-tures concep-tually shownas stored in thememory of acomputer J a

    U r

    H a

    emp[2].name

    emp[2].numb

    emp[2].height

    emp[1].height

    emp[1].numb

    emp[1].name

    emp[0].name

    emp[0].numb

    emp[0].height

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    16/31

    Part I Structures in C++ 141

    /* program to demonstrate keying into and accessing data from array ofstructures*/#include #include #define TRUE 1#define MAXNUMB 2void newempname (void);void listallemp (void); struct personnel

    {

    char name[25];int numb;float height;};struct personnel emp[MAXNUMB]; /* declaration of array-of -

    structure */ void main(void) {

    char ch; while (TRUE)

    {cout

  • 8/11/2019 C++Lang chap6

    17/31

    142 Programming in C++ Part I

    int n; for (n = 0; n < MAXNUMB; n++) {

    cout > emp[n].name;cout > emp[n].numb;cout > emp[n].height;

    } }

    /* for listing all employees data */ void listallemp(void) { cout

  • 8/11/2019 C++Lang chap6

    18/31

    Part I Structures in C++ 143

    Figure 6.12(b)

    Typical run of the programgiven in Fig-ure 6.12(a) forentry of data

    Type e to enter data for new employees

    Type l to list data of all employeese

    Enter new employee name: Ram

    Enter employee number ( 3 digits): 123

    Enter employee height (in cm): 175

    Enter new employee name: Mohan

    Enter employee number ( 3 digits): 234

    Enter employee height (in cm): 190^C

    Figure 6.12(c)

    Typical run of the programgiven in Fig-ure 6.12(a) fordisplay of entered data

    6.3.1 Initialization of an Array-of-StructuresAn array-of-structures can be initialized in the same way as an array of data in C++. The programshown in Figure 6.13(a) initializes the data for the employee by initializing data immediately afterthe declaration of the structure. The output of the program is shown in Figure 6.13(b).

    /* program demonstrating array-of-structures initialization */#include

    main() { struct personnel /* definition of data structure */ { int numb; /* employee number */ int sal; /* employee salary */ };

    (Contd... )

    LISTING OF DATA OF EMPLOYEES

    Record number1

    Employee Name: RamEmloyee Number: 123Employee Height:175Record number2

    Employee Name: MohanEmloyee Number: 234Employee Height:190

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    19/31

    144 Programming in C++ Part I

    personnel emp[2] = { {123,4000 }, /* initializing data for emp1*/ {234,5000 } /* initializing data for emp2 */ };

    cout

  • 8/11/2019 C++Lang chap6

    20/31

    Part I Structures in C++ 145

    personnel emp[MAX] = {{"Ramchander",123,4000 }, /* initializing data for emp1*/{"Suraj",234,5000 } /* initializing data for emp2 */ };

    cout

  • 8/11/2019 C++Lang chap6

    21/31

    146 Programming in C++ Part I

    personnel emp[MAX] = {{"Ramchander",123,4000 },/* initializing data for emp1*/{"Suraj",234,5000 }/* initializing data for emp2 */ };

    for (int i = 0; i

  • 8/11/2019 C++Lang chap6

    22/31

    Part I Structures in C++ 147

    { char name[20]; /* employee name */ int numb; /* employee number */ int sal; /* employee salary */ }; personnel emp[MAX] = {

    {"Ramchander",123,4000 }, /* initializing data for emp1*/{"Suraj",234,5000 } /* initializing data for emp2 */ };

    for (int i = 0; i

  • 8/11/2019 C++Lang chap6

    23/31

    148 Programming in C++ Part I

    The following program segment illustrates the method of passing a structure to a function.

    #include struct simple { int x; int y; };simple first; /* first declared as the structure of type simple */void show (struct simple out); /* prototype function show */void main(void){show first /* calling function show in the main() block*/}void show (struct simple out) /* function show definition */{out.x = 15;out.y = 25;cout

  • 8/11/2019 C++Lang chap6

    24/31

    Part I Structures in C++ 149

    date thisday; thisday.day = 15; thisday.month = 12; thisday.year = 1996; show(thisday); } void show (struct date one) { cout

  • 8/11/2019 C++Lang chap6

    25/31

    150 Programming in C++ Part I

    In this program you find a new operator "->" which is used with structures. It is called theindirect membership operator and is used to refer to a member of a structure by using the pointer toit. So if "emp_rec" is the pointer, then:

    emp_rec->name refers to the "name" member andemp_rec->SSN refers to the "SSN" member.

    /*program demonstrating use of pointers to structures */#include #include #include

    #include #define ASK(prompt,response) fputs(prompt,stdout); fgets(response,si-zeof(response),stdin)

    struct employee{char name[30+2];char dept[3 + 2];char SSN[11 + 2];float pay_rate;}employee_record;

    void read_info(struct employee *);void display_info(struct employee *);void hold_it(void);void read_info(struct employee *emp_rec)

    {char pay_string[5 + 2];ASK("Employee name:",emp_rec->name);ASK("Employee department (xxx):",emp_rec->dept);ASK("SSN (###-##-####):",emp_rec->SSN);ASK("Pay rate:",pay_string);emp_rec->pay_rate=atof(pay_string);

    }void display_info(struct employee *empl_recrd){

    cout

  • 8/11/2019 C++Lang chap6

    26/31

    Part I Structures in C++ 151

    void hold_it(void){ char c;

    coutc;

    } main()

    {

    read_info(&employee_record);display_info(&employee_record);return(0);

    }

    Figure 6.18(a) Using pointers to structures

    Figure 6.18(b)

    Output of theprogram givenin Figure 6.18(a)

    The output of the program in Figure 6.18(a) is shown in Figure 6.18(b).

    Note that the following two expressions mean the same thing:

    emp_rec->name(*emp_rec).name

    In the second expression we must use the parentheses because the dot operator is of higherprecedence than the "*" operator.

    6.5 USER DEFINED DATA TYPESC++ provides two more ways of defining application specific data types using typedef and enumdeclarations. Both these declarations help in clarifying program code.

    Employee name:MohanEmployee department (xxx):SalSSN (###-##-####):123-23-456Pay rate:45

    Employee Information:Name:Mohan

    Department:Sal

    SSN:123-23-456

    Pay rate:45/hr.

    Press any key to continue..

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    27/31

    152 Programming in C++ Part I

    6.5.1 Use of Typedef for Declaring Structure VariablesUsing the keyword typedef we can rename basic or derived data types, giving them names thatmay suit our application or make our program simpler. Look at this declaration:

    typedef unsigned long int ulong;

    After this declaration the new type "ulong" becomes known to the compiler and is treated the sameas unsigned long int . Now if we want to declare more variables of this type, we can use the newlydefined type as in:

    ulong distance;

    We may also use typedef with structures, as in the following example:

    typedef struct{

    char name[30 +1];char dept[3 + 1];float pay_rate;

    } record;This definition creates a new variable "record." We can now declare a structure variable as fol-lows:

    record employee_record;

    Thus employee_record is a structure variable of the type record defined earlier.We do not have to use the keyword struct again because the new type "record" refers to the

    same structure.

    6.5.2 Enumerated Data TypesDefinitions Enumerated data types let us define sets. These are used to express special data items that can fitinto an ordered series, like the days of the week or the months of the year.

    Decla ra t ion To declare an enumeration for the days of the week, the keyword enum is used as in the statement:

    enum weekdays{mon,tue,wed,thu,fri,sat,sun};

    According to this declaration, every day in the enumeration will possess an int value startingfrom zero. Therefore, "mon" will contain the value "0", "tue" will contain the value "1" and so on.

    The program shown in Figure in 6.19 uses the enum type of data.

    The output of the program will be:

    1 2 3 4 5 6 7 8 9 10 11 12

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    28/31

    Part I Structures in C++ 153

    /*program demonstrating the use of enum declaration */#include

    main(){enum month_name {jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};int month;for (month=jan; month

  • 8/11/2019 C++Lang chap6

    29/31

    154 Programming in C++ Part I

    /* Program demonstrates symbolic constant.*//* It converts temperature in Celsius to Fahrenheit */#include #define INVALID_DEGREE -1 /* Symbolic Constant */int main( void ){ int DegreeInCelsius; /* Variable Declarations */ float DegreeInFahrenheit; cout > DegreeInCelsius; while( DegreeInCelsius != INVALID_DEGREE ) { DegreeInFahrenheit = DegreeInCelsius * 1.8 + 32.0; cout

  • 8/11/2019 C++Lang chap6

    30/31

    Part I Structures in C++ 155

    TEST PAPERTime: 3 Hrs

    Max Marks: 100

    Answer the following questions.1. Fill in the blanks:

    Array elements must all be of the _______________, whereas structure members can beof ______________________.

    2. The purpose of declaring a structure type is to:(a) Set aside the appropriate amount of memory.(b) Define the format of the structure.(c) Specify a list of structure elements.(d) Define a new data type.

    3. Write a statement that declares a structure type consisting of two elements: a string of 10characters and an integer.

    4. How many structure variables of a given type can you use in a program?(a) one(b) none(c) as many as you like(d) as many as there are members in the

    structure5. Write a statement that will declare a structure variable car to be of the type vehicle .6. Assume the following declaration for the structure body:

    struct body{

    int arm;int legs;

    }struct body mohan;Write an assignment statement that will set the number of arms in mohans body equalto 2.

    7. Assuming that struct1 and struct2 are structure variables of the same type and containthe same number of members, is the following statement possible?struct1 = struct2;

    8. Write a program in C++ that will:(a) set up a structure to hold a date. The structure will consist of three integer values,

    for the month, day, and year.(b) Assign values to the members of the structure(c) Print out the values in the format 12/31/97

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap6

    31/31

    156 Programming in C++ Part I

    9. Modify the program in Q 8 so that the date is printed out by a function. Pass the structureto the function.

    10. Write a program in C++ to create a database with the following items using structureddata type with the tag patient_history.(a) patient_name(b) patient_admission_number(c) sex(d) date_of_admissionYour program should be able to do the following:(i) Insert a new entry.(ii) Delete an entry.(iii) Edit an entry.

    11. Write a program in C++ to create a library information system which includes the fol-lowing data members:(a) access_number(b) author_name(c) book_title(d) priceThe program should be able to do the following:(i) Insert a new entry.(ii) Delete an entry.(iii) Edit an entry.

    12. Distinguish the structure data type from other data type variables.13. What is the difference between declaration of a structure and initialization of a structure?

    Summarize the rules governing the declaration of a structure.14. How is a structure different from an array in C++? Give an example of each.15. What is meant by an array of fields in a structure and how is it different from an array?