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

Module 2 Arrays

Uploaded by

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

Module 2 Arrays

Uploaded by

samanthachua155
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Learning Module in Computer Programming 2

Module 2 - Arrays
Learning Content:
• Introduction to Arrays
• Declaring Arrays
• Passing Arrays to functions
• Sorting Arrays
• Searching Arrays
• Multiple-Subscripted Arrays

Learning Outcomes:
• Introduce the array data structure
• Use of arrays to store, sort and search lists and tables of values.
• Define an array, initialize an array and refer to individual elements of an array.
• Pass arrays to functions
• Explain the basic sorting techniques
• Define and manipulate multiple subscript arrays.
• Create different programs using arrays

Array is
• Is a derived data type (derived from fundamental data type)
• used to store a collection of data
• a collection of variables called elements of the same type
• consist of contiguous memory locations.
• the lowest address corresponds to the first element and the highest address to the last
element.
• Can have data items of type like: int, char, float and also user-defined types like: structures,
object.

The memory locations in the array are known as elements of array.

The total number of elements in the array is called length.

The elements of array is accessed with reference to its position in array, that is call index or subscript.

Advantages of Array:
• Arrays can store a large number of value with single name.
• Arrays are used to process many value easily and quickly.
• The values stored in an array can be sorted easily.
• The search process can be applied on arrays easily.

Need for an Array:


• to store large number of variables of same type under a single variable.
• easy understanding of the program.
o Example:
▪ To store Marks of 50 students
▪ Record of sales of 100 salesman
Declaration of an Array:

Like a regular variable, an array must be declared before it is used. A typical declaration for
an array in Visual C++ is:

type name [elements];


− type is a valid type (like int, float...)
− name is a valid identifier

Page | 1
Learning Module in Computer Programming 2

− elements field (which is always enclosed in square brackets []), specifies how many of these
elements the array has to contain. (# of elements that can be stored. It can be a
integer value without the sign)

Explanation:

INT NUM[6]

size of the
Base type array
name of
array array

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables. A specific element in an array is accessed by an index.

Initializing Arrays
You can initialize C++ array elements using any of the following examples:
• With array size but without values
For example: int myArray [5]={};
• With array size and values
For example: int myArray [5]={4,8,9,10,3};
• Without array size but with values
For example: int myArray []={4,8,9,10,3};

Just remember that the number of values between braces { } shall not be greater than the
number of elements in the array. If declared with less, the remaining elements are set to their default
values (which for fundamental types, means they are filled with zeroes).

Example:

#include <iostream>
Using namespace std;

Void main ( )
{
Int array [ 5 ];
array [ 0 ] = 10;
array [ 1 ] = 20;
array [ 2 ] = 30;
array [ 3 ] = 40;
array [ 4 ] = 20;

cout <<”Array contents:” <<endl ;


for ( int n = 0 ; n<5 ; n++
{ cout << “array [ “ <<n << “] = “ <<array [n ] <<endl ; }
}

• An array definition consists of type specifier, an identifier, and a dimension. The dimension, which
specifies the number of elements contained in an array, is enclosed in a bracket pair.

• An array must be given a dimension size greater than or equal to 1. The dimension value must
be a constant expression – that is, it must be possible to evaluate the value of the dimension at
compile time. This means that a non-const variable cannot be used to specify the dimension of
an array.

Page | 2
Learning Module in Computer Programming 2

Types of Array
• Single dimensional array
• is one in which one subscript /indices specification is needed to specify a particular
element of array

Syntax and Declaration :

Data_type array_name [size of array ];

The arraySize must be an integer constant greater than zero and type can be any
valid C++ data type.

int x[10]; // declares an integer array with 10 elements


float arr[5]; // declares an float array with 5 elements
char n[50]; // declares an character array with 50 elements

Example:
Int my_array [10];

Initializing Arrays

You can initialize C++ array elements either one by one or using a single statement
as follows −
int my_array[5] = {1000, 2, 3, 17, 50};

Note:
The number of values between braces { } can not be larger than the number of
elements that we declare for the array between square brackets [ ].

Accessing 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.

0 1 2 3 4

my_array 1000 2 3 17 50

int num= my_array[2];

Memory Representation:
num[0] num[1] num[2] num[3] num[4] num[5] num[6] num[7] num[8] num[9]

2000 2002 2004 2006 2008 2010 2012 2014 2016 2018

starting Address of location

Total memory in bytes that an array is occupied :


Page | 3
Learning Module in Computer Programming 2

Size of array = size of array * size of (base type)


Hear,
10*2=20

Example Program:

#include <iostream.h>
main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";

// Storing 5 number entered by user in an array


// Finding the sum of numbers entered
for (int i = 0; i < 5; ++i)
{
cin >> numbers[i];
sum += numbers[i];
}

cout << "Sum = " << sum << endl;

return 0;
}

• Two dimensional array


− is an array in which each element is itself an array.
− is, in essence, a list of one-dimensional arrays.
− an array can have as much dimensions as required. However, two dimensional and three
dimensional array are commonly used.

Example:

int num[4][3]

Syntax and Declaration:


type arrayName [ x ][ y ];

For example,

Page | 4
Learning Module in Computer Programming 2 Madeline M. Taggueg

int a[10][10]; // declares an integer array with 100 elements


float f[5][10]; // declares an float array with 50 elements
char n[5][50]; // declares an character array with 250 elements

