INFORMATION FROM DR. EBRAHIMI'S C++ PROGRAMING EASY WAYS

Home                  ABOUT US                    CONTACT US                  TUTORIAL

CHAPTER 7

 

 STRUCTURE:  PUTTING RELATED ITEMS TOGETHER

 

When writing a program, several variables (identifiers) are declared and used. Some of the names used as identifiers are related and can be grouped together (memory wise) in one location as one unit in memory. This grouping of related names, including several variables and functions is called a structure.   In C, structures group only variables, while in C++ structures group variables as well as their related functions. Each variable and function is referred to as a member of the structure. In C++, the bundling of variables and functions adds the important concept of Object Oriented Programming (OOP), also known as class, to the C language.  This incorporation of variables and functions makes C++ both a Procedural as well Object-Oriented language.

 

 

HOW TO CREATE A STRUCTURE IN C

 

The key word struct is used to create a structure. In C, there are three general formats to create a structure variable as shown in Figures 7.1a, b, and c. Notice in Figure 7.1a, the structure is defined with the use of a tag name followed by the definition of the structure and the actual structure variable name. In Figure 7.1b, the use of a tag name is eliminated and the rest of the definition and the structure declaration remain the same.

 

Text Box: 1.      struct tagname { 
2.            datatype variablename;
3.            datatype variablename;
4.                  ·
5.                  ·
6.      };
7.      struct tagname structurevariablename;
Text Box: 1.       struct {
2.            datatype variablename;
3.            datatype variablename;
4.                 ·
5.                 ·
6.       } strucuturevariablename;
Text Box: Figure 7.1b – The definition and declaration of a structure without the use of the tag name following the struct keyword.
Text Box: 1.       struct tagname { 
2.            datatype variablename;
3.            datatype variablename;
4.                  ·
5.                  ·
6.       } structurevariablename;
 
Text Box: Figure 7.1a – The definition and declaration of a structure with the use of a tag name following the struct keyword.

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

Text Box: Figure 7.1c – The definition and declaration of a structure with the use of the tag name following the struct keyword in both the definition and the declaration.

  

 

 


 

Figure 7.1c shows the C declaration of a structure using the tag name twice. Line one uses the tag name to give the structure a name. Line seven uses the tag name as well as the struct keyword to declare an instance of the structure.

 

 

C++ STRUCTURE IS EQUIVALENT TO THE C STRUCTURE

 

In C, the name after the keyword struct indicates the structure tag that can be used later in the program with the keyword struct to declare a structure variable.  However, in C++ the name after the keyword struct is considered a type and can be used to declare a structure variable. Therefore, when a structure variable is declared using C++, the struct keyword is no longer needed.  Additionally, C++ structures can include functions as part of the structure.  This introduces the concept of OOP and class, which is discussed in a later chapter.

 

In Figure 7.2a, notice the definition is exactly like that of Figure 7.1a. A structure variable declaration can always follow the definition of a structure in C and C++. In Figure 7.2b, an easier and more meaningful definition and declaration of a structure is given. The C++ declaration uses a tag name followed by the actual structure variable name. The reuse of the struct keyword is eliminated. This elimination leads to less redundancy. It isn’t necessary to retype the struct keyword because with C++ the tag name becomes the type of structure that you are declaring.

Text Box: 1.      struct structuretype {
2.            datatype variablename; 
3.            datatype variablename;
4.                  ·
5.                  ·
6.      } structurevariablename;
Text Box: Figure 7.2a – The C++ version of a structure. Notice that the definition is the same as that of Figure 7.1a. A structure can always be declared in this manner, whether in C or C++.
Text Box: Figure 7.2b – A C++ version of a structure that uses the tagname as the type of structure to be declared. Line 7 shows the use of the tagname as the structure type.
Text Box: 1.      struct structuretype {
2.            datatype variablename;
3.            datatype variablename;
4.                  ·
5.                  ·
6.      };
7.      structuretype  structurevariablename;

  

 

 

 

 

 

 

 


 

The two examples that follow illustrate the differences between C and C++ structures. Figure 7.3a shows the C definition and declaration of a structure and 7.3b shows that of a C++ structure definition and declaration. Both examples define and declare the same type of structure. It is important to observe line 5 of Figure 7.3b, note the use of person, which is the type of structure defined, and is also used to declare an employee structure of type person.


 

 

Text Box: 1.      struct persontag{
2.            char name[20];
3.            double salary;
4.      };
5.      struct persontag employee;
 
Text Box: Figure 7.3a – The C version of a structure definition and declaration.
Text Box: Figure 7.3b – The C++ version of a structure definition and declaration. 
Text Box: 1.      struct person{
2.            char name[20];
3.            double salary;
4.      };
5.      person employee;
 

  

 

 

 

 

 


 

C++ STRUCTURE AS A BETTER C STRUCTURE AND AS A CLASS

