0% found this document useful (0 votes)
8 views

C++ ch3

Uploaded by

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

C++ ch3

Uploaded by

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

Debremarkos University Department of software Engineering

CHAPTER THREE
3. STRUCTURES

3.1. Introduction
In many occasions what we want to store are not mere sequences of elements of the same data
type (as in arrays), but sets of different elements with different data types. Structures offer a way
of joining these heterogeneous elements together to form complex structures.

A structure is a group of data elements grouped together under one name. These data elements
known as members (also called fields) can have different types, some can be int, some can be
float, some can be char and so on, and different lengths.

The difference between array and structure is the element of an array has the same type while the
elements of structure can be of different type. A structure is heterogeneous (composed of data of
different types). In contrast, array is homogeneous since it can contain only data of the same
type. Another difference is that each element of an array is referred to by its position while each
element of structure has a unique name.

Structures hold data that belong together. Examples:

 Student record: student id, name, major, gender, start year etc.

 Bank account: account number, name, currency, balance etc.

 Address book: name, address, telephone number etc.

3.2. Declaring a Structure


Structures are declared in C++ using the following syntax:
struct structure_name
{
Member_type 1 member_name1;
Member_type 2 member_name2;
Member_type 3 member_name3;
.
.
} object_names;

Where struct is a keyword, structure_name is a valid identifier name for the structure type;
object_name can be a set of valid identifiers for objects that have the type of this structure.
Within braces { } there is a list with the data members (structure variables), each one is specified
with a data type and a valid identifier as its name.

1|Page Fundamentals of Programming-II(ITec 2042)


Debremarkos University Department of software Engineering

For example:
Three variables: custnum of type int, salary of type int, commission of type float are structure members
and the structure name is Customer. This structure is declared as follows:

In the above example, it is seen that variables of different types such as int and float are grouped
in a single structure name Customer. Arrays behave in the same way, declaring structures does
not mean that memory is allocated. Structure declaration gives a skeleton or template for the
structure.
The first thing we have to know is that a structure creates a new type: Once a data structure is
declared, a new type with the identifier specified as structure_name is created and can be used in
the rest of the program as if it was any other type. After declaring the structure, the next step is to
define a structure variable.

3.2.1. Declaration of Structure Variables


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 cust1 is defined
as follows.

The structure variables are created in different ways.


 We can create structure variables at the time of declaration
Example
struct student
{
char name [20];
char Idd [10];
char Department [25];
int age;
} stud1, stud2, stud3;
2|Page Fundamentals of Programming-II(ITec 2042)
Debremarkos University Department of software Engineering

 We can create structure variables in such a way


struct student
{
char name [20];
char Idd [10];
char Department [25];
int age;
};
struct student stud1, stud2, stud3;

 We can also create structure variables as follows


struct student
{
char name [20];
char Idd [10];
char Department [25];
int age;
};
student stud1, stud2, stud3;

Here are examples of declaring structure variable.

