Introduction

As C++ features the real world model so at times it becomes necessary for the programmer to store a number of information about a particular object in C++ .Here we make use of the structures in C++.like for storing the roll number, name and class of many students we have to take different variables which will become very difficult if the number of students are more say 50 or 100.so here we make use of structure which can store the different information about an object under a common name. It is better to use a common name for every student rather than using variable for each entity of a student.

 

structure

So structure is basically the grouping of variables under a common name. Structure is declared using the keyword struct.Yes you are right a structure needs to be declared before it can be used in C++.take a look at the syntax of a structure

struct structure name {

                Datatype member 1 name;

                Datatype member n name;

};

Example:

struct student

{

int roll;

char name[40];

};

 

Making structure variable

In order to use a structure we need to make structure variable after which we can store data in the structure variable. The variable is created in the following way. 

Structure name variable name;

 

Member Access

A member of a structure is the variable declared inside the structure body we will refer to them as member variables and the structure object as the structure variable. A member variable is accessed using the dot (.) operator. That means to access or use the member roll of the structure student we use the command

student.roll=15;

These members along with their full address i.e. the way I have explained above can be used as any other variable. An able programmer can use this feature by looping and playing with the name using arrays..

One full example showing all the features of the structure concept

 

#include<iostream.h>

struct stud

{

int roll;

char div;

};

void main()

{

stud a,b,c;

cout<<"enter the details for first student\n";

cout<<"enter the roll number:";

cin>>a.roll;

cout<<"enter the division:";

cin>>a.div;

cout<<"enter the details for second student\n";

cout<<"enter the roll number:";

cin>>b.roll;

cout<<"enter the division:";

cin>>b.div;

cout<<"enter the details for third student\n";

cout<<"enter the roll number:";

cin>>c.roll;

cout<<"enter the division:";

cin>>c.div;

cout<<"\nthe details are as follows \n";

cout<<"the first student\n";

cout<<"roll number:"<<a.roll;

cout<<"\ndivision:"<<a.div;

cout<<"\nthe second student\n";

cout<<"roll number:"<<b.roll;

cout<<"\ndivision:"<<b.div;

cout<<"\nthe third student\n";

cout<<"roll number:"<<c.roll;

cout<<"\ndivision:"<<c.div;

}

 

 

Make a Free Website with Yola.