Two-dimensional array can be think as a table, which will have x number of rows and
y number of columns. A 2-dimensional array a, which contains three rows and four columns
can be shown as below –

Thus, every element in array a is identified by an element name of the form a[ i ][ j ],


where a is the name of the array, and i and j are the subscripts that uniquely identify each
element in a.

Initializing Arrays
Multidimensioned arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

Accessing Array Elements


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index
and column index of the array.

int val = a[2][3];

Example Program:

Memory Representation:
Total bytes= no of rows*no of columns*size of(base type)

Memory reprsentation in 2-D array:

char A [2][3]

• Multi dimensional array


Page | 5
Learning Module in Computer Programming 2

− an array in which data are arranged in the form of arrays.


− an array with dimensions more than two
− the maximum limit of array is compiler dependent

Syntax and Declaration:


The syntax for declaring a multidimensional array is:

datatype arrayName [arraySize_1][arraySize_2]…[arraySize_n];

where: arraySize_1 is the number of elements of the first dimension array.


arraySize_2 is the number of elements of the second dimension array.
arraySize_n is the number of elements of the nth dimension array.

Data_type name [a][b][c][d][e][f]…….[n];

Array of 3 or more dimensional are not often use because of huge memory
requirement and complexity involved

For example:
int myArray [3][5];
double arrayko [3][4][5];

Initializing Arrays
You can initialize C++ array elements using any of the following examples:
• With array size but without values
For example: int myArray [5]={};
• With array size and values
For example: int myArray [5]={4,8,9,10,3};
• Without array size but with values
For example: int myArray []={4,8,9,10,3};

Just remember that the number of values between braces { } shall not be
greater than the number of elements in the array. If declared with less, the remaining
elements are set to their default values (which for fundamental types, means they
are filled with zeroes).

Accessing Arrays
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]

where: index is an integer or integer variable that starts with 0 and goes till size of array
minus 1.
Example 1: int myArray [5]={4,8,9,10,3};
int num= myArray[2];

In the given example above, the value of num will be equal to 9 as illustrated below:

0 1 2 3 4 index

myArra 4 8 9 10 3 elements
y

Example 2: int myArray [3][5]={{4,8,9,10,3}


{2,7,6,1,11}
{12,14,15,13,5}};
int num= myArray[2][3];

Page | 6
Learning Module in Computer Programming 2 Madeline M. Taggueg

In the given example above, the value of num will be equal to 13 as illustrated below:

index (row)

0 1 2 3 4 index (column)

0 4 8 9 10 3 elements

1 2 7 6 1 11

2 12 14 15 13 5

Example Programs:
(a.)
#include <iostream>
using namespace std;
int main()
{
int myA[] = {16, 2, 77, 40, 12071};
int result=0;
for (int n=0 ; n<5 ; ++n )
{
result += myA[n];
}
cout << result;
return 0;
}

(b.)
#include <iostream>
using namespace std;
int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";
for (int i = 0; i < 5; ++i)
{
cin >> numbers[i];
sum += numbers[i];
}
cout << "Sum = " << sum;
return 0;
}

(c.)
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the number of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! range is 1 to 100." << endl;
cout << "Enter the number again: ";
cin >> n;
}
Page | 7
Learning Module in Computer Programming 2

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


{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}

Arrays as Parameters
• C++ does not allow to pass an entire array as an argument to a function.
• But what can be passed instead is its address. (using Pointers)
• To accept an array as parameter for a function, the parameters can be declared as the
array type, but with empty brackets.

Example:
void procedure (int arg[ ])

In order to pass to this function an array declared as:


int myarray [40];

it would be enough to write a call like this:


procedure (myarray);

To accept an array as parameter for a function, the parameters can be declared as the
array type..

For Example: void procedure (int arg[ ])

In order to pass to this function an array declared as:


int myarray [40];
write a call like this:
procedure (myarray);

Below is a sample program that uses array as parameter for a function:

#include <iostream>
using namespace std;

void display(int g[5])


{
cout << "Displaying marks: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "Student "<< i + 1 <<": "<< g[i] << endl;
}
}

int main()
{
int grades[5] = {92, 73, 88, 75, 82};
display(grades);
return 0;
}

#include <iostream>
Page | 8
Learning Module in Computer Programming 2

using namespace std;


void display(int m[5])
{
cout << "Displaying marks: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "Student "<< i + 1 <<": "<< m[i] << endl;
}
}
int main()
{
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}

Example:
#include <iostream>
using namespace std;
void printarray (int arg[ ], int length)
{
for (int n=0; n<length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
int main ()
{
int firstarray[ ] = {5, 10, 15};
int secondarray[ ] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
}

#include <iostream>
using namespace std;
void display(int n[3][2])
{
cout << "Displaying Values: " << endl;
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 2; ++j)
{
cout << n[i][j] << " ";
}
}
}
int main()
{
int num[3][2] = { {3, 4}, {9, 5}, {7, 1} };
display(num);
return 0;
}

Note:
• Arrays have 0 as the first index not 1. For example, mark[0] is the first element.
• If the size of an array is n, to access the last element, (n-1) index is used.
• Suppose you declared an array of 10 elements. If you try to access array elements outside
of its bound, the compiler may not show any error. However, this may cause unexpected
output (undefined behavior).

Page | 9

You might also like