Friday 26 July 2013

Define Structure in C++

                   Although arrays greatly improved our ability to store data, there is one major drawback to their use ... each element (each box) in an array must be of the same data type.  It is often desirable to group data of different types and work with that grouped data as one entity.  We now have the power to accomplish this grouping with a new data type called a structure.
    

                    A structure is a collection of variable types grouped together. You can refer to a structure as a single variable, and to its parts as members of that variable by using the dot (.) operator.  The power of structures lies in the fact that once defined, the structure name becomes a user-defined data type and may be used the same way as other built-in data types, such as int, float,double and char.
 

****Defining a structure****


                    When dealing with the students in a college, many variables of different types
are needed.  It may be necessary to keep track of a name, an address (street, city, state, zip code), an age, an ID number, and a grade point average.

For example:-

struct STUDENT_TYPE
{
        char name, street, city, state, zipcode;
        int age;
        double IDnum;
        double grade;
};

Here, STUDENT_TYPE is called the structure tag, and is your brand new data type, like int, double, char.name, street, city, state, zipcode, age, IDnum, and grade are structure members.

****Declaring Variables of Type struct****


    The most efficient method of dealing with structure variables is to define the structure globally.  This tells "the whole world", namely main and any functions in the program, that a new data type exists.  To declare a structure globally, place it BEFORE void main().  The structure variables can then be defined locally in void main..

No comments:

Post a Comment