0% found this document useful (0 votes)
18 views31 pages

Chapter 3 - Structure

Uploaded by

amanuaman1995
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views31 pages

Chapter 3 - Structure

Uploaded by

amanuaman1995
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Structures in C++

Chapter 3
Lecture Outline
1. Concept of a structure
2. Structure definition
3. How to declare structures
4. How to initialize structures
5. How to access structures
6. Arrays and Structures
7. Nested Structure
8. Pointers and Structures
9. Structures and Functions
10. Function Return Structure

Fundamentals of Prog. II | Structure 2


Concept of a Structure
• We have already dealt with arrays. Arrays are used to store similar
type of data. Have you ever thought if there is any way to
store dissimilar data?
• The answer is yes. We use structures to store different types of
data.
• For example, you are a student. Your name is a string and your
phone number and reg_no are integers. So, here name, address and
phone number are those different types of data. Here, structure
comes in the picture.

Fundamentals of Prog. II | Structure 3


Structure Definition
• Recall that an array is a collection of data items, all having the SAME
DATA TYPE and accessed using a common name and an INTEGER INDEX
into the collection.

• A struct is also a collection of data items, except with a struct the data
items can have DIFFERENT DATA TYPES, and the individual fields within
the struct are ACCESSED BY NAME instead of an integer index. These
data items are called MEMBERS

• Structs are very powerful for BUNDLING TOGETHER data items that
collectively describe a thing, or are in some other way related to each
other.

Fundamentals of Prog. II | Structure 4


Structure Definition (2)
• A structure is a user-defined data type in C++. A structure creates a data
type that can be used to group items of possibly different types into a
single type.
• A structure is a collection of related data items stored in one place and can
be referenced by more than one names. Usually these data items are
different basic data types. Therefore, the number of bytes required to
store them may also vary.
• It is very useful construct used in data structure, although in C++,
many struct constructs has been replaced by class construct

Fundamentals of Prog. II | Structure 5


How to create a structure?
• In order to use a structure, we must first declare a structure template/skeleton . The
variables in a structure are called elements or members.

• The ‘struct’ keyword is used to create a structure. The general syntax to create a
structure is as shown below:

struct structureName{
data-type member1;
data-type member2;
.
.
.
data-type memberN;
};

Fundamentals of Prog. II | Structure 6


How to create a structure?(2)
• For example, to store and process • Here, struct is a keyword that
a student’s record with the tells the compiler that a
elements id_num , name and age, structure template is being
we can declare the following declared and student is a tag
structure. that identifies its data
structure.
struct student { • Tag is not a variable; it is a label
string id_num; for the structure’s template.
string name;
int age; • Note that there is a semicolon
}; after the closing curly brace.

Fundamentals of Prog. II | Structure 7


How to create a structure?(3)
• A structure tags simply a label for the structure’s template but you
name the structure tag using the same rules for naming variables

• Compiler will not reserve memory for a structure until you declare
a structure variable same as you would declare normal variables
such as int or float.

• Declaring structure variables can be done in any of the following


ways (by referring to the previous example):

Fundamentals of Prog. II | Structure 8


How to create a structure?(4)|Structure Variables
Method (1) Method(2)
struct student {
struct student {
string id_num;
string id_num;
string name;
string name;
int age;
int age;
};
}; studno_1, studno_2; • Based on no. 2 version, then in main
program we can declare the structure
something like this:

• struct student studno_1, studno_2;


Fundamentals of Prog. II | Structure 9
How to create a structure?
|Structure Variables(2)
• In the above two cases, two structure variables,
studno_1 and studno_2, are declared

• Each structure variable has 3 elements that is 2 string variables and


an integer variable.

• In (1) the structure variables is declared immediately after the


closing brace in the structure declaration whereas in (2) they are
declared as student in the main of the program.

Fundamentals of Prog. II | Structure 10


#include<iostream> cout<<"\nEnter student idno ";
using namespace std; cin>>studno1.id_num;
struct student { cout<<"\nEnter your age";
string id_num; cin>>studno1.age;
string name; cout << "\n\nHello " << studno1.name <<" reg no "
int age; << studno1.id_num<< ". How are you?\n ";
}; cout << "\nCongratulations on reaching the age of
" << studno1.age<< ".\n";
int main(){ return 0;
struct student studno1; }
cout<<"Enter student name ";
cin>>studno1.name;

Fundamentals of Prog. II | Structure 11


How to initialize structure members?(2)
• Structure members can be initialized using curly braces ‘{}’. For
example, the following is a valid initialization.

struct Point {
int x, y;
};

int main() {
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}

Fundamentals of Prog. II | Structure 12


#include <iostream> How to access
using namespace std;
struct Point {
structure elements?
int x, y;
};
• Structure members are
int main() {
accessed using the dot (.)
struct Point p1 = { 0, 1 };
operator.
// Accessing members of point p1
p1.x = 20;
cout << "x = " << p1.x << ", y = " << p1.y;
return 0;
} //Output: x = 20, y = 1

Fundamentals of Prog. II | Structure 13


Structure Example(2)| declaration, initialization and
accessing structure elements

Fundamentals of Prog. II | Structure 14


