Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views24 pages

Chapter 6 - Structures

Chapter 6 discusses structures in C/C++, which are user-defined data types that allow the combination of different data items. It covers the definition, declaration, initialization, and usage of structures, including accessing member variables and creating arrays of structures. Additionally, it explains how structures can contain other structures and provides examples of how to implement and manipulate these structures in code.

Uploaded by

Fana Admasu
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)
7 views24 pages

Chapter 6 - Structures

Chapter 6 discusses structures in C/C++, which are user-defined data types that allow the combination of different data items. It covers the definition, declaration, initialization, and usage of structures, including accessing member variables and creating arrays of structures. Additionally, it explains how structures can contain other structures and provides examples of how to implement and manipulate these structures in code.

Uploaded by

Fana Admasu
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/ 24

Chapter 6

Structures
1. STRUACTURE
 In C/C++ arrays allows you to define variables that combine
several data items of the same kind but structure is another user
defined data type which allows to combine different data items of
different kinds.
 The term structure in C++ means both a user-defined type which
is a grouping of variables as well as meaning a variable based on a
user-defined structure type.
 For the purpose of distinction we will refer to the user-defined
type side as structure definition and the variable side as structure
variable.
 A structure definition is a user-defined variable type which is a
grouping of one or more variables.
 The type itself has a name, just like „Int‟, „double‟, or „char‟ but it is
defined by the user and follows the normal rules of identifiers.
Continued….
 Since a structure definition is a grouping of several types: it is a
group of one or more variables.
 Before creating a structure variable you must create a structure
definition. This is a blue print for the compiler that is used each
time you create a structure variable of this type.
 The structure definition is a listing of all member variables with
their types and names.
 When you create a structure variable based on a structure
definition, all of the member variables names are retained.
 The only name you have to give is that of the new structure
variable.
2. struct Specification: Defining Structures
 Defining a structure is giving the compiler a blue print for creating your
type.
 When you create a variable based on the structure definition, all of the
member variables are created automatically and grouped under the
name you gave.
 Note that when you create a variable of any kind, you must give it a
unique name that is different than its type.
 syntax for a structure definition:
struct structname {
datatype1 variable1;
datatype2 variable2;
};
 N.B: Writing a structure definition begins with the word „struct‟
followed by the type-to-be, and ended with a structure block that is
ultimately terminated with a semicolon.
Continued…
 The data members (synonym for member variables) of a structure won‟t
actually be created until a variable based on the structure is created.
 Technically an „int‟ is just this as well. It‟s a description of a storage unit.
That storage unit isn‟t reserved until you create a variable with it.
 Example defining a student struct,
struct student
{
int id;
char name[15];
};
 Example: The follow defines a structure called „date‟ which contains three
„int‟ member variables: „day‟, „month‟, and „year‟:
 struct date {
 int day;
int month;
int year;
};
 struct date{ int day, month, year;};
Continued….
 Note: You cannot initialize member variables in a structure definition.
The following is wrong and will not compile:
struct date{
int day = 24, month = 10, year = 2001;};
 A structure definition has the same type of scoping as a variable.
 The following is an empty program that defines a „date‟ structure globally:
#include <iostream.h>
struct date{
int day, month, year;};
int main(){
return 0;
}
3. Declaring and using struct data types
 Once you have defined a structure you can create a variable from it just as
you would any other variable.
student std1;
date birthday;
 The above declaration statements would create a variable called „birthday‟
whose type is the structure „date‟.
 The variable contains three parts: „day‟, „month‟, and „year‟. What this
actually does is set aside a whole block of memory that can contain all of
the member variables.
 Each member variable then occupies a chunk of it for their individual
storage units. The member variables are not actually created one at a time.
int i;
student std1;
 The above statements are similar in nature because both declare a variable
of a given type. The former is a built in type, which is integer while the later
declares a variable type of user-defined type. std1 will have the
characteristics of representing id and name of a student.
3.1. Initializing Structure Variables
 You cannot initialize member variables in the structure definition. This

is because that definition is only a map, or plan, of what a variable based


on this type will be made of.

 You can, however, initialize the member variables of a structure


variable. That is, when you create a variable based on your structure
definition you can pass each member variable an initializer.

 To initialize a structure variable‟s members, you follow the original

declaration with the assignment operator (=).

 Next you define an initialization block which is a list of

initializers separated by commas and enclosed in curly braces.


CONTINUED…
 Lastly, you end it with a semi-colon. These values are assigned to
member variables in the order that they occur.
 Let‟s look at an example:
date nco_birthday = { 19, 8, 1979 };
student std1={"Ababe", "Scr/2222/22"};
 It is possible to use any expression that you normally would. But
remember that the expression must result in a value. Here is an
example of initialization with things other than literals:
int myday = 19;
int mymonth = 5;
date nco_birthday = { myday, mymonth + 3, 2001 - 22 };
 Although you can assign a value to a variable in the same way you
