codescracker


c++

C++ Data Structure



« Previous Tutorial Next Tutorial »


Sometimes, some logically related elements need to be treated under one unit. For example, the elements storing a student's information (e.g, rollno, name, class, marks, grade) need to be processed together under one roof. Similarly, elements keeping a date's information (e.g., day, month, and year) need to be processed together. To handle and serve to such situations, C++ offers structures.

C++ Structure Definition

To define structure in C++, follow this general form:

struct tag
{
	type variable-name ;
	type variable-name ;
	type variable-name ;
}structure-variables ;

where either tag-name or structure-variables may be omitted, but not both.

The following code fragment shows how to define a structure (say date). The keyword struct tells the compiler that a structure is being defined :

struct date
{
	short day ;
	short month ;
	short year ;
};

In the above definition, the date is a structure tag and it identifies this particular data structure and its type specifier.

C++ Structure Variable Definition

Also remember, at this point of time (i.e., after the above definition), no structure variable has been declared, that is, no memory space has been reserved. Only the form of the data has been defined. To declare a structure variable having the data form as defined by date, we will write :

data joining_date;

This declares a structure variable joining_date of type date. Thus, the complete structure definition is as follows :

struct date
{
	short day ;
	short month ;
	short year ;
};
date joining_date;

Now, the structure joining_date will be having its elements as day, month and year. The C++ compiler automatically allocates sufficient memory to accommodate all of the element variables that make up a structure variable.

The above given two separate statements of structure can be joined also, as shown below:

struct date
{
	short day ;
	short month ;
	short year ;
}joining_date ;

The above statement defines a structure type called date and declares a structure variable joining_date.

Accessing Structure Members in C++

In C++, once a structure variable has been defined, its member can be accessed through the use of dot (.) operator. You will learn more on it in C++ Access Structure Member tutorial. But for now, here is an example, the following code fragment access rollno element of senior_student structure variable:

senior_student.rollno;

C++ Structure Elements Initialization

The structure elements of structure can be initialized either separately, using separate assignment statements or jointly, using notation similar to array initialization. For example, the members of structure senior_student can be initialized separately as shown below:

senior_student.rollno = 01 ;
senior_student.class = 12 ;
senior_student.marks = 50.00 ;
senior_student.grade = 'A' ;

Alternately, the structure senior_student can be initialized by using notation used for array initialization, as it is shown below :

stutype senior_student = {01, 12, 50.00, 'A'};

Please note that the second method of structure initialization defined above, can be used only when the structure variable is defined. It can't be used before the structure variables have been defined. In that case the first method of separate initialization of elements is used.

In the above given statement stutype is the type specifier for senior_student and the structure senior_student is being declared and initialized simultaneously. The values to be assigned to the structure members are surrounded by braces and separated by commas. The first value is assigned to the first member, the second value to the second member, and so on.

C++ Structure Assignments

Objects of the structure types can be assigned, passed as function arguments, and returned as the result form a function. As can be seen in the following statement, one structure variable can be assigned to another:

junior_student = senior_student ;

With this statement, the value of each member senior_student is assigned to the corresponding member of junior_student.

Note - One structure variable can be assigned to another only when they are of the same structure type. If you try to assign the variable of one structure type to the variable of another structure type, then the compiler will report an error.

A structure may be local (to a function), if defined within a function. That is, no function other than the one which defines it, can access it (the structure). A structure may be global (to all functions within a program) if defined outside all the functions (i.e., any function can access it).

C++ Data Structure Tutorial

This tutorial on C++ data structure, divided into the following parts:

You will learn all about data structures in C++, one by one in detail. Now, below are some example programs on C++ data structures

C++ Data Structure Example

Here is an example program, demonstrating data structure in C++ practically

/* C++ Data Structures */

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

struct stud
{
	int rollno;
	char name[20];
	char branch[3];
	char batch[2];
	float marks[5];
	char grade;
}stud_var;

