VKS-LEARNING HUB

Home » Class-XI » C++ XI » Structure

Structure

Structure in C++

Structure is a collection of simple variables of different types, grouped together under a single name for convenient handling. Variables can be of any type: int, float, char etc. The main difference between structure and array is that arrays are collections of the same data type and structure is a collection of variables under a single name.

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;

where tag_name is a name for the structure type, Structure_variables can be a set of valid identifiers that have the type of this structure. Within braces { } there is a list with the data members, each one is specified with a type and a valid identifier as its name.

struct product {

int weight;

float price;

} ;

product prod1, prod2;

Declaring structures does not mean that memory is allocated. Structure declaration gives a skeleton or template for the structure.

After declaring the structure, the next step is to define a structure variable

We have first declared a structure type called product with two members: weight and price, each of a different fundamental type. We have then used this name of the structure type (product) to declare three objects of that type: prod1, Prod2  as we would have done with any fundamental data type.

How to declare Structure Variable?

This is similar to variable declaration. For variable declaration, data type is defined followed by variable name. For structure variable declaration, the data type is the name of the structure followed by the structure variable name.

In the above example, structure variable  prod1  is defined as:

Right at the end of the struct declaration, and before the ending semicolon, we can use the optional field Structure_variables to directly declare Variable of the structure type. For example, we can also declare the structure Variable prod1, prod2 melon at the moment we define the data structure type this way:

struct product {

int weight;

float price;

}prod1 , prod2 ;   // First Way

 

Second method

struct product {

int weight;

float price;

};

product prod1, prod2; // Second Way

How to access structure members in C++?

To access structure members, the operator used is the dot operator denoted by (.). The dot operator for accessing structure members is used thusly: structure_variable_name.member_name

A programmer wants to assign 2 for the structure member weight in the above example of structure product with structure variable prod1 this is written as:

prod1.weight =2;

prod.price=12.5

Example 2

struct item

{

int code;

char name[20];

double price;

};

Values can be stored in structure variable by using assignment operator (=) for the fundamental data type and using strcpy() for the string type. An example is given below:

item p;

p.code=10;

strcpy(p.name,”DOVE SOAP”);

p.price=42.75;

Values can be stored in structure variable by using an initializer. Initializer can only be used at the point of creation of a structure variable.

  • item p1 = {1001, “BASMATI RICE”, 75.5};

p1.code will contain value 1001, p1.name will contain value “BASMATI RICE” and p1.price will contain value 75.5. This is an ideal case, where data members are fully initialized, that is, values inside the initializer are exactly equal to number of data members and the order of the values inside the initializer matches with order of declaration of the data members.

  • item p2 = {1002, “LIPTON TEA”};

p2.code will contain value 1002, p2.name will contain value “LIPTON TEA” and p2.price will contain value 0.0. In this example data members are partially initialized. Since last data member is not initialized, by default it will have value 0.

  • item p3 = {};

p3.code will contain value 0, p2.name will contain “” and p2.price will contain value 0.0.

  • item p4 = {1003, “GLUCOSE-D”, 80.0, 25};

Syntax error, variable p4 will not be created since number of values inside the initializer exceeds number of data members.

  • item p5 = {“GLUCOSE-D”, 1004, 80.0};

Syntax error, since values inside the initializer appear in the wrong order.

Examples of incorrect structure declarations are given below:

1.     struct item

{

int code=1007;

char name[20]=”HP Laptop”;

double price=40000;

};

Syntax error because values cannot be assigned to data members of structure type. Values only can be assigned to data members of a structure variable.

2.     struct item

{

int code;

char name[20];

double price;

}

Syntax error because semi-colon is missing after closing curly bracket.

3.     item

{

int code;

char name[20];

double price;

};

Syntax error, keyword struct is missing before the structure name

Displaying a structure variable

Values stored in a structure variable can be displayed using cout or printf(). A string type data member  can be displayed with the puts(). An example is given below:

cout<<“Code =”<<p.code<<endl;

cout<<“Name =”<<p.name<<endl;

Or,

cout<<“Name =”; puts(p.name);

cout<<“Price=”<<p.price<<endl;

printf(“Code =%i\n”, p.code);

printf(“Name =%s\n”, p.name);

printf(“Price=%lf\n”, p.price);

cout<<p<<endl;

Each data member of a structure variable has to be displayed separately. cout<<StructVarName; is not allowed, that is, cout<<p; will flag syntax error

 

Complete programs are given below showing the use of structure in a C++ program:

1.     #include<iostream.h>

#include<stdio.h>

struct item

{

int code;

char name[20];

double price;

};

void main()

