Understanding Arrays in C++ Programming
Understanding Arrays in C++ Programming
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’};
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]
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};
The remaining indexed variables are initialized to zero of the base type
int yourList[5];
int myList[5];
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];
list[i] = 0;
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.
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;}
char char3[20];
Your Name
strcpy(char3, yourname);
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 operations3 = s1; //ch2=ch3 not possible in character array
Concatenating operations1+s2;
Comparison operation s1<s2;
Insertion operation cout <<s3;
Extraction operatorcin>>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;
cout<<" "<<copyString<<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)
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