Chapter 5 cp
Chapter 5 cp
Structure
A simple data type can store only one value at a time
A structured data type is one in which each data item is
a collection of other data items
In a structured data type, the entire collection uses a
single identifier (name)
The purpose of structured data types is to group related
data of various types for convenient access using the
same identifier
Similarly, data can then be retrieved as an aggregate, or
each component (element) in the collection can be
accessed individually
2
Examples of structured data types in C++ are Arrays,
Structures and Classes
Arrays - collection of fixed number of components
(elements), wherein all of components have same data
type
One-dimensional array: array in which components are
arranged in list form
Two-dimensional array: array in which components are
arranged in tabular form
3
Defn :- An array is a group of logically related data items of the
same data type addressed by a common name, and all the
items are stored in contiguous (physically adjacent) memory
locations.
One dimensional array:
◦ Consecutive group of memory locations that all have the same type
◦ The collection of data is indexed, or numbered, and at starts at 0
◦ Position number is formally called the subscript or index
First element is subscript 0 (zero), sometimes called the zeroth element.
The highest element index is one less than the total number of elements in the
array
Array elements are distinguished from one anther by a subscript
A subscript is a number inside square bracket, [], that differentiates one
element of the array from the other
4
Homogeneous data:
◦ Homogeneous data structures are those data structures that
contain only similar type of data e.g. like a data structure
containing only integral values or float values
◦ The simplest example of such type of data structures is an
Array
Heterogeneous Data:
◦ Heterogeneous Data Structures are those data structures that
contains a variety or dissimilar type of data, for e.g. a data
structure that can contain various data of different data types
like integer, float and character
◦ The examples of such data structures include structures, class
etc
5
ARRAY STRUCTURE
Array refers to a collection consisting of elements of homogeneous data type. Structure refers to a collection consisting of elements of heterogeneous data type.
Array uses subscripts or “[ ]” (square bracket) for element access Structure uses “.” (Dot operator) for element access
Array is pointer as it points to the first element of the collection. Structure is not a pointer
Array size is fixed and is basically the number of elements multiplied by the size of an
element. Structure size is not fixed as each element of Structure can be of different type and size.
Array declaration is done simply using [] and not any keyword. Structure declaration is done with the help of “struct” keyword.
Array traversal and searching is easy and fast. Structure traversal and searching is complex and slow.
Array elements are stored in contiguous memory locations. Structure elements may or may not be stored in a contiguous memory location.
Array elements are accessed by their index number using subscripts. Structure elements are accessed by their names using dot operator.
6
Like other variables in C++, an array must be declared
before it can be used to store information
Like other variable declarations array declaration specifies
a variable type and name
In addition to this it also includes additional feature – size
The size specifies how many data items the array will
contain
It is specified with in square bracket in the array declaration
An array can have one or more dimensions
The dimension specifies the number of subscript (index)
values the array has
7
One dimensional array
◦ A one dimensional array is an array which has one subscript
(index) value and is referred to as a list
◦ A one dimensional array is declared using the following syntax
8
◦ The following are valid array definition statements
9
Accessing array elements
Once an array variable is defined, its element can be accessed by
using an index
The syntax for accessing array elements is
ArrayName[index]
Ex:
int number[10]; //defines number to be array of 10 elements
cout<<”Enter the numbers:”; //prompts for the numbers
for(int i=0;i<10;i++)
cin>>number[i]; //read the ith number and store it at the ith
//location in the array
10
we use loops ,usually the for loop is used , to read the elements of
an array
i, array index, indicates the element of the array, which has to be
accessed
Ex:
cout<<number[4]; //displays the 5th number on the screen
for(int j=0;j<10;j++)
cout<<number[i]; //displays the number at the ith location in the
// array number
11
EX:
the following reads elements of an array which has 5 elements
for( int i=0; i<5; i++)
{
cout<<"Enter person"<< i+1<<"age:";
cin>>age[i];
}
age[i]++; //increments the value of the ith item array age
age[1]=11; //assigns 11 to the second element
age[2]=25; //assigns 25 to the third element
Note:-
the expression age[3] is equivalent to3[age];
12
Initialization at Definition
Arrays can be initialized at the point of their definition as follows:
13
Note:
C++ dose not check for the validity of the array index value while
accessing the array elements
If the program tries to store something not within the size of an
array, neither the compiler nor the run-time will indicate the error
Such a situation may cause over writing of data or code leading to a
serious error
Therefore, the programmer has to take extra care to use indexes
within the array limits!
14
EX:
int age[40]; //It defines age to be an array of 40 integer and then
age[50]=11; // modifies the 51th element which is not with in the
//limit
age[50]=++;
The following shows memory representation for the array defined as
int age[4];
15
Ex: Write a program that accepts list of numbers from the keyboard and
counts the number of elements below the average
16
Sorting Array Elements
Sorting is the process of arranging set of values in some order relation
(ascending, descending).
Arrays are used to store set of values that are going to be sorted. There are
different sorting algorithms
The following program uses the most popularly known sorting algorithm
(bubble sort)
The bubble sort works as follows:
In each pass the first two items in a list are compared and placed in
the correct order
Items two and three are compared and then reordered, followed by
items three and four, then four and five, and so on
The sort continues until a pass with no swap (exchange) occurs
17
Ex: Bubble sort
18
Two dimensional array
A two dimensional array is also called a Matrix
Two subscripts are required to access each element of
a matrix
The general format for defining two-dimensional array
is
19
EX:
int mark[4] [3];
float b[3] [3];
The expression mark [0] [0],accesses the first element of the matrix
mark and mark[3][2] accesses the last row and last column
The representation of a two dimensional array (e.g. mark) in
memory can be shown as follows
20
21
Accessing Two Dimensional Array Elements
The elements of two dimensional arrays can be accessed by the following
way
Array Name[j][k]
Where j shows the row number and k shows the column number of
the current element
The subscripts must be integer constants or variables or they can be
expressions generating integer results
Ex
cout<<mark[2][2];
22
EX: Addition and subtraction of matrices
int main ()
{
int a[5] [5],b[5] [5],c[5] [5];
int i,j,m,n,p,q;
cout<<"Enter row and column size of A "
cin>>m>>n;
cout<<"Enter row and column size of B"
cin>>p>>q;
if ( (m = = p ) && ( n = = q ) )
{
cout<<"these matrices can be added or subtracted";
cout<<"Enter A’s elements";
for( i = 0; i<m; ++i )
for( j = 0; j<n; ++j)
cin>>a[i] [j];
cout<<"Enter B’s elements “;
for( i = 0; i<p; i++ )
for( j = 0; j<q; j++)
cin>>b[i] [j]);
23
for( i = 0; i<m; i++)
for(j = 0; j<n; j++)
c[i][j] = a[i][j] + [i][j];
cout<<"sum of A and B is";
for( i = 0; i<m; ++i )
{
for( j = 0; j<n; ++j )
cout<<c[i][j]<<" ";
cout<<endl;
for( i = 0; i<m; i++ )
for( j = 0; j<n; j++ )
c[i][j] = a[i][j]-b[i][j];
cout<<"Difference of Aand B is";
24
for( i=0; i<m; ++i)
{
for( j=0; j<n; ++j)
{
cout<<setw(2)<<c[i][j]<<" ";
}
cout<<endl;
}
}
return 0;
}
25
Initialization at the point of declaration
A two dimensional array can be initialized during its definition as
follows:
26
EX:
int a[3] [3]=
{
{1,2,3 },
{ 4,3,1},
{ 3,1,2 }
};
The first subscript (size of the row) can be omitted
Hence, the example can be written as:
27
int a[] [3]=
{
{1,2,3},
{4,3,1},
{3,1,2}
};
The inner braces can be omitted, permitting numbers to be
written in one continuous sequence as follows:
int a[] [3]={1,2,3,4,3,1,3,1,2};
28
Strings
A string is an array of characters whose end is marked
by the NULL ('\0') character
Strings are used in programming languages for storing
and manipulating text, such as words, names and
sentences
String constants are enclosed in double quotes
EX: "Hello World“
A string is stored in memory by using the ASCII codes
of the characters that form the string
29
Representation of the string "Hello World" in memory is as
follows
h
e
l
l
o
w
o
r
l
d
\0 * character string terminated by null character
30
String variable declaration
An array of characters representing a string is defined
as follows:
char array_name[size];
◦ the size of the array must be an integer value
EX: char name[50];
the length of this stirng can not exceed 49 since one
storage location must be reserved for the end of the
string marker (the NULL character \0)
31
Ex:
#include<iostream>
int main()
{
char name[50];
cout<<"Enter your name<49-max>:";
cin>>name;
cout<<"your name is: "<<name;
return 0;
}
32
Initialization at the point of declaration
The string variable can be initialized in two ways
i) char array-name[size]={list of values separated by
comma};
EX: char month[]={'A','p','r','i','l','\0'};
ii) C++ offers an other style for initializing an array of
characters
EX: char month[]="April";
Special characters can be embedded with in a string
When manipulated using C++ I/O operators, they are
interpreted as special characters and action is taken a
according to their defined meaning
33
5.2.1.String input/output
Reading string from keyboard
Just like other values, string is read from keyboard using cin
object
In the same way as other input values, cin skips over any leading
spaces and terminates reading a value when it encounters a
whitespace (space, tab, newline etc)
The null character will be appended to the end of the string in
character array by the stream function
Ex: if you would like to read full name from keyboard, you have
to create two string variables for the first name and last name and
read them one by one because if you try to read them together,
the reading will be terminated when it encounters blank space
34
char full_name[20];
cin>>full_name;
if the user enters Abebe Kebede
Only Abebe is read
To read the full name (and any other string value with more
than one word), we read them using separate variables as:
char first_name[10];
char last_name[10];
cin>>first_name>>last_name;
To read the entire string including white spaces, we use the
get() method of the cin object as in the following example
35
#include<iostream>
#include<string>
int main( )
{
char full_name[24];
cout<<"Enter full name";
cin.get(full_name,24);
cout<<"\nYour full name is:"<<full_name;
return 0;
}
36
Reading Multiple lines
In the above program the get() method takes two arguments (the
string variable identifier and the maximum number of characters
read including spaces
In this example the reading ends when the user hits the enter key
To read multiple lines, we use a third argument for the get()
method
By default, this third argument is the newline (‘\n’)
But if you call the method with some other character for this
argument, the default will be overridden by the specified
character
In the following example, the user can enter the first name and
last name on separate lines and end the input with $
37
#include<iostream>
#include<string>
using namespace std;
int main( )
{
char full_name[24];
cout<<"Enter full name";
cin.get(full_name,24,'$');
cout<<"\nYour full name is:"<<full_name;
return 0;
}
38
Writing string
String can be written on the screen using cout object
like other data values
When writing strings, the output can be affected by
escape sequences
39
5.2.2.String constants
String constants, also known as string literals, are a
special type of constants which store fixed sequences of
characters
A string literal is a sequence of any number of
characters surrounded by double quotes:
"This is a string literal"
The null string, or empty string, is written like "“
A literal string is stored internally as a given sequence
of characters plus a final null character
40
A null string is stored as a single null character
The characters inside the double quotes can include escape sequences
This code, for example:
"\t\"Name\"\\\tAddress\n\n
Prints like this:
"Name"\ Address
Adjacent string literals separated only by whitespace are concatenated
during the parsing phase
For example:
"This is" "just"
"an example"
is equivalent to
"This is just an example"
41
Line continuation with Backslash
You can also use the backslash (\) as a continuation
character to extend a string constant across line
boundaries:
"This is really \
a one-line string. "
42
5.2.3.String methods and manipulation
String Manipulations
C++ has several built-in function such as strlen(),strcar(), strlwl()
,---; for string pulation
To use these functions, the header string.h (String or cstring)
must be include in the program as
#include<string.h>
String length
The string function strlen ( ) return the length of a given string
A string constant or an array of characters can be passed as an
argument
The length of the string excludes the end-of- character(NULL)
43
EX:
#include<iostream>
#include<string.h>
int main( )
{
char s1[25];
cout<<"Enter your name:";
cin>>s1;
cout<<"your name is composed of :"<<strlen(s1)<<" characters";
return 0;
}
44
2) String copy
The string function strcpy( ) copies the content of one string to another
It takes two arguments; the first argument destination string array and the
second is the source string array
EX:
#include<iostream>
#include<string.h>
int main( )
{
char s1[25],s2[25];
cout<<"Enter a string:";
cin>>s1;
strcpy(s2,s1);
cout<<"strcpy(s2,s1)="<<s2;
return 0;
}
45
3) String concatenation
The string function strcat( ) concatenates two strings resulting a single string
It takes two arguments which are the destination and the source strings
The destination and the source strings are concatenated and the resultant is stored in
the destination (first) string
EX:
#include<iostream>
#include<string.h>
int main( )
{
char s1[40],s2[25];
cout<<"Enter string s1:";
cin>>s1;
cout<<"Enter string s2:";
cin>>s2;
strcat(s1,s2);
cout<<"strcat(s1,s2):"<<s1;
return 0;
}
46
4) String comparison
The string function strcmp( ) compares two strings, character by
character
It accepts two strings as parameters and returns an integer whose value
is
< 0 if the first string is less than the second
= = 0 if both are identical
>0 if the first string is greater than the second
Whenever two corresponding characters in the string differ, the string
which has the character with the higher ASCII value is greater
For example consider the string “hello” and “Hello”
The first character itself differs
The ASCII code for h is 104, while the ASCII code for H is 72
Since the ASCII code for h is greater, the string “hello” is greater than
the string “Hell”
Once a differing character is found there is no need to compare
remaining characters in the string
47
Ex:
#include<iostream>
#include<string.h>
int main( )
{
char s1[25],s2[25];
cout<<"Enter string s1:";
cin>>s1;
cout<<"Enter string s2:";
cin>>s2;
int status=strcmp(s1,s2);
cout<<strcmp(s1,s2);
if(status==0)
cout<< s1<<" is equal to "<<s2;
else
if(status > 0)
cout<<s1<<" is greater than "<<s2;
else
cout<<s1<<" is less than "<<s2;
return 0;
}
48
5) String to Upper/Lower case
The functions strlwr( ) and strupr( ) convert a string to lower case and upper
case respectively and return the address of the converted string
Ex:
#include<iostream>
#include<string.h>
int main( )
{
char s1[25],temp[25];
cout<<"Enter a string";
cin>>s1;
strcpy(temp,s1);
cout<<"strupr(temp):"<<strupr(temp)<<"\n";
cout<<"strlwr(temp):"<<strlwr(temp);
return 0;
}
49
Array of strings
An array of strings is a two dimensional array of
characters and is defined as follows:
char array_name[row_size][column_size];
For instance the statement
char person[10][15];
defines an array of string which can store names of ten
persons and each name can not exceed 14 characters
50
EXERCISES
1. Write a program that accepts a one dimensional array of integers from the user and computes the
average of the numbers
2. Write an interactive program for calculating grades of N students from 3 tests and present the result
in the following format
------------------------------------------------------------------------------------------
Sl/No Scores Average Gr
------------------------------------------------------------------------------------------
XX XX XX XX XX X
3. Write a program that reads in a two-dimensional array of integers with n rows and n columns and
interchanges the rows and columns of the array.
Ex: 4 3 2 1 4 5 0 8
5 7 4 9 3 7 5 8
0 5 6 2 becomes 2 4 6 0
8 8 0 4 1 9 2 4
51
4.Write a program that reads a two dimensional array of integers,
with n rows and n columns. The value of n is supplied by the
user. Your program then computes whether the array satisfies
any of the following conditions.
i. the array is symmetric. This would be the case if, for all i and j, we
have a [i,j]=a[j,i]; where a denotes the name of the array
ii. The array is diagonal. This would be the case if, whenever i != j,
we have a[i,j]=0, where a denotes the name of the array.
iii. The array is upper triangular. This would be the case if, for all i
and j;, if i>j, then a [i,j]=0.
52
6.Write a program to accept a line of text from the
keyboard and count the number of vowels and
consonants
7.Write a program that accepts an array of names from
the user and sorts the names in alphabetical order.
8.Write a program that accepts list of numbers and
displays the number which has the highest frequency.
53
String class
In the preceding sections we have seen how strings are
manipulated in C style programming which is also supported by
C++
In addition to this, the standard C++ library provides a string
class type that supports all the operations listed above and much
more functionality
To use the string class library, we have to include the string.h
header file in our source code
Variable declaration using string class
We have different ways of declaring variables using string class
EX:
string s; //declares an empty string variable;
s="Hello"; //initializes the string variable s
54
EX: Declaring and initializing a string variable with a copy of
existing value
string s1="Hello";
string s2(s1); //s2 is initialized to contain a copy of s1
EX:
string s1="Hello World";
string s2(s1,5); //s2 is initialized to contain the substring of s1
starting at position 5
55
Thus far you have worked with variable’s whose data types
are very simple: they are a numbers of either integer or
floating-point format with a specific range or characters
These types of variables, who only have a single value to
their name, are known as basic variables or primitives
Everything in computers is built on numbers, but not
necessarily singular types
Sometimes it’s advantageous to group common variables
into a single collection
For example a date would require a day, month, and year
From what we have discussed currently explained, you
could create three separate variables for each, like so:
int day, month, year;
56
This isn’t so bad, but what happens if you want to store
two dates and not one?
You’d have to create three more variables and give
them unique names:
int day1, month1, year1;
int day2, month1, year2;
This begins to become a hassle
Not only do you have to create many variables, but you
have to keep giving them unique names
C++ provides a way to collect similar variables into a
single structure
57
An array is a data structure which holds multiple
numbers of objects having the same basic property
(data type) in a contiguous memory slots
Programmer can also reserve contiguous memory space
for aggregates of elements of arbitrary data types each
A data type which is created to reserve such type of
memory space is called user defined data type
User defined data types can be equally used like
predefined data types to declare variable identifiers
For example we can define simple or array variable
identifier from this user defined data type
58
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
Once the type has been defined through the C++ ‘struct’
keyword, you can create variables from it just like you would any
other type
59
Since a structure definition is a grouping of several types: it
is a group of one or more variables
These are known as elements or member variables as they
are members of the structure definition they are part of
Following through with our hinted example, a structure
definition could be a ‘date’ which might be made up of
three ‘int’ member variables: ‘day’, ‘month’, and ‘year’
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
60
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
The element names within that variable will be the same as in the
structure type
If you create two structure variables from ‘date’, both will have
all three member variables with the same name in both: ‘day’,
‘month’, and ‘year’
Member variables are distinguished by the structure variable they
are part of
You wouldn’t simply be able to use ‘day’ by itself; instead you’d
have to refer to both the structure variable’s name (that you gave
when you created it) as well as ‘day’
61
5.3.1. Structure Definition and Declaration
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
Below is the syntax for a structure definition:
struct structname
{
datatype1 variable1;
datatype2 variable2;
};
62
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 - Do not forget this trailing semi-colon
when defining a structure!
The name of a structure definition is known as the structure tag
This will be the name of the type that you create, like ‘int’ or ‘float’
It is the type that you will specify when creating a structure variable
This structure block is remarkably similar to a statement block since it
starts and ends with curly braces
But don’t forget that it ultimately ends with a semi-colon
Within the structure block you declare all the member variables you
want associated with that type
Declare them as you would normal variables, but do not try to
initialize them
This is simply a data blue print, it is not logic or instructions and the
compiler does not execute it
63
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
64
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;
};
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;
};
65
A structure definition has the same type of scoping as a
variable
If you define a structure in a function, you will only be able
to use it there
If you define it in a nested statement block, you will only be
able to use it inside there and any statement blocks nested
within it
But the most common place is defining it globally, as in
outside of any functions or blocks
Typically, you’ll want to be able to create variables of the
defined structure anywhere in your program, so the
definition will go at the top
66
The following is an empty program that defines a ‘date’
structure globally:
#include <iostreamh>
struct date{
int day, month, year;
};
int main(){
return 0;
}
67
Declaring and using sturct 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
68
Storage for member variables exist at some offset from the beginning
of the glob of memory reserved by the entire structure
For example, in our ‘date’ structure variable the first member variable
is ‘day’ so it exists at offset 0
The next member variable, ‘month’ in this case, will exist at the next
available offset
If ‘day’ uses 4 bytes (32 bits), then ‘month’ will be at offset 4:
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
69
5.3.2.Initialization of Structure
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
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={"Abebe", "Scr/2222/22"};
70
This creates a variable called ‘nco_birthday’ and initializes
it to a list of values
The values are assigned to the member variables in the
order they are declared in the structure definition
Remember what is mentioned about each member variable
having an offset
The same order in which each member is given an offset is
the order in which each is assigned a value in an
initialization
So the first initializer is used to initialize the first member
variable in the structure, next is the second, and so on and
so forth
This order of initialization continues until the values run out
71
If you try to assign more values than are member variables,
you will get a compiler error
However, you can assign fewer values than there are
member variables
If there are no more values to be assigned, the assignment
will simply end
For example, if we had omitted the last value, ‘1979’, then
no value would be assigned to ‘year’
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 };
72
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 };
Assigning values to multiple members of a structure
variable is only possible when that variable is first created
Once a structure variable has been declared, you must
access each member individually
73
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
74
Example: to reading and displaying values to and from
structure s1
75
Example:-a program that creates student struct and uses it to store student information
#include<iostream>
using namespace std;
struct student
{
int id;
char name[15];
};
int main()
{
//creating three 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";
cin>>s2.name;
cout<<"\nStudents Information";
cout<<"\n Student id\t Student Name";
cout<<endl<<s1.id<<"\t"<<s1.name; This program shows you how to capture data
cout<<endl<<s2.id<<"\t"<<s2.name; in student variables.
return 0;
}
76
Example 2: This program demonstrates using member variables for user input, output, and
mathematical operations.
#include <iostream.h>
struct date
{
int day, month, year;
};
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 << “/”<< birth.day
<< “/” << birth.year << endl;
cout << “You were born in the “<< ((birth.year / 100) + 1)
<< “th Century!”<< endl;
return 0;
}
77
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;
78
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;
The above creates a structure variable called ‘point’ which has two member
variables
Because the structure definition is not named, it cannot be used elsewhere to create
variables of the same structure type
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, point2;
79
Now we have two structure variables of the same nameless structure
type
Even more fun we can initialize these structure variables as we
normally would:
struct{
int x, y;
} point1 = { 0, 0}, point2 = {0, 0};
This creates the two structure variables, ‘point1’ and ‘point2’, and
initializes both members, ‘x’ and ‘y’, on each to zero (0)
You don’t need to make a name-less definition to do this
You could still have a structure tag and initialize the variables created
after the definition
Note: Not only can you write name-less structures, but you can write
them without declaring any variables
This will cause a warning on smarter compilers, but is perfectly legal:
struct
{
int x, y;
};
80
The above structure definition can’t be used to create
any variables because it has no name
Likewise, no variables are declared after it either
So this is a nice way to fill up your programs with
useless source code
But why stop there?
You could make an empty, name-less definition:
struct { };
81
Array of structs
#include<iostream>
using namespace std;
struct student {
int id;
char name[15];
};
int main()
{
student s[5]; //creating 5 student using an array
int i;
for(i=0; i < 5; i ++)
{
cout<<"\n Enter Student Id";
cin>>s[i].id;
cout<<"\nEnter Name";
cin>>s[i].name;
}
cout<<"\n Displaying student Info";
cout<<"\nStudent Id \t Student Name";
cout<<"\n============================";
return 0; }
82
Memory map of the above struct declaration
0 id 1
name Tameru
1 id 2
name Hassen
2 id 3
name Selamawit
3 id 4
name
4 id 5
name Micheal
83
The following program declares and uses a book struct
Also swaps the content of two book struct variables
#include<iostream>
using namespace std;
struct Book {
int id;
char title[15];
};
int main(){
//creating three Book variables
Book b1,b2,temp;
cout<<"\n Enter Book Id";
cin>>b1.id;
cout<<"\nEnter Title";
cin>>b1.title;
cout<<"\n Enter Book Id";
cin>>b2.id;
cout<<"\nEnter Title";
cin>>b2.title;
cout<<"\n Book Information";
cout<<"\n Before Changing Contents";
cout<<"\n Book id\t Title";
84
cout<<"\n=========================";
cout<<endl<<b1.id<<"\t\t\t"<<b1.title;
cout<<endl<<b2.id<<"\t\t\t"<<b2.title;
//swapping content
temp=b1;
b1=b2;
b2=temp;
cout<<"\nAfter swapping contents";
cout<<"\n Book Information";
cout<<"\n Book id\t Title";
cout<<"\n=========================";
cout<<endl<<b1.id<<"\t"<<b1.title;
cout<<endl<<b2.id<<"\t"<<b2.title;
return 0;
}
85
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 day 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
structs
The following program declares two structs one for address and other for student
#include<iostream>
using namespace std;
struct Address{
int kebele;
char Kefle_ketema[20];
char roadname[20];
};
struct Student {
int id;
char name[15];
char section[6];
//declaring address type within student
Address studaddress;
};
86
int main(){
Student s1; //creating Student type that encapsulates Address
cout<<"\n Enter Student Id";
cin>>s1.id;
cout<<"\nEnter Student Name";
cin>>s1.name;
cout<<"\n Enter Section";
cin>>s1.section;
//reading address attributes
cout<<"\nEnter Kebele";
cin>>s1.studaddress.kebele;
cout<<"\nEnter Street Name";
cin>>s1.studaddress.roadname;
cout<<"\nEnter Kefle Ketema";
cin>>s1.studaddress.Kefle_ketema;
cout<<"\n Student Information";
cout<<"\n id\t Name\t Section \t Kebele";
cout<<" \t Street Name \t Kefele Ketema ";
cout<<"\n==================================";
cout<<endl<<s1.id<<"\t"<<s1.name;
cout<<"\t"<<s1.section<<"\t"<<s1.studaddress.kebele;
cout<<"\t"<<s1.studaddress.roadname<<"\t";
cout<<s1.studaddress.Kefle_ketema;
return 0;
}
87
The memory map of student s;
id 1
name Asefa
section RDDOB02
studaddress kebele 21
Kefle_ketema Arada
roadname Gahandi
88
Example: This assumes that ‘date’ and ‘time’ are structures that
have already been declared
struct moment
{
date theDate;
time theTime;
};
These structure members can then be accessed as normal
member variables, but then their variables must be accessed as
well
If there is a variable based on ‘moment’ called ‘birth’, then we
would need to write the following to assign ‘19’ to “birth’s date’s
day”:
birth.theDate.day = 19;
89
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;
};
90
To be able to define a structure you only must know the types
and the names of the member variables declared inside
With the above we declare the structures ‘date’ and ‘time’ but do
not define them until later
This simply acknowledges that they exist and they can therefore
be used within ‘moment’
What if ‘date’ and ‘time’ hadn’t defined?
It would still be legal, but then I would not be able to use
‘moment’ at all
Why? Since ‘date’ or ‘time’ have not been defined, the compiler
does not know how big they are supposed to be or what kind of
data they contain
You couldn’t then create a variable based on ‘moment’ because
the compiler doesn’t know how big of a memory block to
allocate
Likewise if you try to use a structure that has been declared
before it has been defined, you will encounter the same problem
91
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;
};
92
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
Thus we could remove the ‘date’ and ‘time’ structure
type identifiers and it would work fine
You can write any number of variables in a structure
definition and a valid variable declaration statement
(minus initialization of course) is valid inside a
structure definition
93
Let’s say we want to be able to use ‘date’ elsewhere, but not ‘time’
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>
struct date { int day, month, year; } ;
struct moment
{
date theDate;
struct
{
int sec, min, hour;
} theTime;
};
94
int main()
{
moment birth;
cout << “Enter your birth moment!” << endl; Note:-
cout << “Year: “; Any number of structure
cin >> birth.theDate.year; definitions can be nested; you can
cout << “Month: “; get extremely complex with
cin >> birth.theDate.month; structures, which is why they are
cout << “Day: “; sometimes known as complex
cin >> birth.theDate.day;
types.
cout << “Hour (military): “;
cin >> birth.theTime.hour;
cout << “Minute: “;
cin >> birth.theTime.min;
cout << “Second: “;
cin >> birth.theTime.sec;
cout << “You entered “ << birth.theDate.month << “/” << birth.theDate.day << “/” <<
birth.theDate.year
<< “ @ “ << birth.theDate.hour << “:” << birth.theDate.min << “:” << birth.theDate.sec
<< endl;
if (birth.theTime.hour > 20 || birth.theTime.hour < 8)
cout << “You were born early in the morning!” << endl;
return 0;
}
95
5.3.3.User defined data types (UDT)
A user defined data type is a typical data type that we can
derive out of any existing data type in a programming
language
We can utilize them for extending those built-in types that
are already available in a programming language, and then
you can create various customized data types of your own
The built-in data types originally present in a programming
language may not offer a wide variety of functions
But despite the various basic as well as derived data types
present, there is a special feature using which we can define
custom data types of our own, on the basis of our needs
96
The User-Defined Data Types are basically defined by a user
according to their will
These offer various functions on the basis of how one defines
them
Thus, these are termed to be “User-Defined”
In the preceding chapters, we have seen how to create user
defined data types using enum and typedef keywords
The enum refers to a keyword that we use for creating an
enumerated data type
The enum is basically a special data type (enumerated data type)
that consists of a set of various named values – known as
members or elements
We mainly use it for assigning different names to the integral
constants
This way, the program becomes much more readable
We use the keyword typedef for creating an alias (a new name)
for a data type that already exists
The typedef won’t create any new form of data type
97
In this chapter we have seen how we work with structures
We use the structure for organizing a group of various data items into
one single entity – for grouping those data items that are related but
might belong to different data types
The structure data types are related (usually), such as the different sets
of information regarding a person, an account, or a part, etc
Every data item present in a structure is known as a member
These members are sometimes also known as fields
We use the struct keyword for creating a structure
The primary advantage of using a structure is that it becomes very easy
for a person to access the members
It is because the allocation of all the members that belong to a specific
structure is in the continuous memory
Thus, structure helps in minimizing the memory access time for any
program
98