void main()
{
	clrscr();
	float sum = 0;
	float avg;

	cout<<"Enter rollno: ";
	cin>>stud_var.rollno;
	cout<<"Enter name: ";
	gets(stud_var.name);
	cout<<"Enter branch: ";
	gets(stud_var.branch);
	cout<<"Enter batch: ";
	gets(stud_var.batch);
	cout<<"Enter marks obtained in 5 subjects:\n";
	for(int i=0; i<5; i++)
	{
		cout<<"Subject "<<i+1<<": ";
		cin>>stud_var.marks[i];
		sum = sum + stud_var.marks[i];
	}
	avg = sum / 5;
	if(avg<50)
	{
		stud_var.grade = 'F';
	}
	else if(avg<60)
	{
		stud_var.grade = 'C';
	}
	else if(avg<80)
	{
		stud_var.grade = 'B';
	}
	else
	{
		stud_var.grade = 'A';
	}

	cout<<"\nStudent Result:\n";
	cout<<"\nRoll no: "<<stud_var.rollno<<"\t\tName: "<<stud_var.name;
	cout<<"\nBranch: "<<stud_var.branch<<"\t\tBatch: "<<stud_var.batch;
	cout<<"\nTotal Marks: "<<sum<<"\tGrade: "<<stud_var.grade;

	getch();
}

Here is the sample run of the above C++ program:

c++ data structure

Here is another program, also demonstrating data structure in C++

/* C++ Data Structure */

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

struct voter
{
	int idno;
	char name[20];
	char address[60];
	int age;
};

void main()
{
	clrscr();
	voter ward[10];
	for(int i=0; i<10; i++)
	{
		cout<<"Voter No. "<<i+1;
		cout<<"\nEnter id no: ";
		cin>>ward[i].idno;
		cout<<"Enter Name: ";
		gets(ward[i].name);
		cout<<"Enter Address: ";
		gets(ward[i].address);
		cout<<"Enter Age: ";
		cin>>ward[i].age;
		cout<<"\n";
	}
	clrscr();
	cout<<"Voters with age more than 60 are:\n";
	for(i=0; i<10; i++)
	{
		if(ward[i].age > 60)
		{
			cout<<"\nId no: "<<ward[i].idno;
			cout<<"\nName: "<<ward[i].name;
			cout<<"\n";
		}
	}
	getch();
}

Here are the sample runs of the above C++ program.

c++ structure definition

c++ structure initialization

c++ structure variable definition

After feeding the data, as shown in the above three sample runs, press ENTER to see the voters having age more than 60

c++ data structure example

Let's take one more program illustrating data structure in C++

/* C++ Data Structures */

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

const int SIZE = 5;

struct person
{
	char title[3];
	char fname[20];
	char lname[20];
	char address[40];
	char city[20];
	char state[20];
	long pin;
};

void main()
{
	clrscr();
	person labels[SIZE];
	for(int i=0; i<SIZE; i++)
	{
		cout<<"Enter information for person "<<i+1<<":\n";
		cout<<"Title (Mr/Mrs): ";
		cin>>labels[i].title;
		cout<<"First Name: ";
		cin>>labels[i].fname;
		cout<<"Last Name: ";
		cin>>labels[i].lname;
		cout<<"Address: ";
		gets(labels[i].address);
		cout<<"City: ";
		gets(labels[i].city);
		cout<<"State: ";
		gets(labels[i].state);
		cout<<"Pin: ";
		cin>>labels[i].pin;
		cout<<"\n";
	}
	char ch;
	cout<<"Want to display ? (y/n).. ";
	cin>>ch;
	if(ch=='y' || ch=='Y')
	{
		clrscr();
		for(i=0; i<SIZE; i++)
		{
			cout<<"Person "<<i+1<<": \t";
			cout<<labels[i].title<<" ";
			cout<<labels[i].fname<<" "<<labels[i].lname<<endl;
			cout<<"\t\t";
			cout<<labels[i].address<<", "<<labels[i].city<<endl;
			cout<<"\t\t";
			cout<<labels[i].state<<endl;
			cout<<"\t\t";
			cout<<labels[i].pin<<endl;
		}
	}
	getch();
}

Here are some sample runs of the above C++ program. Feeding data, shown in the following three figures

c++ data structure program

c++ structure programs

c++ structure examples

After feeding the data shown above, press y and then press ENTER to see the feeded data on the screen as shown in this figure:

data structure c++

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test