HowToProgramC : Lesson 38


Back Home Next



Working with Structures

We have so far learnt how to define a structure and declare its variables. Let’s see how can we put the values in its data members. The following example can help us understand the phenomenon further.

struct student{
char name[64];
char course[128];
int age;
int year;
};
student s1, s2, s3;

Once the structure is defined, the variables of that structure type can be declared. Initialization may take place at the time of declaration i.e.

student s1 = {“Ali”, “C++ Programming”, 19, 2002 };

In the above statement, we have declared a variable s1 of data type student structure and initialize its data member. The values of data members of s1 are comma separated in curly braces. “Ali” will be assigned to name, “C++ Programming” will be assigned to the course, 19 to age and 2002 to year. So far we have not touched these data members directly. To access the data members of structure, dot operator (.) is used. Therefore while manipulating name of s1, we will say s1.name. This is a way of referring to a data member of a structure. This may be written as:

s1.age = 20;

The above statement will assign the value 20 to the age data member of structure s1. To display the name of s1 we can write it as:

cout << “The name of s1 = “ << s1.name;

Other data members can be displayed on the screen in the same fashion.

Here is a simple example showing the initialization and displaying the structure.

/* Simple program showing the initialization of structure.*/
#include <iostream.h>
main()
{
// Declaring student structure
struct student{
char name[64];
char course[64];
int age;
int year;
};
// Initializing the structure
student s1 = {"Ali", "C++ Programming", 22, 2002};
cout << "Displaying the structure data members" << endl;
cout << "The name is " << s1.name << endl;
cout << "The course is " << s1.course << endl;
cout << "The age is " << s1.age << endl;
cout << "The year is " << s1.year << endl;
}

The output of the above program is:

Displaying the structure data members
The name is Ali
The course is C++ Programming
The age is 22
The year is 2002

Here, s1 is a unit. The data members have been grouped together. If we have s1 and s2 as two variables of student type and want to copy the data of s1 to s2, it can be written as:

s2 = s1;



Back Home Next


Google




learntoknow@yahoo.com
© All rights Reserved.