C++ is known to be superior to C.  One reason for its superiority is that C++ simplifies the concepts of the C programming language. Some of these improvements are demonstrated in previous chapters with areas input and output (cin and cout of C++ versus scanf and printf of C) and the passing of parameters (pass by reference of C++ versus pass by pointer of C). Other major improvements are shown in the structure, such as:

 

1.)    In C++, the name after the keyword struct defines the type of structure being defined, therefore, a tag name is not necessary. The use of a tag with C is an overhead particularly when a structure needs to be passed to a function. In C, the keyword typedef is used in conjunction with the structure to overcome this problem.

2.)    In C++ a structure can contain functions related to the structure. This makes the structure a class. This transition to class is the gateway to Object-Oriented Programming (OOP).  OOP can become tedious to learn but will be beneficial in the long run.

 

 

PROGRAMMING WITH STRUCTURES OR WITHOUT: PARALLEL ARRAYS

 

Programmer uses a structure to group related data under a common name. By doing so, all of the data is treated as one entity. Can you imagine a large program without a structure? A programmer without a structure has to remember, which scattered variables are related to each other.  The other alternative is to use an index of parallel arrays to form a relationship between variables. For example name[ i ], phone[ i ], age[ i ] are related by the use of the same index, named i, for all the related variables. Figure 6.19a of Chapter 6 illustrates the use of parallel arrays: such as id[100], hoursworked[100], and hourlyrate[100]. Each value of i represents the ID, hours worked, and the hourly rate of one specific employee.

 

 

 

 

 

 

 

EXAMPLE OF C STRUCTURE

 

The examples of Figures 7.4a, b., and c. illustrate how C structures can be used in a program in various ways. Depending on the situation, one style may be preferable. The structures listed in the examples consist of three member variables: name, age, and salary. Each example program reads data into each variable and then displays the variable’s value. The program examples also match the styles used in Figure 7.1a, b, and c respectively. Figure 7.4d shows the output of all three programs based on the same input data.

 

Text Box: 1.      #include <iostream>
2.      using namespace std;
3.      struct  persontag {
4.            char name[ 20 ];
5.            int age;
6.            float salary;
7.      }employee;
8.      main( ){
9.            cout << " ENTER EMPLOYEE NAME:    ";
10.        cin >> employee.name;
11.        cout << " ENTER EMPLOYEE AGE:        ";
12.        cin >> employee.age;
13.        cout << " ENTER EMPLOYEE SALARY:";
14.        cin >> employee.salary;
15.        cout << " NAME IS     " << employee.name << endl;
16.        cout << "AGE IS          " << employee.age << endl;
17.        cout << " SALARY IS " << employee.salary << endl;
18.        return 0;
19.  }//MAIN

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

 

 

 

 


 

 

Text Box: 1.       #include <iostream>
2.      using namespace std;
3.        struct {
4.            char name[ 20 ];
5.            int age;
6.            float salary;    }employee;
7.       main( ){
8.             cout << "ENTER EMPLOYEE NAME:    ";
9.             cin >> employee.name;
10.         cout << "ENTER EMPLOYEE AGE:        ";
11.         cin >> employee.age;
12.         cout << "ENTER EMPLOYEE SALARY:";
13.         cin >> employee.salary;
14.         cout << " NAME IS     " << employee.name << endl;
15.         cout << "AGE IS          " << employee.age << endl;
16.         cout << " SALARY IS " << employee.salary << endl;
17.         return 0;
18.   }//MAIN
Text Box: Figure 7.4b – The program illustrates the style used in Figure 7.1b to define and declare a C structure. 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: 1.      #include <iostream>
2.      using namespace std;
3.      struct persontag {
4.            char name[ 20 ];
5.            int age;
6.            float salary;    };
7.      struct persontag  employee; 
8.      main( ){
9.            cout << "ENTER EMPLOYEE NAME:    ";
10.        cin >> employee.name;
11.        cout << "ENTER EMPLOYEE AGE:        ";
12.        cin >> employee.age;
13.        cout << "ENTER EMPLOYEE SALARY:";
14.        cin >> employee.salary;
15.        cout << " NAME IS     " << employee.name << endl;
16.        cout << "AGE IS          " << employee.age << endl;
17.        cout << " SALARY IS " << employee.salary << endl;
18.        return 0;
19.  }//MAIN
 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 7.4c – The program illustrates the style used in Figure 7.1c to define and declare a C structure.

  

 

 

 

Text Box: Figure 7.4d – The output of the programs of Figures 7.4a, b, and c, based on the same input data.
Text Box:  ENTER EMPLOYEE NAME:     Ebrahimi
 ENTER EMPLOYEE AGE:         45
 ENTER EMPLOYEE SALARY:  250000
 NAME IS     Ebrahimi
 AGE IS         45
 SALARY IS  250000

  

 

 

 

 

 

 

 

 


 