{

item prod;

cout<<“Product Code ? “; cin>>prod.code;

cout<<“Product Name ? “; gets(prod.name);

cout<<“Product Price? “; cin>>prod.price;

cout<<“Product Code =”<<prod.code<<endl;

cout<<“Product Name =”<<prod.name<<endl;

cout<<“Product Price=”<<prod.price<<endl;

}

Running of the program produces following output

Product Code ? 1023

Product Name ? Lipton Ice Tea Lemon

Product Price? 150

Product Code =1023

Product Name =Lipton Ice Tea Lemon

Product Price=150

2.     #include<iostream.h>

#include<stdio.h>

struct employee

{

int eno;

char name[20];

double basic;             //Basic Salary

double da;                //Dearness Allowance=50% of Basic

double hra;                       //House Rent=30% of Basic

double ca;                 //City Allowance=20% of Basic

double gross;             //Gross Salary=basic+da+hra+gross

};

void main()

{

employee a;

//Input of data into structure variable


cout<<“Employee Name  ? “; gets(a.name);

cout<<“Employee Number? “; cin>>a.eno;

cout<<“Basic Salary   ? “; cin>>a.basic;

//Process of inputted data


a.hra=0.3*a.basic;
a.da=0.5*a.basic;

a.ca=0.2*a.basic;

a.gross=a.basic+a.da+a.hra+a.ca;

//Display of inputted data and processed data on the screen

cout<<“Employee Number   =”<<a.eno<<endl;

cout<<“Basic Salary      =”<<a.basic<<endl;

cout<<“Employee Name     =”<<a.name<<endl;

cout<<“Dearness Allowance=”<<a.da<<endl;

cout<<“House Rent        =”<<a.hra<<endl;

cout<<“City Allowance    =”<<a.ca<<endl;

cout<<“Gross Salary      =”<<a.gross<<endl;

}

Running of the program produces following output

Employee Number? 1246

Employee Name  ? Nimesh Kumar Sampat

Basic Salary   ? 45000

Employee Number   =1246

Employee Name     = Nimesh Kumar Sampat

Basic Salary      =45000

Dearness Allowance=22500

House Rent        =13500

City Allowance    =9000

Gross Salary      =90000

Nested Structure

When a structure contains another structure as its member, it is called nested structure. We need at least two structures, outer structure and inner structure. Outer structure will contain inner structure as its member. When declaring the two structures, inner structure has to be declared first. An inner structure can be created inside outer structure. An example is given below:

struct date

{

int dd, mm, yy;

};

Inner structure name is date. Outer structure name is student. Outer structure student contains doj of the type date as its data member

struct student

{

int roll;

char name[20];

date doj;

};

Or,


{
struct student

int roll;

char name[20];

struct date

{

int dd, mm, yy;

} doj;

};

Outer structure name is student. Outer structure student contains structure declaration of doj, which is of the structure type date. 

Accessing the data members of a nested structure variable

Accessing the data members of a nested structure variable is very similar to accessing data member of a structure variable. General rule to access member of nested structure and complete program showing its use is given below:

OuterStuctVarName.InerStructDatavar.InnerStructDataMember

#include<iostream.h>

#include<stdio.h>

struct date

{

int dd, mm, yy;

};

struct student

{

int roll;

char name[20];

date dob;

};

void main()

{

student s;;

cout<<“Roll ? “; cin>>s.roll;

cout<<“Name ? “; gets(s.name);

cout<<“Day  ? “; cin>>s.dob.dd;

cout<<“Month? “; cin>>s.dob.mm;

cout<<“Year ? “; cin>>s.dob.yy;

cout<<“Roll     =”<<s.roll<<endl;

cout<<“Name     =”<<s.name<<endl;

cout<<“Birth Day=”<<s.dob.dd<<‘-‘<<s.dob.mm<<‘-‘<<s.dob.yy;

}

Running of the program produces following output

Roll ? 12

Name ? Allen John Mathew

Birth Day

Day  ? 3

Month? 7

Year ? 1990

Roll     =12

Name     =Allen John Mathew

Birth Day=3-7-1990

#include<iostream.h>

#include<stdio.h>

struct date

{

int dd, mm, yy;

};

struct employee

{

int code;

char name[25];

double salary;

date doj;

};

void main()

{

employee t;

cout<<“Code       ? “; cin>>t.code;

cout<<“Name       ? “; gets(t.name);

cout<<“Salary     ? “; cin>>t.salary;

cout<<“Day   [1-31]? “; cin>>t.doj.dd;

cout<<“Month [1-12]? “; cin>>t.doj.mm;

cout<<“Year  [YYYY]? “; cin>>t.doj.yy;

cout<<“Code       =”<<t.code<<endl;

cout<<“Name       =”<<t.name<<endl;

cout<<“Salary     =”<<t.salary<<endl;

cout<<“Join Date  =”<<t.doj.dd<<‘-‘<<t.doj.mm<<‘-‘

<<t.doj.yy<<endl;

}

