0% found this document useful (0 votes)
4 views95 pages

Understanding Arrays in C++ Programming

cpp

Uploaded by

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

Understanding Arrays in C++ Programming

cpp

Uploaded by

gtekileyesus
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

1

Computer Programming II
(SEng2021)

Chapter-Two
ARRAYS AND
STRUCTURE
Introduction 2
 Array is a group of similar types of elements that
have contiguous memory location.
 An array is a data structure, which can store a
fixed-size collection of elements of the same data
type. An array is used to store a collection of data,
but it is often more useful to think of an array as a
collection of variables of the same type.
 All arrays consist of contiguous memory locations.
The lowest address corresponds to the first element
and the highest address to the last element.
Cont… 3
 A simple example program will serve to introduce arrays. This
program, ARRAY1, creates an array of four integers
representing the ages of four people. It then asks the user to
enter four values, which it places in the array.
 Finally, it displays all four values. // [Link] // gets four ages
from user, displays them
 #include using namespace std;
 int main() {
 int age[4]; //array ‘age’ of 4 ints
 for(int j=0; j<< “Enter an age: “;
 cin >> age[j]; //access array element }
 for(j=0; j<4;j++)//displays for array element
 cout<< “You entered “ << age[j] << endl;
 return 0; }
Cont… 4
 Advantages of Array
 An array implementation allows Print to be carried out in linear time and
Find operation in constant time, which is good as can be expected
 Random access is possible
 Implementation of list using array is easier as compared to other
implementations
 Disadvantages of Array
 Elements of arrays are always stored in contiguous memory
 Inserting or deleting an element in an array may require all of
its elements to be shifted
 The size of array is always fixed
 You cannot add a new element beyond the end of the array
 Memory for the entire array is always reserved even though you
use only part of the array
 You must guess the expected maximum size of the list in
advance.
Declaration of Array 5
 The general form for declaring a one-dimensional
array is:
datatype arrayName[ArraySize];
 This is called a single-dimensional array.
The arraySize must be an integer constant greater
than zero and type can be any valid C++ data type.
For example, now to declare a 5-element array
called number of type int, use this statement
 Example: int num[5];
 Here, num is a variable array, which is sufficient to
hold up to 5 integer numbers.
 Declares an array num of five components. Each component
is of type int. The components are num[0], num[1], num[2],
num[3], and num[4].
Cont… 6
 product numbers:
 int product[] = {12, 36, 78, 09};
 student scores:
 int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};
 characters:
 char words[5] = {’A’, ’b’, ’C’, ’d’, ’E’};

 Size of array must be fixed at compile time.


 We can also declare arrays as follows:
const int ARRAY_SIZE = 10;
int list[ARRAY_SIZE];
 we cannot do the following:
int arraySize; //Line 1
cout << "Enter the size of the array: "; //Line 2
cin >> arraySize; //Line 3
cout << endl; //Line 4
int list[arraySize]; //Line 5; not allowed
 Specifying the size of an array during program execution possible
using pointers called dynamic array.
Accessing Array 7

Elements
The general form (syntax) used
component is:
for accessing an array

 arrayname[index];
 in which index, called the index, is any expression whose
value is a nonnegative integer. The index value specifies the
position of the component in the array.
 In C++, the array index starts at 0 and last index size-1.
 Example: int list[10];
 This statement declares an array list of 10 components. The
components are list[0], list[1], . . ., list[9]. In other words, we
have declared 10 variables.
 First [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] (Last)

 List
Cont… 8
 The assignment statement:
list[5] = 34;
stores 34 in list[5], which is the sixth component of the array
list
[0] [1] [2] [3] [4] [5] [6] [7] [8]
[9]

int i=3; list[i]=10;


list[6]=list[3]+list[5];
cin>>list[2];
cout<<list[2];

10 34 44
Array Initialization During
Declaration 9
 Like any other simple variable, an array can be initialized
while it is being declared by list enclosed in curly brace.
 When initializing arrays as they are declared, it is not
necessary to specify the size of the array.
 The size is determined by the number of initial values in the
braces.
 double sales[ ] = {12.25, 32.50, 16.90, 23, 45.68};
 int list[10] = {0};
 declares list to be an array of 10 components and initializes all of the
components to 0.
 When you declare and initialize an array simultaneously,
we do not need to initialize all components of the array.
 This procedure is called partial initialization of an array
during declaration.
Cont… 1
0
 The following examples help to explain what happens when you
declare and partially initialize an array. The statement:
int list[10] = {8, 5, 12};

int list[10] = {2, 5, 6, , 8}; //illegal

 If too few values are listed in an initialization statement


 The listed values is used to initialize the first of the indexed variables.

 The remaining indexed variables are initialized to zero of the base type

 Example: int a[10] = {5, 5};


initializes a[0] and a[1] to 5 and a[2] through a[9] to 0
Processing One-Dimensional
1
Arrays 1
 Some of the basic operations performed on a one-dimensional array are:
 Initializing :array using assignment operator[=].
 Inputting: data to the array using cin >> statement.
 Outputting: data stored in the array using cout << statements.
 double sales[10];
 int index;
 double largestSale, sum, average;
 Initializing an array:
 for (index = 0; index < 10; index++) sales[index] = 0.0;
 Reading data into an array:
 for (index = 0; index < 10; index++) cin >> sales[index];
 Printing an array element:
 for (index = 0; index < 10; index++) cout<<sales[index] <<“ ";
 Largest element in the array:
