Chapter 5 C++ arrays_1593ab017b56e50174abd2a866e6c133
Chapter 5 C++ arrays_1593ab017b56e50174abd2a866e6c133
1
Introduction
• An array is a complex data structure that can contain
multiple elements of the same type, each element is
identified by a unique identifier.
• For example, if we need to store the grades of 4 or 5
students, we can easily do so by creating 5 separate
variables. However, if we want to store the grades of 100 or
even 500 students, managing that many variables becomes
quite challenging. This is where arrays come in handy, as
they allow us to store all these values efficiently by simply
creating an array of the required size.
2
Properties of arrays in C++
• An Array is a collection of data of the same data type,
stored at a contiguous memory location.
• Indexing of an array starts from 0. It means the first
element is stored at the 0th index, the second at 1st,
and so on.
• Elements of an array can be accessed using their
indices.
• Once an array is declared its size remains constant
throughout the program.
• An array can have multiple dimensions.
• The size of the array in bytes can be determined by the
sizeof operator using which we can also find the
number of elements in the array.
3
Array declaration in C++
• In C++, we can declare an array by simply specifying
the data type first and then the name of an array
with its size.
• Syntax:
data_type array_name[Size_of_array];
• data_type: Is the type of the elements in the array.
• array_name: Is the name of the array
• Size_of_array: Is the number of arrays elements, it
must be known at the time of declaration
4
Array declaration in C++
• Example:
int Arr[5]
• Declaration of an array variable with 5 integer
elements. Each element is identified by an index
starting with index 0 for the first element. Thus,
Arr[0] is the first element of the array, Arr[1] is the
second, and so on, with Arr[4] being the 5th and
last element of the array.
5
Initialization of Array in C++
• In C++, we can initialize an array in many ways but
we will discuss some most common ways to
initialize an array. We can initialize an array at the
time of declaration or after declaration.
1. Initialize Array with Values in C++:
int arr[5] = {1, 2, 3, 4, 5};
• We have initialized the array with values. The values
enclosed in curly braces ‘{}’ are assigned to the array.
Here, 1 is stored in arr[0], 2 in arr[1], and so on. Here the
size of the array is 5.
6
Initialization of Array in C++
2. Initialize Array after Declaration (Using Loops):
for (int i = 0; i < N; i++) {
arr[i] = value;
}
• We have initialized the array using a loop after declaring
the array. This method is generally used when we want
to take input from the user or we can't to assign
elements one by one to each index of the array. We can
modify the loop conditions or change the initialization
values according to requirements.
7
Some rules
• Array elements:
• To update an element in an array, we can use the
index which we want to update enclosed within the
array subscript operator and assign the new value.
arr[1] = 5;
8
Some rules
• Indexes:
• An index can take the form of any arithmetic
expression of integer type (or character, subject to
automatic conversion rules). For example:
int n, k, j;
arr[n-3];
arr[k+j%2];
are valid notations.
9
Some rules
• The dimension of an array:
• The dimension of an array (its number of elements)
must be either a constant or a constant
expression. Thus, the following construction is
correct:
const int n = 50;
...
int arr[n];
double A[2*n - 1];
10
Traverse an Array in C++
• We can traverse over the array with the help of a
loop using indexing in C++.
• Example 1:
#include <iostream>
using namespace std;
int main()
{
int table[10]= { 2, 4, 6, 8, 10, 12, 14,
16, 18, 20 };
for (int i = 0; i < 10; i++) {
cout << table[i] << " ";
}
return 0;
}
11
Traverse an Array in C++
Example 2:
#include <iostream>
using namespace std;
int main(){
double t[4];
int i;
for(i=0; i<4; i++){
t[i] = 1.0 / (i+1);
}
for(i=0; i<4; i++){
cout<<"The value number "<<i<<" is : " << t[i]
<<endl;
}
return 0;}
12
Array Processing
• We will now study different standard algorithms
that are essential to know for working with arrays:
• calculating the average,
• finding the smallest element,
• and more.
• These operations and various types of searches are
indispensable algorithms that every programmer
must know.
13
Calculating the Average
• We assume that elements are stored in an array
containing 4 cells: we want to calculate the average
of the elements in this array.
• Algorithm used:
• We initialize a variable s to 0. We need to go
through the array and add the current element of
the array to s at each step. We will then divide s by
the number of elements in the array. Now, we need
to formalize this algorithm.
14
Calculating the Average
#include <iostream>
using namespace std;
int main(){
int table[4], i;
double s=0;
for(i=0; i<4; i++){
cout << "Enter table [ " << i << "] : ";
cin >> table[i];
s = s + table[i];
}
s = s/4;
cout << "The average is : " << s << endl;
return 0;}
15
Searching in an Array
• We want to write a program that searches for the
smallest element in an array containing 4 cells.
• Algorithm used:
• We will store our smallest element in a variable
smal. We start by initializing smal to the first
element of the array (at index zero). Then, we go
through all the other elements of the array,
comparing the current element with smal and
updating the value of smal if necessary. Now, we
need to formalize this algorithm.
16
Searching in an Array
• We want to write a program that searches for the
smallest element in an array containing 4 cells.
• Algorithm used:
• We will store our smallest element in a variable
smal. We start by initializing smal to the first
element of the array (at index zero). Then, we go
through all the other elements of the array,
comparing the current element with smal and
updating the value of smal if necessary. Now, we
need to formalize this algorithm.
17
Searching in an Array
#include <iostream>
using namespace std;
int main(){
int table[4], i, smal;
for(i=0; i<4; i++){
cout << "Enter table [ " << i << "] : ";
cin >> table[i];}
smal = table[0];
for(i=1; i<4; i++){
if(smal>table[i]){
smal=table[i];}
}
cout << "the smallest value is "<< smal <<endl;
return 0;} 18
Constants
• Imagine that in a program, we use an array with 100
elements and perform various operations on this array.
• There will be tons of places in the program (especially in
loops) where there will be values of 100 (or 99).
• If we decide to change the size of the array to 200, we
would have to make many modifications throughout the
program, particularly in the loop indices, with a significant
risk of error each time.
• A solution: constants
• We will define a constant N with a value of 100 and write
the entire program — especially all our loop indices — using
N.
• If we want to change the size of the array, we just need to
change the value of N in one place in the program.
19
Constants
• Two syntaxes for constants
• There are two syntaxes for defining constants:
• The older one is to use the #define preprocessor directive.
• The other is to define a global constant variable. The second
solution is preferred, but it’s important to know both.
• First syntax
#define NAME value
• Second syntax
const type identifier = constant_value;
20
Constants
• Example:
#include <iostream>
using namespace std;
#define N 10
int main()
{
int t[N], i;
for (i=0; i<N; i++){
t[i] = i*i;
}
for (i=0; i<N; i++){
cout<< t[i] <<endl;
}
return 0;
}
21
Multidimensional Arrays in C++
• Arrays declared with more than one dimension are
called multidimensional arrays. The most widely used
multidimensional arrays are 2D arrays and 3D arrays.
These arrays are generally represented in the form of
rows and columns.
• Multidimensional Array Declaration
Data_Type Array_Name[Size1][Size2]...[SizeN];
• Were,
• Data_Type: Type of data to be stored in the array.
• Array_Name: Name of the array.
• Size1, Size2,…, SizeN: Size of each dimension.
22
Two-Dimensional Array in C++
• In C++, a two-dimensional array is a grouping of
elements arranged in rows and columns. Each
element is accessed using two indices: one for the
row and one for the column, which makes it easy
to visualize as a table or grid.
• Syntax of 2D array
data_Type array_name[n][m];
Were,
• n: Number of rows.
• m: Number of columns.
23
Two-dimensional array traversing
• To read/write a matrix, you need to read all of its
elements. This requires using two loops to traverse
all its cells: one for the rows (dimension 1) and
another for the columns (dimension 2).
24
Two-dimensional array traversing
• Example:
#include <iostream>
using namespace std;
int main(){
int i, j;
int M[10][5];
for(i=0; i<10; i++)
for(j=0; j<5; j++)
{
cout<<« Read M["<< i <<"]["<< j <<"] :";
cin >> M[i][j];
}
return 0;}
25