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

chapter 2 Array (1)

Uploaded by

Mintesnot Geta
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

chapter 2 Array (1)

Uploaded by

Mintesnot Geta
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Chapter Two

Arrays
2. What is An Array?
Array is a collection of identical data objects, which are stored in
consecutive memory locations under a common heading or a variable
name.
An array is a group of similar elements or data items of the same type
collected at contiguous memory locations.
Array is a linear data structure where all elements are arranged
sequentially.
It is a collection of elements of same data type stored at contiguous
memory locations.
The array is a data structure where values or items are placed in a linear
order, which means the memory assigned to each item is contiguous.
The data type of an array is the same for all the elements present in it.
Indexing in the array
We can identify and access each value with the help of an index
number in an array.
The array indexing can be of the following types:
0-based indexing
If the first value of the array gets the index 0, it is called 0-based
indexing.
For example, arr[1] will be used to access the second element of the
array in zero-based indexing.
Most of the programming languages follow 0-based indexing.
1-based indexing
If the array index starts from 1, it is called 1-based indexing. It means
the first value of the array will be assigned index 1.
// declare and initialize an array
int x[6] = {19, 10, 8, 17, 9, 15};
2.1. Properties of arrays:
An Array is a collection of data of the same data type, stored at a contiguous memory
location(Array can only hold values of one type.)
Arrays in C++ are zero-bounded; Indexing of an array starts from 0. that is the index of
the first element in the array is 0 and the last element is N-1, where N is the size of the
array.
Elements of an array can be accessed using their indices.

Once an array is declared its size remains constant throughout the program.

It is illegal to refer to an element outside of the array bounds, and your program will
crash or have unexpected results, depending on the compiler.
An array can have multiple dimensions.
2.2. Array declaration
Declaring the name and type of an array and setting the number of elements
in an array is called dimensioning the array.
The array must be declared before one uses in like other variables.
In the array declaration one must define:
1. The type of the array (i.e. integer, floating point, char, string etc.)
2. Name of the array,
3. The total number of memory locations to be allocated or the maximum
value of each subscript. i.e. the number of elements in the array.
So the general syntax for the declaration is:
Datatype Arrayname [array size];
Example1: int num [10];
Example 2: int a[5];
2.2. Array declaration
2.3. Initializing Arrays
Array initialization is the process of assigning/storing elements to an array.

The initialization can be done in a single statement or one by one.

Note that the first element in an array is stored at index 0, while the last element is
stored at index n-1, where n is the total number of elements in the array.
The total number of elements within the { } cannot exceed the value stated within the [].

 In the case of the age array, the first element will be stored at index 0, while the last
element will be stored at index 4.
int age[5] = {19, 18, 21, 20, 17};
2.3. Initializing Arrays rules
1.The initializer can even have no values, just the braces, each initialized with a
value of zero:
Example int baz[5]={};
2.3. Initializing Arrays rules
2. the elements in an array can be explicitly initialized to specific values when it
is declared, by enclosing those initial values in braces {}.
For example: int foo [5] = { 16, 2, 77, 40, 12071 };
2.3. Initializing Arrays rules
3. If declared with less, the remaining elements are set to their default values
(which for fundamental types, means they are filled with zeroes). For example:
Example int bar [5] = { 10, 20, 30 };
2.3. Initializing Arrays rules
4. When an initialization of values is provided for an array, C++ allows the possibility of
leaving the square brackets empty[]. In this case, the compiler will assume automatically a
size for the array that matches the number of values included between the braces {}:
Example int foo [] = { 16, 2, 77, 40, 12071 };
2.4. Accessing and processing array elements

 An element is accessed by indexing the array name.

This is done by placing the index of the element within square


brackets after the name of the array.

The syntax is:


Arrayname[index];
2.4. Accessing and processing array elements

 For example
 Foo[0]=1;
 foo [1] = 5;
 foo [2] =12;
 Foo[3]=8;
 foo [4] = 7;