#include<iostream.h> #include<iostream.h>
struct customer struct customer
{ {
int custnum; int custnum;
char name[10]; char name[10];
int phonenum; int phonenum;
}cust1,cust2,cust3;//structure variable declarn };
int main( ) int main( )
{ {
…. struct customer cust1,cust2,cust3;//structure variable declaration
} }

What happens when this is defined? When structure is defined, it allocates or reserves space in
memory. The memory space allocated will be cumulative of all defined structure members. In
the above example, there are 3 structure members: custnum, name and phonenum. If integer
space allocated by a system is 2 bytes and char one bytes the above would allocate 2 bytes for
custnum, 2 bytes for phonenum and 10 bytes for name; hence a total of 14 bytes for the structure.

3.2.2. Accessing structure Members


We use the dot operator (.) to access members of a structure. We use this format to read
(accept), to write (display) or assign data to members of a structure. The dot operator is one way
to initialize individual members of a structure variable in the body of your program. With the dot

3|Page Fundamentals of Programming-II(ITec 2042)


Debremarkos University Department of software Engineering

operator, you can treat each structure member almost as if it were a regular non-structure
variable.

The general syntax to access members of a structure variable would be:


StructureVariableName.MemberName

A structure variable name must always precede the dot operator, and a member name must
always appear after the dot operator. Using the dot operator is easy, as the following examples
show.
#include<iostream.h> #include<iostream.h>
struct customer struct customer
{ {
int custnum; int custnum;
char name[10]; char name[10];
int phonenum; int phonenum;
}cust1; };
int main ( ) int main ( )
{ {
cout<<”Enter customer number”<<endl; struct customer cust1;
cin>>cust1.custnum; cout<<”Enter customer number”<<endl;
cout<<”Enter customer name”<<endl; cin>>cust1.custnum;
cin>>cust1.name; cout<<”Enter customer name”<<endl;
cout<<”Enter customer phone number”<<endl; cin>>cust1.name;
cin>>cust1.phonenum; cout<<”Enter customer phone number”<<endl;
cout<<”Customer cin>>cust1.phonenum;
Number:”<<cust1.custnum; cout<<”Customer
cout<<”\nCustomer Name:”<<cust1.name; Number:”<<cust1.custnum;
cout<<”\ cout<<”\nCustomer Name:”<<cust1.name;
nCustomerPhone:”<<cust1.phonenum; cout<<”\
} nCustomerPhone:”<<cust1.phonenum;
}

3.2.3. Initializing structure members


You cannot initialize individual members because they are not variables. You can assign only
values to variables. The braces must enclose the data you initialize in the structure variables, just
as they enclose data when you initialize arrays. This method of initializing structure variables
becomes tedious when there are several structure variables (as there usually are). Putting the data
in several variables, each set of data enclosed in braces, becomes messy and takes too much
space in your code. You can initialize members when you declare a structure, or you can
initialize a structure in the body of the program.

For example:

4|Page Fundamentals of Programming-II(ITec 2042)


Debremarkos University Department of software Engineering

A programmer wants to assign 2000 for the structure member salary in the structure Customer
with structure variable cust1. This is written as:

For example
Initializing members at declaration Initializing members at the body of the program
#include<iostream.h> #include<iostream.h>
struct employee #include<string.h>
{ struct employee
char Emp_id[10]; {
char Name[20]; char Emp_id[10];
float Salary; char Name[20];
}emp1={“DMU/001”,”Zerihun”,2808}; float Salary;
int main() }emp1;
{ int main()
cout<<”Your id:”<<emp1.Emp_id<<endl; {
cout<<”Your name:”<<emp1.Name<<endl; strcpy(emp1.Emp_id,”DMU/001/”);
cout<<”Your salay”<<emp1.Salary<<endl; strcpy(emp1.Name,”Zerihun”);
} emp1.Salary=2808;
cout<<”Your id:”<<emp1.Emp_id<<endl;
cout<<”Your name:”<<emp1.Name<<endl;
cout<<”Your salay:”<<emp1.Salary<<endl;
}

3.3. Arrays of Structures


Arrays of structures are good for storing a complete employee file, inventory file, or any other
set of data that fits in the structure format. Consider the following structure declaration:
struct Company
{
int employees;
int registers;
double sales;
} store[1000];
In one quick declaration, this code creates 1,000 store structures with the definition of the
Company structure, each one containing three members.

5|Page Fundamentals of Programming-II(ITec 2042)


Debremarkos University Department of software Engineering

NB. Be sure that your computer does not run out of memory when you create a large number of
structures. Arrays of structures quickly consume valuable information.

You can also define the array of structures after the declaration of the structure.

struct Company
{
int employees;
int registers;
double sales;
}; // no structure variables defined yet

#include<iostream.h>
int main()
{
struct Company store[1000]; //the variable store is array of the structure Company

}