Running of the program displays following output:

Inputting Employee’s Details

Code       ? 45

Name       ? Pradeep Kumar Sharma

Designation? Manager IT

Salary     ? 74000

Teacher Join Date

Day   [1-31]? 4

Month [1-12]? 9

Year  [YYYY]? 2002

Displaying Employee’s Details

Code       =45

Name       =Pradeep Kumar Sharma

Designation=Manager IT

Salary     =74000

Join Date  =4-9-2002

Global and Local structure variable: Generally a structure is created as a global identifier but structure variables are created locally (inside a block). In all our previous examples, structure variables are created locally. Using a global variable goes against the paradigm of Object Oriented Programming but that does not stop a programmer to create global structure variable. Some examples are given below showing how to create global structure variable.

Example #1:

struct teacher

{

int tcode;

char name[20];

char subject[20];

double salary;

};

teacher t1;  // Global Structure variable

void main()

{

teacher t2;

 // Local Structure variable  can be access inside the function only

//More C++ Code

}

Example #2:

struct teacher

{

int tcode;

char name[20];

char subject[20];

double salary;

} t1;   // Global Structure variable

void main()

{

teacher t2;         // Local Structure variable  can be access inside the function only

//More C++ Code

}

Example #3:

struct

{

int tcode;

char name[20];

char subject[20];

double salary;

} t1, t2;  //  2  Global Structure variable can be access inside the function

void main()

{

//More C++ Code

}

 

Function and Structures

Just like fundamental data and array type, a structure type can be passed as parameter to a function. A structure type can either be passed as value parameter or a reference parameter to a function. By default, structure type is passed by value to a function. A complete program is given below showing the use of structure as parameter to a function.

#include<iostream.h>

#include<stdio.h>

struct contact

{

char name[20];

int phone, mobile;

};

void inputdata(contact& c1)

{

cout<<“Name  ? “; gets(c1.name);

cout<<“Phone ? “; cin>>c1.phone;

cout<<“Mobile? “; cin>>c1.mobile;

}

void viewdata(contact c2)

{

cout<<“Name  =”<<c2.name<<endl;

cout<<“Phone =”<<c2.phone<<endl;

cout<<“Mobile=”<<c2.mobile<<endl;

}

void main()

{

contact co;

inputdata(co);

viewdata(co);

}

Formal parameter c1 is passed as reference since input of values inside the function inputdata() must update actual parameter co. Formal parameter c2 is passed as value parameter since function viewdata() only displays the value stored in co.

Running of the program produces following output

Name  ? Tarun Kumar

Phone ? 25649873

Mobile? 99325681

Name  = Tarun Kumar

Phone =25649873

Mobile=99325681

If we edit the function inputdata() and make formal parameter c1, a value parameter (by removing &), then the running of the program produces following output

Name  ? Tarun Kumar

Phone ? 25649873

Mobile? 99325681

Name  =☻|~g&s

Phone =4243884

Mobile=-19464465

Actual parameter co is passed by value to inputdata() function (formal parameter c1 is copy of actual parameter co). Updating formal parameter c1 does not update actual parameter co.

We have learned how pass a structure type as parameter to a function. Now we are going to learn that return value of a function could be structure type as well. An example is given below:

#include<iostream.h>

struct Time

{

int hh, mm;

};

void InputTime(Time& t)

{

cout<<“Hour  ? “; cin>>t.hh;

cout<<“Minute? “; cin>>t.mm;

}

void ShowTime(Time t)

{

cout<<“Time=”<<t.hh<<‘:'<<t.mm<<endl;

}

Return value of the function AddTime() is Time where Time is a structure. Statement return t, returns value stored in structure variable t to the calling function.

Time AddTime(Time t1, Time t2)

{

Time t;

int m=t1.mm+t2.mm

t.hh=t1.hh+t2.hh+m/60;

t.mm=m%60;

return t;

}

void main()

{

Time t1, t2;

InputTime(t1);

InputTime(t2);

Time t3=AddTime(t1,t2);

ShowTime(t1);

ShowTime(t2);

ShowTime(t3);

}

Running of the program twice, produces following output

Hour  ? 2

Minute? 30

Hour  ? 3

Minute? 10

Time=2:30

Time=3:10

Time=5:40

Hour  ? 4

Minute? 50

Hour  ? 3

Minute? 40

Time=4:50

Time=3:40

Time=8:30