initialize it, the same is not true with structures. So while this works:
int x;
x = 0;
 This doesn‟t:
date nco_birthday;
nco_birthday = { 19, 8, 1979 };
3.2. Accessing members of a structure variable
 There‟s not much you can do with the structure itself; much of your
time with structure variables will be spent using its members.
 You can use a member variable in any place you‟d use a normal variable,
but you must specify it by the structure variable‟s name as well as the
member variable‟s name using the member operator.
 To specify that you want a member of a specific structure variable, you
use the structure member operator which is the period (also known as
a “dot”).
 Simply use the structure‟s name, follow with the period, and end with
the member:
 structure.member
 Example: to reading and displaying values to and from structure s1.
 cin>>s1.id; //storing to id item of s1
 cin>>s1.name; //storing a name to s1
 cout<<s1.id; //displaying the content of id of s1.
 cout<<s1.name; //displaying name
a program that creates student struct and uses it to store student information.
#include<iostream> cin>>s2.name;
#include<conio.h> cout<<"\nStudents Information";
struct student cout<<"\n Student id\t Student Name";
{ int id; cout<<endl<<s1.id<<"\t"<<s1.name;
char name[15]; }; cout<<endl<<s2.id<<"\t"<<s2.name;
void main() getch();
{ }
//creating two student variables
student s1,s2;
cout<<"\n Enter Student Id";
cin>>s1.id;
cout<<"\nEnter Name";
cin>>s1.name;
cout<<"\n Enter Student Id";
cin>>s2.id;
cout<<"\nEnter Name";
Example 2: This program demonstrates using member variables for user input,
output, and mathematical operations.
#include <iostream> birth.day << “/” << birth.year << endl;
struct date
{ cout << “You were born in the “<< ((birth.year /
int day, month, year; 100) + 1) << “th Century!”<< endl;
}; return 0;
int main() }
{
date birth;
cout << “Enter your birth date!” << endl;
cout << “Year: “;
cin >> birth.year;
cout << “Month: “;
cin >> birth.month;
cout << “Day: “;
cin >> birth.day;
cout << “You entered “ << birth.month << “/”<<
3.3. Variables with Definition
 The syntax of „struct‟ also allows you to create variables based
on a structure definition without using two separate statements:
 struct tag
 {member(s);} variable;
 The structure variables created in this way will have the same
scope as their structure definition.
 This is a nice thing to use when you want to group some
variables in one place in your program without it affecting other
things.
 You can create a structure definition as well as variables from it
in that one local place and not have to ever use it again.
 Example: A „point‟ variable right after the „pointtag‟ structure is defined:
struct pointtag{
int x, y;
} point;
Continued…
 In this, „point‟ is a variable just as if we had declared it separately. In fact, this
statement is identical to:
struct pointtag{
int x, y;
};
pointtag point;
 Rather than defining a structure under a name and then creating
variables which refer to the named definition, the definition becomes
part of the variable declaration.
 It is even possible to omit the structure tag which may make more sense
in this situation:
struct{
int x, y;
} point;
 However, like in any variable declaration, you can create multiple
variables of the same type by separating them with commas:
struct{
int x, y;
} point1 = { 0, 0}, point2 = {0, 0};
4. Array of struct
#include<iostream.h> cout<<"\n Displaying student Info“;
#include<conio.h> cout<<"\nStudent Id \t Student Name";

struct student cout<<"\n==================“;

{ for( i = 0; i < 5; i++)

int id; {cout<<endl<<s[i].id<<"\t\t\t"<<s[i].name;

char name[15]; getch(); }

}; }

void main() Memory map of the above struct declaration.