How to insert and print array elements?
Example shows to insert and display each array elements
int mark[5] ={10, 10, 8, 17, 9};
//change the 4th element to 9
Mark[3]=9;
//take input from the user and store the value at the third position
cin>>makr[2];
//take input from the user and insert on the ith position
cin>>mark[i-1];
//print first element of the array
cout<<mark[0];
//print the ith element of the array
cout<<mark[i-1]
Types of array

1.One-dimensional Array
2.Two-dimensional Array
Types of array

1.One-dimensional Array
1.One-dimensional Array
In this type of array, it stores elements in a single dimension.
A One-Dimensional Array in C++ programming is a special type of variable that can store
multiple values of only a single data type such as int, float, double, char, structure, pointer, etc.
at a contagious location in computer memory.
 Here contagious location means at a fixed gap in computer memory.
A One-Dimensional Array is also known as 1D Array.
Suppose we want to store the age of 10 students. In that case, we have to declare 10 variables
in our C++ program to store the age of 10 students.
Declaring One-dimensional Array
Declaration Syntax of a One Dimensional Array in C++
datatype variable_name[size];
Example: int a[5];
Once we declare the 1D Array, it will look like as shown in the picture below:
Initialize One-dimensional Array

 Initialize Syntax of a One Dimensional Array in C++


 datatype variable_name[size]=value;
 Example: int a[5] = {1, 2, 3, 4, 5};
Initialize One-dimensional Array
 There are various ways to do this:
 Initialize at the time of declaration using {}.
int a[5] = {1, 2, 3, 4, 5};
 Initialize an array without specifying its size at declaration time.
int a[] = {1, 2, 3, 4, 5};
 Though we haven't specified the size, the compiler understands the size as 5 due to the
initialization of 5 elements.
 the elements initialized are less than the size of the array declared
int a[5] = {1, 2, 3};
 Here an array a of size 5 is declared. We have initialized it with 3 elements only. In this case,
the compiler assigns random values to the remaining places. this random value is 0.
 the elements initialized are empty
Int a[5]={};
 The compiler automatically assigns zero’s
One-dimensional Array example
#include <iostream>
Output
using namespace std; Enter array elements :
int main() 1
{ 3
int num [5] ; 5
cout<<"Enter array elements : \n"; 7
for(int i = 0; i < 5 ; i++) 9
{
cin >> num[i] ;
}
}
Store Numbers in a One Dimensional Array
 To store the number in each cell of the array we can use the following syntax.
 array_name[index]=value;
 Example 1: a[3]={26,15,34}
a[0]=26;

a[1]=15;

a[2]=34;
Access Numbers in a One Dimensional Array
 We can access any number stored in a 1D array using the following syntax.
 array_name[index];

 Example: cout<<a[0]<<" "<<a[1]<<" "<<a[2];


Output
………
One-dimensional Array accessing example
#include <iostream> Output
using namespace std; …………….
int main() {
int a[] = {25, 50, 75, 100};
cout << a[0] << '\n';
cout << a[1] << '\n';
cout << a[2] << '\n';
cout << a[3] << '\n';
return 0;
}
1.One-dimensional Array accessing example
#include <iostream>
using namespace std; Output
int main()
{ ……..
int age[5] = { 19, 18, 21, 20, 17 };
for (int x = 0; x < 5; x++)
{
cout <<age[x]<<"\n";
}
return 0;
}
1.One-dimensional Array example
#include <iostream>
using namespace std; Output
int foo [] = {16, 2, 77, 40, 12071};
int result=0; 12206
int main ()
{
for ( int i=0 ; i<5 ; i++ )
{
result += foo[i];
}
cout << result;
return 0;
}
1.One-dimensional Array string example
#include <iostream>
#include <string> Output
int main()
{ …………..
// Initialize String Array
std::string colour[4]
= { "Blue", "Red", "Orange", "Yellow" };
// Print Strings
for (int i = 0; i < 4; i++)
std::cout << colour[i] << "\n";
}
Types of array

2. Two-dimensional Array
2. Two-dimensional Array
It can be visualized as an array of arrays.
Two Dimensional Array (or 2D Array) A two-dimensional array in
C++ is a collection of elements organized in rows and columns.
 It can be visualized as a table or a grid, where each element is
accessed using two indices:
one for the row and one for the column.
In 2D of array, two indexes describe each element, the first index
represents a row, and the second index represents a column.
2. Two-dimensional Array
A two-dimensional array in C++ is the simplest form of a multi-dimensional array.
A two-dimensional array is also called a matrix.
Fig bellow the 2-D Array Representation
declaring a 2D array
Matrix represents a bi-dimensional array of 4 per 2 values of type int . The way to declare
this array would be:
datatype arrayName[row size][column size];
Example int a[4][2];
where,
datatype: Type of data to be stored in the array.
arrayName: Name of the array.
size1, size2, Size of each dimension.
Initializing a 2D array
datatype arrayname[row size][column size]={};
int arr[4][2] = {
{1234, 56},
{1212, 33},
{1434, 80},
{1312, 78}
};
Arrayname[row index][column index]
For example, the way to reference the second element vertically and fourth horizontally
in an expression would be:
matrix [1][3]
Example matrix [1][3]
Accessing a 2D array
#include<iostream>
using namespace std;
int main( )
{
int arr[4][2] = {{ 10, 11 },{ 20, 21 },{ 30, 31 },{ 40, 41 }} ;
int i,j;
cout<<"Printing a 2D Array:\n";
for(i=0;i<4;i++)
{
for(j=0;j<2;j++)
{
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
return 0;
}
Size of a two dimensional Array
The size of an array is equal to the size of the data type multiplied by the total

number of elements that can be stored in an array.


We can calculate the total number of elements in an array by multiplying the

size of each dimension of a two dimensional array.


For example:1 int arr1[2][4];
The array int arr1[2][4] can store total (2*4) = 8 elements.
In C++ int data type takes 4 bytes and we have 8 elements in the array ‘arr1’ of

the int type.


Total size = 4*8 = 32 bytes.
Size of a two dimensional Array
Exercise
Calculate the size of the following two dimensional array
1. Q#1 double sum[8][4];
2. Q#2 float var[8][4];
3. Q#3 long double add[8][4];
4. Q#4 short int pop[8][4];
Size of a two dimensional Array
Size of the most basic data types in byte
Size of a two dimensional Array
#include <iostream>
using namespace std;
int main()
{
int arr1[2][4];
int arr2[4][8];
cout << "Size of array arr1: " << sizeof(arr1)<< " bytes" << endl;
cout << "Size of array arr2: " << sizeof(arr2)<< " bytes";
return 0;
}
Advantages of using arrays
Some of the advantages of using arrays include:
Accessing elements randomly: Arrays give you random access to elements, meaning that
you can access position elements more efficiently compared to data structures, which have
sequential access and only allow you to access the values it contains in a specific order.
Managing memory: Because an array sorts various variables under a single name, arrays
offer a more efficient memory management strategy.
Organizing data elements: Different array algorithms, like bubble sort, selection sort and
insertion sort, can help you organize various data elements clearly and efficiently.
Disadvantages of using arrays
Some potential disadvantages of arrays include:
Inflexible data values: Because of the fixed and static sizing of arrays,
the software requires you to create an additional array to alter the size of your
dataset rather than adding to or subtracting from the one you've created.
This can make your work more time-consuming, but you can avoid this by
reviewing your data before creating an array.
Insertion and deletion challenges: In addition to the fixed size of arrays, they
also may present challenges with inserting or deleting data values.
Because arrays store elements in consecutive memory features, deleting
values and inserting new ones can be challenging, but you can avoid this issue
by taking your time and carefully planning your data entries.
Th a n k y o u ! ! !
Qu e s t i o n ? ? ?
co m m e n t

You might also like