EXAMPLE OF C++ STRUCTURES

Figures 7.5a. and b. illustrates a C++ structure. Even though a C++ structure has its own style, any C structure shown above can be used in a C++ program. Since C++ is an improved C, it is recommended that you adhere to the C++ structure convention when using structures in a program. 

The program examples listed next match the styles used in Figure 7.2a and b respectively. Figure 7.5c shows the output of the two programs based on the same input data.

Text Box: 1.       #include <iostream>
2.      using namespace std;
3.       struct person {
4.            char name[ 20 ];
5.            int age;
6.            float salary;    }employee;
7.       main( ){
8.            cout << " ENTER EMPLOYEE NAME:    ";
9.            cin >> employee.name;
10.        cout << " ENTER EMPLOYEE AGE:        ";
11.        cin >> employee.age;
12.        cout << " ENTER EMPLOYEE SALARY:";
13.        cin >> employee.salary;
14.        cout << " NAME IS     " << employee.name << endl;
15.        cout << " AGE IS          " << employee.age << endl;
16.        cout << " SALARY IS " << employee.salary << endl;
17.        return 0;
18.   }//MAIN
Text Box: Figure 7.5a – The program illustrates the style used in Figure 7.2a to define and declare a C++ structure.
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

Text Box: 1.       #include <iostream>
2.      using namespace std;
3.       struct person {
4.            char name[ 20 ];
5.             int age;
6.             float salary;    };
7.       person  employee;
8.       main( ){
9.            cout << " ENTER EMPLOYEE NAME:    ";
10.        cin >> employee.name;
11.        cout << " ENTER EMPLOYEE AGE:        ";
12.        cin >> employee.age;
13.        cout << " ENTER EMPLOYEE SALARY:";
14.        cin >> employee.salary;
15.        cout << " NAME IS     " << employee.name << endl;
16.        cout << " AGE IS         " << employee.age << endl;
17.        cout << " SALARY IS " << employee.salary << endl;
18.        return 0;
19.   }//MAIN
Text Box: Figure 7.5b – The program illustrates the style used in Figure 7.2b to define and declare a C++ structure.
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box:  ENTER EMPLOYEE NAME:     Ebrahimi
 ENTER EMPLOYEE AGE:         45
 ENTER EMPLOYEE SALARY:  250000
 NAME IS     Ebrahimi
 AGE IS         45
 SALARY IS  250000

  

 

 

 

 

 

 

 

Text Box: Figure 7.5c – The output of the programs of Figures 7.5a and 7.5b, based on the same input data.

  

 

 

 

 


 

RECORD: ANOTHER NAME FOR A STRUCTURE

 

Some languages and databases call the structure a record, each record may contain several fields of data types such as an integer, float, character, bool (Boolean) or other types. The COBOL language frequently uses the concept of a record.

 

 

 

 

 

DOT OPERATOR: ACCESS MEMBERS OF A STRUCTURE

 

To refer to a variable of a structure, use the dot operator (character period on the keyboard) between the structure name and the structure contained variable. For example, in Figure 7.5a, each of the variables listed below belongs to the structure named person.

 

·         name is a 20 character long character array.

·         age is an integer variable

·         salary is a float variable

 

 

STRUCTURE INITIALIZATION

 

The data members of a structure can be initialized the following three ways:

1.)    At the time of declaration:

Text Box: person  employee = { "Ebrahimi", 35, 65000.00 };
 

  

 


 

Figure 7.6a shows an example program of a structure’s data elements that are initialized at declaration time.

 

Text Box: 1.       #include <iostream>
2.      using namespace std;
3.       struct person {
4.            char name[ 20 ];
5.            int age;
6.            float salary;     };
7.        main( ){
8.            person employee = { "Ebrahimi", 35, 350000.00 };
9.            cout << " NAME IS     " << employee.name << endl;
10.        cout << " AGE IS         " << employee.age << endl;
11.        cout << " SALARY IS " << employee.salary << endl;
12.        return 0;
13.   }//MAIN
Text Box: Figure 7.6a – The initialization of a structure’s data elements at structure declaration time.
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

2.)    Text Box: employee.age = 35;
employee.salary = 350000.00;
 

Manually initializing the members ( You simply assign a value to the members of a structure): 

 

 

Text Box: char initial;
 

How do we assign a name to a character array variable named name? There is no problem assigning a single character to a non-character array and adding it to the structure named person: 

 

Then the following line of code would assign the value of capital ‘A’ to the character variable named initial of the structure variable named employee:

Text Box: employee.initial = ‘A’;
 

  

 


 