maxIndex = 0;
for (index = 1; index < 10; index++){
if (sales[maxIndex] < sales[index])
maxIndex = index;}
largestSale = sales[maxIndex];
Base Address of an Array and Array in
Computer Memory 1

2
The base address of an array is the address (that is, the
memory location) of the first array component.
 Declaring the array int a[6]:
 Reserves memory for six variables of type int
 The variables are stored one after another
 The address of a[0] is remembered called base address.
 The addresses of the other indexed variables is not remembered
 To determine the address of a[3]
 Start at a[0]
 Count past enough memory for three integers to find a[3]
1
3
Cont… 1
4
 Suppose that you also have the following statement:

int yourList[5];

int myList[5];

 Then, in the statement:

if (myList <= yourList)


...

 The expression myList <= yourList evaluates to true if the base


address of the array myList is less than the base address of the array
yourList; and evaluates to false otherwise.

 It does not determine whether the elements of myList are less than or
equal to the corresponding elements of yourList.
Array Index Out of 1
5
Bounds


In C++, there is no guard against out-of-bound indices.
If the index goes out of bounds and the program tries to access
the component specified by the index, then whatever memory
location is indicated by the index that location is accessed.
 This situation can result in altering or accessing the data of a
memory location that you never intended to modify or access.
 Consider the following declaration: double num[10]; int i;
 The component num[i] is valid, that is, i is a valid index if
i= 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9.
 The index—say, index—of an array is in bounds.
 if index >= 0 and index <= ARRAY_SIZE - 1.
 If either index < 0 or index > ARRAY_SIZE - 1, then we say
that the index is out of bounds.
Cont…. 1
6
 A loop such as the following can set the index out of bounds:

int list[10];

for (i = 0; i <= 10; i++)

list[i] = 0;

 Here, we assume that list is an array of 10 components. When i


becomes 10, the loop test condition i <= 10 evaluates to true and
the body of the loop executes, which results in storing 0 in list[10].
Logically, list[10] does not exist.

 If we use an array index that is out of bounds, then the compiler will
probably compile and even run. But, there is no guarantee to get the
correct result.

 Result may unpredictable and it will start causing many problems that
Some Restrictions on Array
1
Processing 7
 Consider the following statements:
int myList[5] = {0, 4, 8, 12, 16};
int yourList[5];
 same type and have the same number of
components.
1) C++ does not allow aggregate operations on an array.
 Suppose that you want to copy the elements of myList into the
corresponding elements of yourList. The following statement is
illegal:
yourList = myList;
 To copy one array into another array, you must copy it component-
wise—that is, one component at a time. This can be done using a
loop, such as the following:
for (int index = 0; index < 5; index ++)
yourList[index] = myList[index];
Cont… 1
8
2) Read data into the array yourList.
 The following statement is illegal and, in fact, would
generate a syntax error:
cin >> yourList;
 To read data into yourList, you must read one
component at a time, using a loop such as the following:
for (int index = 0; index < 5; index ++)
cin >> yourList[index];
3) Printing the contents of an array
 The following statement is illegal and, in fact, would
generate a syntax error:
cout << yourList; //print base address of yourlist
Cont… 1
9
 To printing the contents of an array
for (int index = 0; index < 5; index ++)
cout<< yourList[index];
4) Determining whether two arrays have the
same elements
 Following statements are illegal in the sense that
they do not generate a syntax error; however, they
do not give the desired results.
if (myList <= yourList)
Multidimensional 2
0
Arrays
For example, suppose that you want to track the number of
cars in a particular color that are in stock at a local dealership.
The dealership sells six types of cars in five different colors.
Cont… 2
1
 we can declare a one-dimensional array of 30 components of
type int.
 first five components of the one-dimensional array can store
the data of the first row of the table, the next five components
can store the data of the second row of the table, and so on.

 If you do so, the algorithms to manipulate the data in the one


dimensional array will be somewhat complicated, because you
must know where one row ends and another begins.
 You must also correctly compute the index of a particular element.

 C++ simplifies the processing of manipulating data in a table


form with the use of two-dimensional arrays.
Cont… 2

2
Multi-dimensional array a collection of a fixed number of components arranged
in rows and columns (that is, in two dimensions), wherein all components are of
the same type.
 The syntax for declaring a two-dimensional array is:
dataType arrayName[intExp1][intExp2];
 Wherein intExp1 and intExp2 are constant expressions yielding positive integer
values specify the number of rows and the number of columns, respectively, in
the array.
 If the data is provided in a list form, you can use one-dimensional arrays.
However, sometimes data is provided in a table form.
 The statement:
double sales[10][5];
 Declares a two-dimensional array sales of 10 rows and 5 columns, in which every
component is of type double.
 Like one-dimensional array, the rows are numbered 0. . .9 and the columns are numbered 0.
. .4.
Accessing 2D Array
Components 2
3
 To access the components of a two-dimensional array, you
need a pair of indices: one for the row position and one for the
column position.
 The syntax to access a component of a two dimensional array
is:
arrayName[indexExp1][indexExp2];
eg sales[3][2];
sales[1][2];
sales[5][3] = 25.75;
 Suppose that: int i = 5; int j = 3; Then, the previous statement:
sales[5][3] = 25.75; is equivalent to: sales[i][j] = 25.75; So the
indices can also be variables.
Two-Dimensional Array Initialization 2
During Declaration 4
 To initialize a two-dimensional array when it is declared we have to consider
the following rules:
 The elements of each row are enclosed within curly braces and separated by
commas.

 All rows are enclosed within curly braces.

 For number arrays, if all components of a row are not specified, the
unspecified components are initialized to 0. In this case, at least one of
the values must be given to initialize all the components of a row.
 int board[4][3] = {{2, 3, 1}, {15, 25, 13}, {20, 4,7},{11, 18, 14}};
 This statement declares board to be a two-dimensional array of four rows and
three columns.
 names: char names[][40] ={“Peter”, “Mary”, “Lisa”, “John”, "George-
Simon"};
 3D coordinates: Vector coordinates[4][3] = {{0, 0, 0}, {1, 0, 1}, {1, 0, 5},
{4, 7, 9}};
Processing Two-dimensional
2
Arrays 5
 A two-dimensional array can be processed in three ways:
 Process the entire array.
 Process a particular row of the array, called row
processing.
 Process a particular column of the array, called
column processing.
 Initializing and printing the array are examples of
processing the entire two-dimensional array.
 Finding the largest element in a row (column) or finding
the sum of a row (column) are examples of row (column)
processing.
Initialization and Input 2

6
Suppose that you want to initialize row number 4, that is, the
fifth row, to 0. the following for loop does this:
row = 4;
for (col = 0; col <NUMBER_OF_COLUMNS; col++)
matrix[row][col] = 0;
OR
cin >> matrix[row][col];
 If you want to initialize the entire matrix to 0, you can also put
the first index, that is, the row position, in a loop. By using the
following nested for loops, we can initialize each component of
matrix to 0:
for (row = 0; row < NUMBER_OF_ROWS; row++)
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
matrix[row][col] = 0;

OR
cin >> matrix[row][col];
Output the Elements 2

7
By using a nested for loop, you can output the components of
matrix. The following nested for loops print the components of
matrix, one row per line:
for (row = 0; row < NUMBER_OF_ROWS; row++){
for (col = 0; col < NUMBER_OF_COLUMNS; col++){
cout << matrix[row][col] << " ";}
cout << endl;}

 The following for loop finds the sum of row number 4 of


matrix; that is, it adds the components of row number 4:
sum = 0;
row = 4;
for (col = 0; col < NUMBER_OF_COLUMNS; col++){
sum = sum + matrix[row][col];
}
Cont… 2

8
Once again, by putting the row number in a loop, we can find the sum
of each row separately. The following is the C++ code to find the sum
of each individual row: //Sum of each individual row
 for (row = 0; row < NUMBER_OF_ROWS; row++){
sum = 0;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
sum = sum + matrix[row][col];
cout << "Sum of row " << row + 1 << " = " << sum << endl;
}
 The following nested for loop finds the sum of each individual
column: //Sum of each individual column
 for (col = 0; col < NUMBER_OF_COLUMNS; col++){ sum = 0;
for (row = 0; row < NUMBER_OF_ROWS; row++)
sum = sum + matrix[row][col];
cout << "Sum of column " << col + 1 << " = " << sum
<< endl;
}
Largest Element in Each Row and 2
Each Column 9
 The following C++ code determines the largest element in
each row and each column:
//Largest element in each row
 for (row = 0; row < NUMBER_OF_ROWS; row++)
{
//Assume that the first element of the row is the largest.
largest = matrix[row][0];
for (col = 1; col < NUMBER_OF_COLUMNS; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout << "The largest element in row " << row + 1 << " =
“ << largest << endl;
}
Cont… 3
0
 //Largest element in each column
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{
//Assume that the first element of the column
is the largest.
largest = matrix[0][col];
for (row = 1; row < NUMBER_OF_ROWS; row++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout << "The largest element in column " <<
col + 1 << " = " << largest << endl;
}
(C-strings)Character of 3
Array

1
Character array: An array whose components are of type char. Null-
Terminated Strings is a null-terminated character array.
 It contains the characters that comprise the string followed by a null.
 When declaring a character array that will hold a null-terminated string,
you need to declare it to be one character longer than the largest string
that it is to hold if not its syntax error.
 The null character, '\0', is used to mark the end of a C string that is
stored
in an array of characters.
 Syntax: char Array_Name[Maximum_C_string_Size + 1];
 For example, declare an array str that can hold a 10-character string
char str[11];
 You can initialize a C-string variable when you declare it, as illustrated
by the following example:
char my_message[20] = "Hi there.";
 f
Cont… 3

2
When you initialize a C-string variable, you can omit the array size. C+
+ will automatically make the size of the C-string variable 1 more than
the length of the quoted string. (The one extra indexed variable is for '\
0'.) For example,
char short_string[] = "abc"; is equivalent to
char short_string[4] = "abc";
 Be sure you do not confuse the following initializations:
char short_string[] = "abc"; and
char short_string[] = {'a', 'b', 'c'};
They are not equivalent.
 A C-string variable is a partially filled array of characters. Like any other
partially filled array, a C-string variable uses positions starting at
indexed
variable 0 through as many as are needed.
 Thus, if s contains the string "Hi Mom!", then the array elements are
filled as shown here:
Cont… 3

3
When manipulating these indexed variables, you should be very
careful
not to replace the null character '\0' with some other value.
 If the array loses the value '\0', it will no longer behave like a C-
string variable.
 For example, the following will change the array happy_string
so that it no longer contains a C string:
char happy_string[7] = "DoBeDo";
happy_string[6] = 'Z';
 After this code is executed, the array happy_string will still
contain the six letters in the C-string "DoBeDo", but
happy_string will no longer contain the null character '\0' to
mark the end of the C string.
 Many string-manipulating functions depend critically on the
presence of '\0' to mark the end of the C-string value.
Processing Character 3

Array 4
Aggregate operations, such as assignment and comparison, are not
allowed on arrays. Even the input/ output of arrays is done
component-wise.
 However, the one place where C++ allows aggregate operations on arrays
is the input operator >> and output operator << of C-strings but all
whitespace (blanks, tabs, and line breaks) are skipped when C strings are
read this way Doesn’t read whitespace
 char name[31];//input C-string must be less than or equal to 30.
cin >> name;//not read whitespace and stop reading as soon as first
whitespace.
char a[80], b[80];
cout << "Enter some input:\n";//Do be do to you
cin >> a >> b;
cout << a << b << "END OF OUTPUT\n"; //DobeEND OF OUTPUT

 To read string(with whitespace) get function can be used.


 [Link](char, m + 1); stores the next m characters, or all characters until
the newline character '\n' is found, into char.
 To read and store a line of input, including whitespace characters, you
can also use the stream function getline.
Cont… 3

5
Suppose that you have the following declaration:
char textLine[100];
 The following statement will read and store the next 99 characters, or
until the newline character, into textLine. The null character will be
automatically appended as the last character of textLine.
[Link](textLine, 100);
[Link](str,max,’$’);//terminates with $
 Now you can type as many line. The function will continue to accept
character until you enter the terminated character $ or until exceed the
size of the array.
 The output of C-strings is another place where aggregate operations on
arrays are allowed.
 You can output C-strings by using an output stream variable, such as
cout, together with the insertion operator, <<.
 For example, the statement: cout << name; outputs the contents of
name on the screen.
Cont… 3

6
Aggregate operations such as assignment and
comparison, are not allowed on arrays.
 char name[10];
 name=“student”; //illegal
 C/C++ supports a wide range of functions that
manipulate null-terminated strings. The functions
use the standard header file string.h.
Cont… 3

7
You can copy string using strcpy and strncpy function.
Prototype of this function is in string.h
 Strcpy(destination, source);
 Copies character from location specified by source to the location
specified by destination.
 Stop copying character after it copies the terminating null
character.
 Return value is the value of destination parameter.
 Make sure that destination string is large enough to hold all of the
character in the source.
 Strncpy(destination, source, int n);
 It may not copy the terminating null character only copies
specified number of character.
Cont… 3

8
You can concatenating string by using strcat() and strncat()
function.
 Strcat(destination, source);
 First character of the source string is copied to the location of the
terminating null character of the destination string.
 Destination string must have enough space to hold both string
and a terminating character.
 Strncat(destination, source, int n);
 Copies only specified number of character.
Cont… 3
9
char myname[]=“My Name”;

char yourname[]=“Your Name”;

char char3[20];
Your Name
strcpy(char3, yourname);

cout<<char3<<endl; Your NameMy Name

strcat(char3, myname); 16

cout<<char3 <<endl;
1
cout<< strlen(char3)<<endl;

cout<<strcmp(char3,myname) <<endl;
Arrays of Strings
 Arrays of string: An array whose components are of type string.
 Strings in C++ can be manipulated using either the data type string or
character arrays (C-strings).
 Processing a list of strings using the data type string is straightforward.
 Suppose that the list consists of a maximum of 100 names. You can
declare an array of 100 components of type string as follows:
string list[100]; // declare an array of 100 components of type string
 Basic operations, such as assignment, comparison, and input/output, can
be performed on values of the string type. Therefore, the data in list can
be processed just like any one-dimensional array discussed in the first
part of this chapter.
 Assignments operations3 = s1; //ch2=ch3 not possible in character array
 Concatenating operations1+s2;
 Comparison operation s1<s2;
 Insertion operation cout <<s3;

 Extraction operatorcin>>s2;

Defining and Assigning
string 4

1
Defining string object.
 constructor with no arguments.

Objects
use a one-argument constructor.
 string str1(“Software”); string str2 = “Engineering”; string str3;
 objects of class string can be assigned to one another with a
simple assignment operator. Software Engineering
str3 = str1 + str2; cout << str3;
[Link](i);
[Link](pos, str2);
[Link](pos, length);
[Link](str2);
 The following example std::string to Initialize, Store User Input,
Copy, Concatenate, and Determine the Length of a String
Cont…. 4
/*String Manipulation */
2
string str1, str2;

string varInitializing("Variable Declaration with Initializing


");

cout<<"Enter the first string "; getline(cin,str1);

cout<<"\nEnter the Second string "; getline(cin,str2);

cout<<" result of concatenation "<<endl;

string concatString =str1+ “ ” + str2;


cout<<concatString<<endl;

cout<<"The Result of copy string "<<endl;

string copyString; copyString=str1;

cout<<" "<<copyString<<endl;

cout<<"Length of concatenation string =


"<<[Link]()<<endl;

/*String Manipulation */
Member Functions of the 4
Standard string Class 3
Cont… 4
4
Structure 4

5
Although arrays greatly improved our ability to store data, there
is one major drawback to their use,...each element in an array
must be of the same data type.
 It is often desirable to group data of different types and work
with that grouped data as one entity. we now have the power to
accomplish this grouping with new data type called a
structure(Records ).
 Structure is a collection of variables of different data types
under a single name. It is similar to a class in that both holds a
collection of data of different data types.
 A structure can contain both built-in data types and another
structure.
 The concept of structure is pretty much the same as arrays
except that in array, all the data is of the same types but in a
structure, the data can be of different types.
Cont… 4

6
Example:
 Suppose that you want to write a program to process student data. A
student record consists of, among other things, the student’s name,
student ID, GPA, courses taken, and course grades.
 Thus, various components are associated with a student. However,
these components are all of different types. For example, the
student’s name is a string, and the GPA is a floating-point number.
 Because these components are of different types, you cannot use an
array to group all of the items associated with a student.
 C++ provides a structured data type called struct to group items of
different types. Grouping components that are related but of
different types offers several advantages. For example, a single
variable can pass all the components as parameters to a function.
What is structure? 4

7
“ A structure is a collection of variables under a single name.
These variables can be of different ,and each has a name that is
used to select it from the structure”
 A collection of a fixed number of components in which the
components are accessed by name. The components may be of
different types.
 There is always a requirement in most of our data processing
applications that the relevant data should be grouped and
handled as a group.
 In structure, we introduce a new data type.
 A structure can contain any data type including array and
another structure as well.
 It provides a simple method of abstraction and grouping.
 Each variable declared inside structure is called member of
structure.
Cont… 4

8
A structure may itself contain structure.
 A structure can be assigned to as well as passed to and
returned from functions.
 We declare a structure using the keyword struct.
 Student{-name,Address,Date of birth,CGPA,Displine
 Car{model,Manufacturer Company,Engine size,Number of
seats,
 Employee{Employee Id,Name,De’t,Date of Joining,Salary.
 When to use a Structure?
 Here are some reasons using structure in C++.
 Use a struct when you need to store elements of different data types under
one data type.
 C++ structs are a value type rather than being a reference type. Use a
struct if you don’t intend to modify your data after creation.
Structure Vs Class 4
9
Step to create 5
0
Structure


Declare structure
Initialize Member of structure
 Access Structure Elements.
 Declare structure
 struct keyword is used for creating structure.
 Structure declaration ways
 By struct keyword
 By declaring variable at the time of defining structure.
Declaration of 5
1
Structure
The structure is declared by using keyword struct followed by
structure name, also called a tag.
 Then the structure member(variables) are defined with their type
and variable names inside the open and close braces{ and }.
 Finally, the closed braces end with a semicolon denoted as ;
following the statement.
 The above structure declaration is called a structure specifier.
 Structure are syntactically declared with:
 Keyword struct
 Followed by the name of structure
 The data contained in the structure ,is defined in the curly braces
 All the variables that we have been using can be part of structure.
Cont… 5

2
struct struct_name{
member_type1 member_name1;
member_type1 member_name2;
member_type1 member_name3;
}
 struct student{
char name[60];
char address[100];
char discipline[50];
float GPA;
}
Note: Memory is not allocated at the time of its declaration.
Memory is allocated when we declare structure variable.
Cont… 5
3
 The most efficient method of dealing with structure
variables is to define the structure globally.
 This tells “the whole world", namely main and any
functions in the program, that a new data type
exists.
 To declare a structure globally, place it before int
main().
 struct Student{
The structure variables can then be defined locally in
string name,street,city,state,zipcode;
main, int age;
 double Id_num;
Approach1
double grade;
};
int main(){
//declare two variables of the new type
Student student1,student2;
Cont… 5

4
Approach2:

struct Student{
string name,street,city,state,zipcode;
int age;
double Id_num;
double grade;
}Student1,student2;
Accessing Structure
5
Members 5
 To access any member of a structure, we use the
member access operator(.).
 The member access operator is coded as a period
between the structure variables name and the structure
member that we wish to access.
 [Link]
 Remember we would use struct keyword to define
variables of structure type.
 Suppose ,you want to access age of structure variable
student1 and assign it 50 to it. we can perform this task
by using the following code:
 [Link]=50;
 Taking input as: cin>>[Link];
Cont… 5
 Example: C++ program to assign data members
6
of a structure variables and display it.
struct Person{
char name[50]; //Displaying entered information
int age; cout<<“Display Information”;
float salary; cout<<“Name:”<<[Link]<<
}; endl;
int main()[ cout<<“Age:”<<[Link]<<endl;
Person p1; cout<<“Salary:”<<[Link];
cout<<“Enter full
name”;
[Link]([Link],50);
cout<<“Enter age”;
cin>>[Link];
cout<<“Enter salary”;
cin>>[Link];
Initializing Structure 5

7
Like normal variable structures can be initialized at the time of
declaration. Initialization of structure is almost similar to
initializing array.
 The structure object is followed by equal sign and the list of
values enclosed in braces and each values is separated with
comma.
 Example:
 Person p1={“Borif”,25,6000};// first way
 Person p2;
 [Link]=“Bona”;//second way
 [Link]=30;
 [Link]=5000;
Structure Variables in Assignment
Statement 5
8
 P1=p2
 The statement assigns the value of each member of
p2 to the corresponding member of p1.
 Note that one structure variable can be assigned to
another only when they are of the same structure
type, otherwise compiler will give an error.
 Limitations with structures
S1+s2
S1-s2 S1=s2
S1*s2
S1/s2
Comparison (Relational
Operators) 5
9
 To compare struct variables, you compare them member-
wise.
 As with an array, no aggregate relational operations are
performed on a struct.
 For example, suppose that p1 and p2 are declared as
shown earlier. Furthermore, suppose that you want to see
whether p1and p2 refer to the same Person.
 Now p1 and p2 refer to the same student if they have
the same name, age and salary.
 To compare the values of p1and p2, you must
compare them member-wise, as follows:
 If([Link]==[Link] && [Link]==[Link] &&
[Link]==[Link])
Cont… 6

0
Although you can use an assignment statement to copy the
contents of one struct into another struct of the same type, you
cannot use relational operators on struct variables.
 Therefore, the following would be illegal:
if (p1== p2) //illegal
...
Pointers to Structure 6

1
A pointer variables can be created not only for native types
like(int ,float,double,etc),but they can also be created for user
defined types like structure.
 We can define a pointer to a structure in the same way as any
pointer to any type.
 Example: struct employee *ptr;
 Suppose we have a pointer to structure as struct Person *pptr;
 Here pptr is a pointer to Person.
 Now p1 is a variable of type person and pptr=&p1 and pptr is
pointing to p1.
 How can we access the data with pptr?we cannot say
*[Link] precedence of dot operator(.) is higher than *
[Link] dot operator is evaluated first and then * operator.
 The complier will give error on the above statements.
Cont… 6

2
To get the results,we have to evaluate * operator first i.e
(*pptr).name will give the desired result.
 There is another easy and short way to access the structures’s
data member i.e using arrow(->) in place of dot operator.
 We normally use the arrow (->) i.e minus sign and then greater
than sign) to manipulate the structure’s data with pointers.
 So to access the name with pptr we wil write:
 pptr->name; or (*pptr).name;
 Not:Remember the difference between the access mechanism of
structure while using the simple variable and pointer.
 While accessing through a simple variable ,use dot operator i.e
[Link] ,while accessing through the pointer to structure ,use
arrow operator i.e pptr->name;
 A pointer to a structure can be used by the ‘&’ operator.
Cont… 6
 Example: 3
 struct Student{
 String name;
 };
 Student s1;
 Student *sptr=&s1;
 (*sptr).name=“Borif”; or *sptr->name=“Borif”;
Cont… 6
4
 Pointer Operators(Summary)

* Dereference This is used to declare variable as pointer.


operator ,indirectio It also used when you want to access the
n operator value pointed by the pointer variable.

& Reference operator Use before a variable to indicate that you


,address-of mean the address of that variable. You’ll
operator often see this in a function header where
the parameter list is given

-> Member selection This is used to refer to members of


operator structures
Passing Structure to 6

Function 5
[Link] an be passed to function as a parameter
 2. Function can also structure as return type.
 So far, all structures used in the preceding examples
have been global and hence were available to all the
functions within the program. But,if you have a
structure local to a function and you need to pass its
values to another functions, then it can be achieved
in two ways:
 By passing individual structure elements
 By passing the entire structure
 Both these ways can be achieved by call by value as
well as call by reference method of passing variables.
Cont… 6
6
 Passing structure elements to function
 When an element of a structure is passed to a function, you are
actually passing the values of that element to the function.
Therefore,it is just like passing a simple variable( unless, of
curse ,that element is complex such as an array of character).
 Example; Consider the following structure
 struct date{
 Short day;
 Short month;
 Short year;
 } Bdate;
 func1( [Link], Bdate. month, [Link]);The above function –
call invokes a function ,func1() by passing values of individual
structure elements of structure Bdate.
Cont… 6
7
 The function can either receive the values by creating
its own copy for them( call by value ) or by creating
references for the original variables ( call by
reference).
 if you want that the values of the structure elements
should not be altered by the function ,then you should
pass the structure elements by value and if you want
to the function to alter the original values, then you
should pass the structure elements by references.
 But: Remember if one of the structure elements
happens to be an array ,it will automatically be
passed by reference as the arrays cannot be passed
by value.
Passing Entire Structure to 6
Function 8
 Passing entire structures makes the most sense when
the structure is relatively compact. The entire structure
can be passed to the functions both ways by value and
by reference. Passing by value is useful when the
original values are not to be changed and passing by
reference is useful when original values are to be
changed.
 C++ pass structure to function call by value
 When the structure is used as an argument to a
function,the entire structure is passed using the
standard call-by-value [Link] coures ,this means
that any changes made to the contents of the structure
inside function to which it is passed do not affect the
structure used as an argument.
Cont… 6
9
 The receiving parameter for the passed structure
must match the type of the passed structure.
 Example:
 struct Employee{
 int id ;
 char Name[25];
 int age;
 long salary;
 };
 void Display( struct Employee);
Cont… 7
0
 int main()
 {
 Employee e={1,”Borif”,25.6000};
 Display(e);//structure is pass by value
 }
 void Display( Employee E)
 {
 cout<<“\n Employee ID:”<<[Link];
 cout<<“\n Employee Name:”<<[Link];
 cout<<“\n Employee Age:”<<[Link];
 cout<<“\n Employee ID:”<<[Link];
Passing Structure Object
By Reference 7

1
Structures can be passed by reference just as other simple types.
When a structure is passed by reference the called function declares
a reference for the passed structure and refers to the original
structure elements through its reference. Thus, the called function
works with the original values.
 In this approach ,the reference/address structure object is passed as
function argument to the definition of function.
 Example:
 struct Employee{
 int id;
 char name[25];
 int age;
 long salary;
 };
 void Display(struct Employee*);
Cont… 7
2
 int main(){
Emloyee e1={2,”Bona”,20,7000};
 Display(&e1)//structure is pass by reference/Address
 }
 void display( Employee *E)
 {
 cout<<“\n Employee ID:”<<E->id;
 cout<<“\n Employee Name:”<<E->name;
 cout<<“\n Employee Age:”<<E->age;
 cout<<“\n Employee Salary:”<<E->salary;
 }
Returning Structure
From Function 7

3
Just like other types,functions can return structures [Link] the
return type of the function is the same as that of the type of the
structure returned.
 For example,if the function displayData() has to return a structure
of type person ,its declaration will change a shown below:
 Person displayData(Person p);
 Example:
 struct Employee{
 int id;
 char Name[25];
 int age;
 long salary;
 };
Cont… 7

4
Emloyee Input();// statement1
 int main(){
 Employee Emp;
 Emp=Input();
 cout<<“\n Employee ID’’<<[Link];
 cout<<“\n Employee Name’’<<[Link];
 cout<<“\n Employee Age’’<<[Link];
 cout<<“\n Employee Salary’’<<[Link];
 }
Cont… 7

5
Employee Input(){
 Employee E;
 cout<<“\n Enter Employee ID:”;
 cin>>[Link];
 cout<<“\n Enter Employee Name:”;
 cin>>[Link];
 cout<<“\n Enter Employee Age:”;
 cin>>[Link];
 cout<<“\n Enter Employee Salary :”;
 cin>>[Link];
 Return E;//statement 2
 }
Array of Structure 7

6
Structure is collection of different datatype. An object of
structure represents a single record of structure type, we
have to create an array of structure or object.
 As we know, an array is a collection of similar type, therefore
an array can be of structure type.
 Syntax for declaring structure array
 struct structure_name{
 datatype var1; Student s[name];
s[0].name;
 datatype var2; s[1].name;
 ------------ s[2].name;
--------
 Datatype varN; s[99].name;
 };
 structure-name obj[size];
Cont… 7

7
Example:
 Struct student{
for(int i=0;i<size;i++{
 string id; cout<<“Enter data for
 string name; student”<<i+1<<endl;
cout<<“________________”<<endl;
 float gpa; cout<<Enter ID\t\t”;
 cin>>std[i].id;
string disciple; cout<<Enter Name\t\t”;
 };//end of structure cin>>std[i].name;
cout<<Enter GPA\t\t”;
 int main(){ cin>>std[i].gpa;
 const int size=2; cout<<Enter disciple\t\t”;
cin>>std[i].discipline;
 student std[size]; }
Cont… 7

8
For(int i=0;i<size;i++){
 cout<<“\n”;
 cout<<“Student”<<i+1<<endl;
 cout<<“_________”<<endl;
 cout<<“ID:\t\t\t”<<std[i].id<<endl;
 cout<<“Name:\t\t\t”<<std[i].name<<endl;
 cout<<“GPA:\t\t\t”<<std[i].gpa<<endl;
 cout<<“Disciple:\t\t\t”<<std[i].disciple<<endl;
 }
 return 0;
 }
Structs in Arrays 7

9
Suppose a company has 50 full-time employees. We need to print their monthly
paychecks and keep track of how much money has been paid to each employee in the
year-to-date. First, let’s define an employee’s record:
 struct employeeType
 { string firstName;
 string lastName;
 int personID;
 string deptID;
 double yearlySalary;
 double monthlySalary;
 double yearToDatePaid;
 double monthlyBonus;
 };
 Each employee has the following members (components): first name, last name,
personal ID, department ID, yearly salary, monthly salary, year-to-date paid, and
monthly bonus.
 Because we have 50 employees and the data type of each employee is the same, we
can use an array of 50 components to process the employees’ data.
 employeeType employees[50];
Cont… 8
0
 This statement declares the array employees of 50
components of type employeeType (see the
following figure). Every element of employees is a
struct. For example, the following figure also shows
employees[2].
Cont… 8
1
 Suppose we also have the following declaration: int
counter; Further, suppose that every employee’s
initial data—first name, last name, personal ID,
department ID, and yearly salary—are provided in a
file.
 For our discussion, we assume that each employee’s
data is stored in a file, say, [Link]. The
following C++ code loads the data into the
employees’ array. We assume that, initially,
yearToDatePaid is 0 and that the monthly bonus is
determined each month based on performance.
Cont… 8

2
ifstream infile; //input stream variable
 //assume that the file [Link] has been
opened
 for (counter = 0; counter < 50; counter++) { infile >>
employees[counter].firstName >>
employees[counter].lastName >>
employees[counter].personID >> employees[counter].deptID
>> employees[counter].yearlySalary;
employees[counter].monthlySalary =
employees[counter].yearlySalary / 12;
employees[counter].yearToDatePaid = 0.0;
employees[counter].monthlyBonus = 0.0;
 }
Cont… 8

3
Suppose that for a given month, the monthly bonuses are already
stored in each employee’s record, and we need to calculate the
monthly paycheck and update the yearToDatePaid amount.
 The following loop computes and prints the employee’s paycheck
for the month:
 double payCheck; //variable to calculate the paycheck
 for (counter = 0; counter < 50; counter++)
 { cout << employees[counter].firstName << " " <<
employees[counter].lastName << " "; payCheck =
employees[counter].monthlySalary +
employees[counter].monthlyBonus;
employees[counter].yearToDatePaid =
employees[counter].yearToDatePaid + payCheck; cout <<
setprecision(2) << payCheck << endl;
 }
Arrays versus structs 8
4
Nested Structure 8

5
Structure within structure: Nested structure
 Structure written inside another structure is called
as nesting two structures. we can write structure
inside another structure as member of another
structures.
 For example: we have two structures named
Address and Employee. To make Address nested to
Employee, we have to define Address structure
before and outside Employee structure and create
an object of Address structure inside Employee
structure.
Cont… 8

6
Way 1:Declare two separate Nested
Accessing structures
Elements
 struct date Structure members are accessed using dot
 { operator

Date structure is nested within Employee
int date;
structure.
 int month; Members of the date can be accessed
 int year; using ‘employee’
 Emp1 and doj are two structure
};
names(variables).
 struct Employee Explanation of Nested structure
 { [Link] Month field:[Link]
 char name[25]; [Link] dayfield:[Link]
[Link] year field:[Link]
 float salary;
 struct date doj;
 }emp1;
Cont… 8

7
Way2:Declare embedded structure
 struct Emplyee
 {
 char name[20];
 float salary;

Accessing nested structure members:
struct date Accessing month:[Link];
 { Accessing day:[Link];
Accessing year:[Link];
 int day;
 int month;
 int year;
 }doj;
 }emp1;
Cont… 8

8
Syntax for nested structure
 struct structure1
 {
Example:
 ---------- Struct Address
 {
----------
char houseNo[25];
 }; char city[25];

};
struct structure2 Struct Employee
 { {
Char name[30];
 --------- Address add;
 --------- };

 structure1 object;
 };
Cont… 8

9
int main()
 {
int I;
 Employee E;
 cout<<\n Enter Employee Name:”;
 cin>>[Link];
 cout<<\n Enter Employee City:”;
 cin>>[Link];
 cout<<\n Enter Employee House No:”;
 cin>>[Link];
 cout<<“\n Details of Employee”;
 cout<<“\n Employee Name:”<<[Link];
 cout<<“\n Employee City:”<<[Link];
 cout<<“\n Employee House No:”<<[Link];
Cont… 9
0
 Example2:
 struct Employee{ int main()
 char ename[25]; {
cout<<“\n Employee
 int ssn; Name:”<<[Link];
 cout<<“\n Employee
float salary; SSN:”<<[Link];
 struct date cout<<“\n Employee
Salary:”<<[Link];
 { cout<<“\n Employee
 DOJ:”<<[Link]<<“/”<<emp.
int day;
[Link]<<“/”<<[Link];
 int month; }
 int year;
 }doj;
 }emp1={“Borif”,1000,1000.50,{22,6,2016}};
Structure Using 9
1
typedef


Using Typedef with structures
It allows us to introduce synonyms for data types which could have
been declared some other way.
 It is used to give new name to the structure
 New name is used for creating instances, passing values to functions,
declarations, etc.
 It provides alternative name for standard data type. It is used for self
documenting the code by allowing descriptive name for the standard
data type.
 The general format is:
 typedef existing datatype new datatype
 Example:
 typedef float real;
 Now,in a program one can use datatype real instead of float.
 Therefore, the following statement is valid: real amount;
Cont… 9
2
 Example:typedef sample program
 int main(){
 typedef int Number;
 Number num1=40,num2=20;
 Number answer;
 answer=num1+num2;
 cout<<“Answer :”<<answer;
 }
Cont…
9
3

In the second example,


typedef struct
 Different
{
way of declaring structure
Record is tag name.
'employee’ is nothing
charusing typedef
ename[30]; but New Data Type. We
int ssn; can now create the
int deptno; variables of type
}employee; ‘employee’ tag name is
optional.

typedef struct Record{


Char ename[30];
Declaring variable:
Int ssn;
Employee e1,e2;
Int deptno;
}employee;
Cont… 9
4

 Using typedef for declaring structure


 typedef struct b1{
 char bname[30];
 int ssn;
 int pages;
 }book;
 Book b1={“c++”,1000.90};
 int main(){
 cout<<“\n Name of Book”:<<[Link];
 cout<<“\n SSN of Book”:<<[Link];
 cout<<“\n Pages in Book”:<<[Link];
 }
9
5

You might also like