728x90 AdSpace

Latest Article



Structures in C++ Programming basic Tutorial with Example





Online Structures in C++ Programming basic Tutorial with Example  data Structure Topic Source code 

STRUCTURES

               Structures are aggregate data types consisting of other elementary data types. As an example we can declare a structure named complex that contains two data members: an integer variable real and another integer variable imaginary. Unlike arrays (all the members of which have to be of the same type), a structure may consist of elements belonging to different data types. For example a structure named book may be declared which has three members: an integer variable id, a floating type variable price and a character array title.
Try to think of many real life objects that you can represent by structures.

How to Use Structures?

                             Structures can be declared by using the keyword struct. For example the structures complex can be declared as:
 
     struct book          // keyword struct  tells that book is a structure
     {
         int id ;
         float price ;
         char title[20] ;
      };                   //note the semicolon (;) at the end of 
structure definition
 
 
      book  sowkoski ;     //declares an instance of type book and names it sowkoski
      book Csbooks[5];     // an array of type book is declared
 
 
Note the similarity between declaring an instance of a built in data type ( int num; int a[5];) and that of a user defined data type( book sowkoski; book Csbooks[5]; )
Alternatively an instance of a structure may also be declared along with the structure definition but usually this is not the preferred method. An example follows that declares two instances of a structure complex with its definition. The structure name may be omitted in such a case but this disallows creation of any more instances in the program.
struct complex                    // keyword struct  tells that complex is a structure
 {
      int real;
      int imaginary ;
} c1, c2 ;                           //declares two instances of the structure complex

How to Access the Members of a Structure?

               The dot operator (.) is used to access the members of a structure. Following examples elaborate the use of the dot operator:
STATEMENTS
OUTPUT
        
sowkoski.id=922;
cout<<"Sowkoski's ID is "<<sowkoski.id;
 
 
cout<<"\n Enter title for first CS book: ";
cin>>Csboks[0].title;
cout<<Csbooks[0].title;
 
Sowkoski's ID is 922
Enter title for first CS book: XYZ
XYZ
 
 
Members of a structure when accessed by the dot operator act as ordinary data types and all valid operations may be performed on them. For example all valid integer operations (+, -, *, /, %, ++ etc) may be performed on sowkoski.id.

no image
  • Title : Structures in C++ Programming basic Tutorial with Example
  • Posted by :
  • Date : 06:34
  • Labels :






  • Blogger Comments
  • Facebook Comments

0 comments:

Post a Comment