 Referencing the array structure


The dot operator (.) works the same way for structure array element as it does for regular
variables. Look the following example
#include<iostream.h>
struct student
{
int id;
float mark;
char name[15];
}stud[50];
int main( )
{
for(int i=0;i<50;i++)
{
cout<<"Enter the id, name and mark of student"<<i+1<<endl;
cin>>stud[i].id>>stud[i].name>>stud[i].mark;
}
for(int i=0;i<50;i++)
{
cout<<"Id of Student "<<i+1<<"="<<stud[i].id<<endl;
cout<<"Name of Student "<<i+1<<"="<<stud[i].name<<endl;
cout<<"Mark of student "<<i+1<<"="<<stud[i].mark<<endl;
}
}

6|Page Fundamentals of Programming-II(ITec 2042)


Debremarkos University Department of software Engineering

3.4. Nesting structures (structure within another structure)


Structures can also be nested so that a valid element of a structure can also be on its turn another
structure.

For example:
struct Book
{
char title[50];
int year;
};
struct student
{
char name[50];
char email[50];
Book favourite_Book;
} S1, S2;

Therefore, after the previous declaration we could use the following expressions (for example):
S1.name
S2.favourite_Book.title
S1.favourite_Book.year

For example, in the following program, we have the structure address nested in structure
employee to access member of a nested structure, we use the dot operator twice.

#include<iostream.h>
struct address
{
char street [30];
int distance;
};
struct employee
{
address branch;
char name[20];
};
int main ( )
{
employee emp1;
cout<<”Enter employee name: ”;
cin>>emp1.name;
cout<<”Enter branch street of the employee: “;
cin>>emp1.branch.street;
7|Page Fundamentals of Programming-II(ITec 2042)
Debremarkos University Department of software Engineering

cout<<”Enter distance of the branch: ”;


cin>>emp1.branch.distance;
cout<<”Employee “<<emp1.name<<” branch street is “ << emp1 . branch. street <<” and
it is “<< emp1.branch.distance<<” kms away”;
}

3.5. Pointers to structures


Like any other type, structures can be pointed by pointers. The rules are the same as for any
fundamental data type. The pointer must be declared as a pointer to the structure:
struct Book
{
char title[50];
int year;
};
Book b1;
Book * pb1;
Here b1 is an object of struct type Book and pb1 is a pointer to point to objects of struct type
Book. So, the following, as with fundamental types, would also be valid: pb1 = &b1;

Ok, we will now go with another example that will serve to introduce a new operator
// pointers to structures
#include <iostream.h>
struct Book
{
char title[50];
int year;
};
int main ( )
{
char buffer[50];
Book b1;
Book * pb1;
pb1 = &b1;
cout<< "Enter title of the book: ";
cin.getline (pb1->title, 50);
cout<< "Enter publication year: ";
cin.getline (buffer, 50);
pb1->year = atoi (buffer);
cout<< "\n The book information is:\n";
cout<<”Title: “<< pb1->title;
cout<< ", and it is published in " << pb1->year << "\n";
}

8|Page Fundamentals of Programming-II(ITec 2042)


Debremarkos University Department of software Engineering

The previous code includes an important introduction: operator->. This is a reference operator
that is used exclusively with pointers to structures and pointers to classes. It allows us not to have
to use parenthesis on each reference to a structure member. In the example we used:
pb1->title
could also be translated to:
(*pb1).title
Both expressions pb1->title and (*pb1).title are valid and mean that we are evaluating the
element title of the structure pointed by pb1.

3.6. Structures as Function Arguments


You can pass a structure as a function argument in very similar way as you pass any other
variable or pointer. You would access structure variables in the similar way as you have accessed
in the above example:

#include <iostream.h>
void printBook( struct Books book );
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan"); OUTPUT
strcpy( Book1.subject, "C++ Programming"); Book title : Learn C++
Book1.book_id = 6495407; Programming
// book 2 specification Book author : Chand Miyan
strcpy( Book2.title, "Telecom Billing"); Book subject : C++ Programming
strcpy( Book2.author, "YakitSingha"); Book id : 6495407
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700; Book title : Telecom Billing
// Print Book1 info Book author :YakitSingha
printBook( Book1 ); Book subject : Telecom
cout<<”\n\n”; Book id : 6495700
// Print Book2 info
printBook( Book2 );
}

9|Page Fundamentals of Programming-II(ITec 2042)


Debremarkos University Department of software Engineering

void printBook( struct Books book )


{
cout<< "Book title : " <<book.title<<endl;
cout<< "Book author : " <<book.author<<endl;
cout<< "Book subject : " <<book.subject<<endl;
cout<< "Book id : " <<book.book_id<<endl;
}

10 | P a g e Fundamentals of Programming-II(ITec 2042)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy