Structure in C++





Structure in C++

Structure is a collection of simple variables of different types, grouped together under a single name for convenient handling. The data items in structure are called the member of the structure. It is a convenient tool for handling a group of logically related data item.

The general format of a structure definition is as follows:-

Struct_tag_name

{

Data_type member1;

Data_type member2;

————————-

————————

Data_type member n;

}

Structure_variables;

 

Accessing structure member

The member of the structure is access using the structure variable name with a period operator or dot operator (.).

The syntax for accessing a structure member is:

Structure_variables. member_name

E.g.

Struct student

{

Char name [20];

Int age;

Char address [25];

} stu;

To access the member of above structure, we write:

Stu.name

Stu.age

Stu.address

Hence, to read the values of name from keyboard, we write:

Cin>>stu.name;

And to write/ print the value of name to the screen, we write:

Cout<<stu.name;

 

Initializing structure elements/ members

 

The structure members of a structure can be initialized as shown below:-

Stu.name=”Ravi”;

Stu.age=11;

Stu.address=”Nepal”;

 

Example,

A program to initialize the member of a structure and to display the content of the structure.

#include<iostream.h>

#include<conio.h>

Struct student

{

Char name [25];

Int roll;

Char address [25];

}stu;

Void main ()

{

Stu.name=”Ravi”;

Stu.roll=11;

Stu.address=”pokhara”;

Cout<<”\n name”<<stu.name;

Cout<<”\n Roll no”<<stu.roll;

Cout<<”\n address”<<stu.address;

getch ();

}



Related posts:

  1. Array Of Class Object Array of class objects Array is a collection of similar...
  2. Pointer , New and Delete in C++ Pointer A pointer is a variable that contains address of...
  3. Class In C++ Class in c++ Class is a group of similar object....
  4. String In C++ String A string is an array of type char. Declaration:- ...
  5. Arrays In C++ Arrays in C++ Array is a collection of similar type...