An example using Structures concept 

// To add two distances and display the result in feet and inches
# include <iostream.h>
struct distance                                             // Structure Declaration
{
int feet;
float inches;

};                                                         // End of structure declaration -terminated by the semi-colon
int main ( )
{
distance d1, d3;  
                                   // Structure variable definition
distance d2 = {11,6.25};    // Structure variable initialization at point of definition
cout<< “Enter the feet”;
cin>>d1.feet;
cout<< “Enter inches”;
cin>>d1.inches;
d3.inches=d1.inches + d2.inches;
d3.feet = 0;
if (d3.inches>12.0)
{
d3.inches- = 12.0;
d3.feet ++;
}
d3.feet = d3.feet + d1.feet + d2.feet;
cout<< “The resultant distance in feet and inches is :”<<d3.feet<< “ ”<<d3.inches;
return 0;
}

Remember : Arthimetic operator works only with built-in data types. Structures are user defined data types.

Hence it is not possible to say   : d3 = d1 + d2;

 In the above program, we declare a structure called distance. It has two data types namely : feet and inches.

You may have come across the line :

distance d2 = {11, 6.25};

This statement defines d2 as belonging to the structure distance. It also gives d2 a value of 11 and 6.25. 11 is assigned to feet and 6.25 is assigned to inches.

Then the program goes on to get the value of d1.feet and d1.inches from the user. The aim of the program is to add d1 (which is got from the user) and d2 (which is kept fixed at 11’6.25”). Hence we have to first add the inches. If the value of inches is greater than 12 then the value of resultant feet should be increased by one. In our case the resultant answer is stored in d3.

I think you should be able to understand the rest of the program. 

The next section deals with : Nesting of Structures

Or Go back to : Contents

Copyright © 2002 Sethu Subramanian All rights reserved.