Structure Example(3)
| Copying Structure Elements
• We can also copy two
structures at one go. We
just have to write p1 = p2
and that's it. By writing
this, all the elements of
p1 will get copied to p2.

Fundamentals of Prog. II | Structure 15


Array of Structures

• We can also make an array of structures. In the previous example


we stored the data of 3 students. Now suppose we need to store
the data of 100 such children. Declaring 100 separate variables of
the structure is definitely not a good option. For that, we need to
create an array of structures.

• Let's see an example for 5 students.

Fundamentals of Prog. II | Structure 16


Array of Structures(2)

Fundamentals of Prog. II | Structure 17


Array of Structures(2)…..

Fundamentals of Prog. II | Structure 18


Array of Structures(3)

• Here we created an array named stud having 5 elements of


structure student. Each of the element stores the information of a
student. For example, stud[0] stores the information of the first
student, stud[1] for the second and so on.

Fundamentals of Prog. II | Structure 19


#include <iostream> Array of Structures(4)

using namespace std;


struct Point { // Access array members
int x, y; arr[0].x = 10;
}; arr[0].y = 20;
int main() { cout << arr[0].x << " " << arr[0].y;
// Create an array of structures return 0;
struct Point arr[10]; }

• Output: 10 20
Fundamentals of Prog. II | Structure 20
Pointers to Structures

• Like we have pointers to int, char and other data-types, we also have
pointers pointing to structures. These pointers are called structure pointers.
Below is h0w we define a structure pointer

• struct structure_name{
data-type member-1;
data-type member-2;
data-type member-N;
};
int main(){
struct structure_name *ptr;
}

Fundamentals of Prog. II | Structure 21


• Like primitive types, we can have a Pointers to Structures (2)
pointer to a structure. If we have a
pointer to structure, members are
accessed using arrow ( -> ) operator
instead of the dot (.) operator. // p2 is a pointer to structure p1
struct Point* p2 = &p1;
#include <iostream>
using namespace std; // Accessing structure members using
structure pointer
struct Point {
int x, y;
}; cout << p2->x << " " << p2->y;
return 0;
int main() { }
struct Point p1 = { 1, 2 }; Output: 1 2
Fundamentals of Prog. II | Structure 22
Pointers to Structures(3)

Fundamentals of Prog. II | Structure 23


Pointers to Structures(4)

• struct student *ptr; - We declared 'ptr' as a pointer to the


structure student.

• ptr = &stud; - We made our pointer ptr to point to the structure


variable stud. Thus, 'ptr' now stores the address of the structure
variable 'stud'.

• cout << ptr->name << ptr->roll_no << endl; - We use -> operator to
access the members of a structure using a pointer to that
structure.

Fundamentals of Prog. II | Structure 24


Structure to Function

• We can also pass a structure to a function. There are two methods


by which we can pass structures to functions.
• Passing by Value
• Passing by Reference

• In this, we pass structure variable as an argument to a function.


Let's see an example to make it clearer.

Fundamentals of Prog. II | Structure 25


Structure to Function|Passing by Value

Fundamentals of Prog. II | Structure 26


Structure to Function| Passing by Value (2)
• In this example, we are printing roll number, name and phone number of a
student using a function.

• We first declared a structure named student with roll_no, name and phone
number as its members and 's' as its variable. Then we assigned the values of roll
number, name and phone number to the structure variable s. Just as we pass any
other variable to a function, we passed the structure variable 's' to a function
'display'.

• Now, while defining the function, we passed a copy of the variable 's' as its
argument with 'struct student' written before it because the variable which we
have passed is of type structure named student. Finally, in the function, we
printed the name, roll number and phone number of the structure variable.

Fundamentals of Prog. II | Structure 27


Structure to Function| Passing by Reference
• In passing by reference, the address of a structure variable is
passed to a function.

Fundamentals of Prog. II | Structure 28


Structure to Function| Passing by Reference(2)

• This case is similar to the previous one, the only difference is that
this time, we are passing the address of the structure variable to
the function.
• While declaring the function, we passed the pointer of the copy 'st'
of the structure variable 's' in its parameter. Since the pointer is of
a variable of type structure named student, we wrote 'struct
student' before the name of the pointer in the argument of the
function. In the function , we accessed the members of the pointer
using -> sign as discussed before.

Fundamentals of Prog. II | Structure 29


Function Returning Structure
Structure is user-defined data type, like built-in data types structure can be return
from function. Example for passing structure object by reference
#include<iostream>
using namespace std; Employee Input() {
struct Employee { Employee E;
int Id; cout << "\nEnter Employee Id : "; cin >> E.Id;
long Salary; cout << "\nEnter Employee Salary : ";
}; cin >> E.Salary;
Employee Input(); //Statement 1 return E; //Statement 2
int main() { }
Employee Emp;
Emp = Input();
cout << "\n\nEmployee Id : " << Emp.Id;
cout << "\nEmployee Salary : " << Emp.Salary;
}
Fundamentals of Prog. II | Structure 30
Function Returning Structure
Output:

Enter Employee Id : 10
Enter Employee Name : Ajay
Enter Employee Age : 25
Enter Employee Salary : 15000

Employee Id : 10
Employee Name : Ajay
Employee Age : 25
Employee Salary : 15000

Fundamentals of Prog. II | Structure 31

You might also like