{clrscr(); 0 id 1
//creating 5 student using an array name Tameru
student s[5]; 1 id 2
int i; name Hassen
for(i=0; i < 5; i ++) 2 id 3
{ cout<<"\n Enter Student Id"; name Selamawit
cin>>s[i].id; 3 id 4
cout<<"\nEnter Name"; name Asia
cin>>s[i].name; 4 id 5
} name Micheal
2. The following program declares and uses a book struct.
Also swaps the content of two book struct variables.
#include<iostream.h> cout<<"\n Before Changing Contents";
#include<conio.h> cout<<"\n Book id\t Title";
struct Book cout<<"\n=========================";
{ cout<<endl<<b1.id<<"\t\t\t"<<b1.title;
int id; cout<<endl<<b2.id<<"\t\t\t"<<b2.title;
char title[15]; //swapping content
}; temp=b1;
void main() cout b1=b2;
{ b2=temp;
//creating three Book variables cout<<"\nAfter swapping contents";
Book b1,b2,temp; cout<<"\n Book Information";
cout<<"\n Enter Book Id"; cout<<"\n Book id\t Title";
cin>>b1.id; cout<<"\n=========================";
cout<<"\nEnter Title"; cout<<endl<<b1.id<<"\t"<<b1.title;
cin>>b1.title; cout<<endl<<b2.id<<"\t"<<b2.title;
cout<<"\n Enter Book Id"; getch();
cin>>b2.id; }
cout<<"\nEnter Title";
cin>>b2.title;
cout<<"\n Book Information";
5. Declaring struct types as part of a struct
 A structure definition contains multiple variables, but not
necessarily just primitives. You can define a structure to have
structure member variables.
 Now if you have data's like birth of date of an employee, published
year of a book, address of a person. What are you going to do? You
must be able to incorporate this type of data's in other struct.
struct structname1
{
datatype1 variable1;
datatype2 variable2;
};
struct structname
{
datatype1 variable1;
datatype2 variable2;
Structname1 data1;
};
#include<iostream.h> //reading address attributes
#include<conio.h> cout<<"\nEnter Kebele";
struct Address{int kebele; cin>>s1.studaddress.kebele;
char Kebele_ketema[20]; cout<<"\nEnter Street Name";
char roadname[20]; }; cin>>s1.studaddress.roadname;
struct Student {int id; cout<<"\nEnter Kefle Ketema";
char name[15]; cin>>s1.studaddress.Kefle_ketema;
char section[6]; cout<<"\n Student Information";
//declaring address type within student cout<<"\n id\t Name\t Section \t Kebele";
Address studaddress; }; cout<<" \t Street Name \t Kefele Ketema ";
int main() cout<<"\n======================";
{//creating Student type that encapsulates cout<<endl<<s1.id<<"\t"<<s1.name;
Address cout<<"\t"<<s1.section<<"\t"<<s1.studaddress.keb
Student s1; ele;
cout<<"\n Enter Student Id"; cout<<"\t"<<s1.studaddress.roadname<<"\t";
cin>>s1.id; cout<<s1.studaddress.Kefle_ketema;
cout<<"\nEnter Student Name"; cin>>s1.name; return 0;
cout<<"\n Enter Section"; }
cin>>s1.section;
 The memory map of student s;
id 1
Asefa
name
RDDOB02
section
studaddress Kebele 21
Kefle_ketema Arada
Roadname Gahandi

 A structure only has to be declared before it can be used in another structure‟s


definition. The following is perfectly acceptable:
struct date;
struct time;
struct moment
{date theDate;
time theTime;};
struct date
{int day, month, year;};
struct time
{ int sec, min, hour;};
6. Defining Structure in Structure
 It is possible to define a structure inside a structure definition and
create variables from it at the same time. For example:
struct moment
{
struct date
{
int day, month, year;
} theDate;
struct time
{
int second, minute, hour;
} theTime;
};
 The drawback of the above is that the „date‟ and „time‟ definitions cannot
be used elsewhere without also referring to the parent structure. If the
„date‟ definition isn‟t going to be used elsewhere anyway, the structure
tag can simply be omitted.
1.The following program demonstrates how the structure definitions would be written as
well as uses the defined structure types in an extended “birth date” sample:
#include <iostream.h> cin>> birth.theDate.month;
struct date cout<< "Day: ";
{ int day, month, year; cin>>birth.theDate.day;
}; cout<<"Hour (military): ";
struct moment cin>>birth.theTime.hour;
{ cout << "Minute: ";
date theDate; cin >> birth.theTime.min;
struct cout << "Second: ";
{ cin >> birth.theTime.sec;
int sec, min, hour; cout << "You entered "<<birth.theDate.month<<
} theTime; "/"<<birth.theDate.day<< "/" <<birth.theDate.year<<"
@ "<<birth.theTime.hour<< ":"
}; <<birth.theTime.min<<":"<<birth.theTime.sec<< endl;
int main() if (birth.theTime.hour > 20 || birth.theTime.hour < 8)
{ cout << "You were born early in the morning!"
moment birth; << endl;
cout<<"Enter your birth moment!" << endl; return 0;
cout<< "Year: "; }
cin>> birth.theDate.year;
cout<< "Month: ";
Structure, Reference and Pointer
 References to structure variables, work the same way as normal references.
 To create one you would write out the name of the structure type,
followed by the reference name which is preceded by the reference
operator (&):
struct_name &reference;
 The following creates a structure variable based on „date‟ and a reference to
it:
 date birth;
 date &mybirth = birth;
 Both of these, „birth‟ and „mybirth‟, would have access to the same member
variables and their values. Thus they can be used interchangeably:
 birth.year = 1981;
 mybirth.year -= 2;
 Can you guess what the value of „birth.year‟ would be from the above? It
would be „1979‟.
 The reference „mybirth‟ is just an alias to „birth‟ and its group of member
variables. Remember that a reference is not a real variable (it has no value),
but simply a nickname for another.
Case Study 1:
Write a C++ program for student information
registration system based on the given specification. The
Program should accept the Student Id, full name, sex,
Birth date and address. The birth date should have day,
Month and year and the address also should have
Kebele, Kefele ketema, and road name. Your program
must register a (10) student and finally display the
recorded Student information to user.
Question:
???

You might also like