Array of structure: So far we have created one or two structure(s) in our program (in our example). Suppose we want to represent many structure variables of same structure type in computer’s main storage, then we have to create an array of structures. To create an array of structures, first we have to create a structure and then we will create an array of that structures. Each element of the array will be a structure variable.

Name of the structure is StructName. Name of the array is Arr. Arr is an array of structure. SIZE is a constant representing number of elements in the array. SIZE could either be a user defined constant or a constant like 10 or 20. Every elements of array Arr will represent structure variable.

struct StructName

{

//DataMembers

};

StructName ArrName[SIZE];

Syntax to access an element of an array of objects is:

ArrName[Index]

ArrName[0], ArrName[1], ArrName[2],…

are the elements of the array ArrName[]. Each element of ArrName[] represents a structure variable. Syntax to access data members of an array of structures is given below:

ArrName[Index].DataMember

Programming example is given below explaining the concept of array of structures:

Structure student has 3 data members – roll, name and mark. Array arr[5] is an array of student.

struct student

{

int roll;

char name[20];

double mark;

};

student arr[5];

arr[0], arr[1], arr[2], arr[3] and arr[4] are the 5 elements of the array. Each element of the array arr[] is a structure variable. List below shows how to access data members of each element of array arr[].

arr[0].rollarr[0].namearr[0].mark arr[1].rollarr[1].namearr[1].mark arr[2].rollarr[2].namearr[2].mark arr[3].rollarr[3].namearr[3].mark arr[4].rollarr[4].namearr[4].mark

A complete program is given below showing use of array of objects.

#include<iostream.h>

#include<stdio.h>

const MAX=20;

struct student

{

int roll;

char name[20];

double mark;

};

void input(student& stu)

{

cout<<“Roll? “; cin>>stu.roll;

cout<<“Name? “; gets(stu.name);

cout<<“Mark? “; cin>>stu.mark;

}

void display(student stu)

{

cout<<“Roll= “<<roll<<endl;

cout<<“Name= “<<name<<endl;

cout<<“Mark= “<<mark<<endl;

}

void main()

{

student arr[MAX];

for (int k=0; k<MAX; k++)

input(arr[k]);

double hm=0, sum=0;

for (int x=0; x<MAX; x++)

{

display(arr[x]);

sum+=arr[x].mark;

if (hm>arr[x].mark)

hm=arr[x].mark;

}

double avg=sum/MAX;

cout<<“Highest=”<<hm<<” & Average=”<<avg<<endl;

}

Or,

void arrinput(student a[], int n)

{

for (int k=0; k<n; k++)

input(arr[k]);

}

void arrdisplay(student a[], int n)

{

for (int k=0; k<n; k++)

display(arr[k]);

}

void arrhiav(student a[], int n)

{

double hm=0, sum=0;

for (int k=0; k<MAX; k++)

{

sum+=arr[k].marks;

if (hm>arr[k].mark)

hm=arr[k].mark;

}

double avg=sum/n;

cout<<“Highest=”<<hm<<” & Average=”<<avg<<endl;

}

void main()

{

student arr[MAX];

arrinput(arr, MAX);

arrdisplay(arr, MAX);

arrhiav(arr, MAX);

}

An initializer can be used with an array of structures to initialize data members of each element of an array of structure. Examples are given below:

struct student

{

int roll;

char name[20];

double mark;

};

Array arr[], array of structure student is fully initialized.

student arr[5]=  {    {10, “Bina Varghese”, 50.0},

{13, “Dinrsh Thakur”, 80.5},

{22, “Manish Shrama”, 75.0},

{24, “Pamela Gupta”, 90.5},

{35, “Rashid Mohd Ali”, 65.5},

};

Array arr[], array of structure item is partially initialized.

student arr[5]=  {    {10, “Bina Varghese”, 50.0},

{13, “Dinrsh Thakur”, 80.5},

{22, “Manish Shrama”, 75.0},

{24, “Pamela Gupta”},

};

arr[3].mark   will contain the value 0 (zero).

arr[4].roll will contain the value 0.

arr[4].name will contain the value “”  (Nul string or Empty string).

arr[4].mark   will contain the value 0 (zero).

If values inside the initializer exceeds the number of elements in the array or exceeds the number of data members of structure, then the compiler flags a syntax error. Example is given below:

student arr[5]=  {    {10, “Bina Varghese”, 50.0},

{13, “Dinrsh Thakur”, 80.5},

{22, “Manish Shrama”, 75.0},

{24, “Pamela Gupta”, 90.5},

{35, “Rashid Mohd Ali”, 65.5},

{36, “Tarun Jain”, 86.0},

{40, “Sudip Lamba”, 72.0, “A1”},

};

Previous

Solved Examples

Unsolved Questions for Practice

 


Leave a comment