When full names need to be inserted into character arrays, the built-in function named strcpy( ) ( found in the header file #include <string.h>) must be used to copy the value of a name to the name variable. The following line of code accomplishes the task of initializing the name variable of the structure named employee to the value of “Ebrahimi”.

Text Box: strcpy( employee.name, "Ebrahimi" );
 
 

  

 


 

In C++ the addition of the STL (Standard Template Library) facilitates string assignment. If the library named string (not to be confused with string.h) is added using the following line of code:

Text Box: #include <string>
 
 

  


 

The character array of the person structure is replaced with a string data type declared as follows:

Text Box: string name;
 

  

 


 

Text Box: employee.name = “Ebrahimi”;
 
 

Then the following line of code assigns the name of Ebrahimi to the string variable named name: 

 

 

The programs of Figures 7.6b and c show the manual initialization of a structures data elements. Figure 7.6b shows the initialization using the string.h library and the string copy (strcpy( ) built-in function ) and Figure 7.6c shows the use of the STL’s string

 library. We will discuss the STL and strings in more detail in a later chapter.


 

 

Text Box: 1.      #include <iostream>
2.      #include <string.h>  // string library old version
3.      using namespace std;
4.      struct person{
5.            char name[ 20 ];
6.            int age;
7.            float salary;     };  
8.      main( ){
9.            person employee;
10.        strcpy( employee.name , "Ebrahimi" );   
11.        employee.age = 35;
12.        employee.salary = 350000;
13.        cout << " NAME IS     " << employee.name << endl;
14.        cout << " AGE IS        " << employee.age << endl;
15.        cout << " SALARY IS " << employee.salary << endl;
16.        return 0;
17.  }//MAIN

  

 

 

 

 

 

 

 

 

Text Box: Figure 7.6b – The manual initialization of a structure’s data elements. Also observe the use of the strcpy( )function of the string.h library to assign a name to a character array.
Text Box: Figure 7.6c– The manual initialization of a structure’s data elements. Notice the use of the STL string library which eliminates the need for the strcpy( ) function to assign a name to a variable.
Text Box: 1.      #include <iostream> // new version of iostream with STL, not the .h version
2.      #include <string>     // the STL string library new version
3.      using namespace std;  // needed when using the STL
4.      struct person{
5.            string name;
6.            int age;
7.            float salary;
8.      };  
9.      main( ){
10.        person employee;
11.        employee.name = ”Ebrahimi”;   // NO string copy function is needed
12.        employee.age = 35;
13.        employee.salary = 350000;
14.        cout << " NAME IS     " << employee.name << endl;
15.        cout << " AGE IS        " << employee.age << endl;
16.        cout << " SALARY IS " << employee.salary << endl;
17.        return 0;
18.  }//MAIN

  

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 7.6d – Output for Figures 7.6a, 7.6b, and 7.6c
Text Box:  NAME IS      Ebrahimi
 AGE IS         35
 SALARY IS  350000

  

 

 

 

 


 

3.)    Through the input routines:

Text Box: cin >>  employee.name >> employee.age >> employee.salary;  // C++ 
 
Text Box: scanf( "%s%d%f", &employee.name, &employee.age, &employee.salary ); // C
 

  

 

 

 

 


 

The program in Figure 7.6e shows the initialization of a structure’s variables using the C++ cin statement. The output is listed in Figure 7.6f.

Text Box: 1.      #include <iostream>
2.      using namespace std;
3.      struct person {
4.            char name[ 20 ];
5.            int age;
6.            float salary;     };
7.      person  employee;
8.       
9.      main() {
10.        cout << "ENTER EMPLOYEE NAME:    ";
11.        cin >> employee.name;
12.        cout << "ENTER EMPLOYEE AGE:        ";
13.        cin >> employee.age;
14.        cout << "ENTER EMPLOYEE SALARY:";
15.        cin >> employee.salary;
16.        cout << "NAME IS      " << employee.name << endl;
17.        cout << "AGE IS          " << employee.age << endl;
18.        cout << "SALARY IS  " << employee.salary << endl;
19.        return 0;
20.  }//MAIN

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 7.6e – The initialization of a structure’s variables using the cin statement of C++.

  

 

 

 

Text Box: Figure 7.6f – Sample output of the program in Figure 7.6e.
Text Box:  ENTER EMPLOYEE NAME:    Ebrahimi
 ENTER EMPLOYEE AGE:        35
 ENTER EMPLOYEE SALARY: 350000
 NAME IS      Ebrahimi
 AGE IS         35
 SALARY IS  350000
 

 

 

 

 

 

 

 

 

 

 

 

 


 

ARRAY OF STRUCTURES

 

Several occurrences of the same structure, an array of structures, may be needed to store or retrieve information for a multitude of people. For example, if there are several employees in a department, each employee should have an occurrence of the structure. The index used to move through the array of structures will point to a specific occurrence in the array of structures. In Figure 7.7a, each employee entered has a location, or occurrence, which contains the employee’s name and phone number.

 

Hosted by www.Geocities.ws

1