Topic 3 Arrays
Topic 3 Arrays
Arrays
Introduction to Array
• An array is a collection of data values.
• A single array can store a large number of
values during the execution of a program.
• An array stores multiple values of the
same type.
• An element in an array can be assessed
using an index.
Declaring Arrays
• Array Declaration
• Examples
i. float marks[10];
ii. const int SIZE =50;
double number[SIZE];
iii. double myList[100];
Declaring Arrays(cont.)
float marks[10]; float myList[100];
marks[0] myList[0]
marks[1] myList[1]
Element
marks[2] myList[2] value
.. Array ..
element at
.. index 2 ..
.. ..
marks[9] myList[99]
Accessing Array Elements
• The array elements are accessed through the
integer index.
double rainfall[12];
0 1 2 3 4 5 6 7 8 9 1 1
0 1
double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Array Initializers(cont.)
• Like other data types, it is possible to
declare and initialize an array at the same
time.
int number[5] = { 2, 4, 6, 8, 10};
int measure [] = {0, 0, 0, 0};
double samplingData[] = { 2.443, 8.99, 12.3,
45.009, 18.2,9.00, 3.123, 22.084, 18.08 };
char monthName[12][10] = {"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };
#include <iostream>
using namespace std;
int main()
{ string name[] = {"ali", "siti", "ken",
"lulu"};
for (int i=0;i<4;i++)
cout<<name[i]<<endl;
return 0;
}
3. Printing arrays
//print character array
#include <iostream>
using namespace std;
int main()
{ char name[4][10] = {"ali", "siti",
"ken", "lulu"};
for (int i=0;i<4;i++)
{ cout<<name[i];
cout<<endl;
}
return 0;
}
3. Printing arrays
//print character array
#include <iostream>
using namespace std;
int main()
{ char monthName[12][10] = {"January",
"February", "March","April", "May", "June", "July",
"August", "September", "October",
"November", "December" };
list = myList;
//1 1 1 1 1 1
Write C++ statements to do the following.
a. Declare an array to hold 10 double values.
b. Input the array
c. Display the sum of the first two elements.
d. Write a loop that computes and display
the sum of all elements in the array.
e. Write a loop that finds and display the
minimum element in the array.
f. Assign value 5.5 to the last element in the
array and display the entire array.
What is the output of the following code?
double findMin(double arr[],int s)
{ double min = arr[0];
for (int i = 1; i < s; i++)
if (arr[i] < min)
min = arr[i];
return min;
}
Passing Array as Parameter to Functions
• In C++ , arrays are passed by reference only.
// arrays as parameters
#include <iostream>
using namespace std;
void printarray (const int arg[], int length)
{ for (int n=0; n < length; ++n)
cout << arg[n] << “ “;
cout << endl;
}
int main ()
{ int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
}
Output:
5 10 15
2 4 6 8 10
Passing Array as Parameter to Functions
#include <iostream>
using namespace std;
int main ()
{ int numbers[5] = {1, 4, 3, 6, 8};
printArray (numbers,5); //call or invoke the function
return 0;
}
}
Output:
1 4 3 6 8
Passing Array as Parameter to Functions(cont.)
// arrays as parameters
#include <iostream>
using namespace std;
int main ()
{ // an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
double getAverage(int arr[], int size)
{ int i, sum = 0; double avg;
for (i = 0; i < size; ++i)
{ sum += arr[i];
}
avg = double(sum) / size;
return avg;
}
Output:
Average value is: 214.4
Passing Array as Parameter to Function(cont.)
Eg 1
void funcArrayAsParameter(int one[], double two[])
{…..
}
Eg 2
void initializeArray(int list[], int size)
{ int index;
for (index = 0; index< size; index++)
list[index] = 0;
}
Passing Array as Parameter to Function(cont.)
Eg 3
void inputArray(int list[], int size)
{ int index;
for (index = 0; index< size; index++)
cin>>list[index];
}
Eg 4
void printArray(const int list[], int size)
{ int index;
for (index = 0; index< size; index++)
cout<<list[index]<<“ “;
}
Passing Array as Parameter to Function(cont.)
Eg 5
int sumArray(const int list[], int size)
{ int index; int sum = 0;
for (index = 0; index< size; index++)
sum = sum +list[index];
return sum;
}
Eg 6
int findMax(int list[], int size)
{ int index; int max = list[0];
for (index = 1; index< size; index++)
if (list[index] > max)
max = list[index];
return max;
}
Passing Array Element as Parameter to Function
void printArray (int arg[], int length)
{ for (int n=0; n < length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
void passArrayElement (int e)
{ cout<<e<<endl;}
void main ()
{ int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10};
printArray (firstArray,3); Output:
printArray (secondArray,5); 5 10 15
passArrayElement(firstArray[1]); 2 4 6 8 10
passArrayElement(secondArray[4]); 10
... 8
}
Passing Array as Parameter to Function
void printArray (int arg[], int length)
{ for (int n=0; n < length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
void modifyArray2 (int arg[],int size)
{ for (int n=0; n < size; ++n)
arg[n] = 0;
}
void main ()
{ int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10}; Output:
printarray (firstArray,3); 5 10 15
printarray (secondArray,5); 2 4 6 8 10
modifyArray2 (firstArray,3); 000
modifyArray2 (secondArray,5); 000
printarray (firstArray,3);
printarray (secondArray,5);
}
Passing Array as Pointer to Function
#include<iostream>
using namespace std;
void printArray(int *list, int arraySize);//function
prototype
int main ()
{ int numbers[5] = {1, 4, 3, 6, 8};
printArray (numbers,5); //call or invoke the
function
return 0;
}
Output:
void printArray (int *list, int arraySize) 14368
{ for (int i=0; i < arraySize; i++)
cout << list[i] << " "; // output array using array
subscript notation
//cout<<*(list + i)<<” “;// output array using
pointer, both ways can be used
Relationship between Array and Pointer
• Arrays and pointers are intimately related in C++ and may be used
almost interchangeably. An array name can be thought of as a constant
pointer. Pointers can be used to do any operation involving array
subscripting.
#include <iostream>
using namespace std;
int main()
{ int b[] = { 10, 20, 30, 40 }; // create 4-element array b
int *bPtr = b; // set bPtr to point to array b
https://www.tutorialspoint.com/cplusplus-program-to-implement-parallel-array
Dynamic Variables
• C++ does not automatically initialize variable.
Pointer variables must be initialized if you do not
want them to point to anything.
int *p = 0;
int *p = NULL;
• You learned how to declare pointer
variables, how to store the address of a
variable into a pointer variable of the same
type as the variable, and how to manipulate
data using pointers.
Dynamic Variables
• The power behind pointers is that pointers can be
used to allocate and deallocate memory during
program executions.
• Variables that are created during program
execution are called dynamic variables.
• With the help of pointers, C++ creates dynamic
variables.
• C++ provides two operators:
– new to create dynamic variables
– delete to destroy dynamic variables
Operator new
• The operator new has two forms: one to allocate a
single variable and another to allocate an array of
variables. The syntax to use the operator new is:
new datatype; // to allocate a single variable
new datatype[intExp]; //to allocate an array of variables
int *ptr;
int arr[5];
ptr = &arr[0];
Array and Pointers
• A C++ array name is actually a constant pointer to
the first element in the array.
• Suppose you declare an array of int values as
follows:
int list[] = {11, 12, 13, 14, 15, 16};
• The following statement displays the starting
address of the array:
cout<<“The starting address of the array is
“<< list << endl;
• C++ allows you to access the elements in the array using
the dereference operator.
*list, *(list + 1), *(list + 2), *(list + 3), *(list
+ 4), *(list + 5),
Array and Pointers
• Array list points to the first element in the array.
type name[size1][size2]...[sizeN];
int threedim[5][10][4];
Two-Dimensional Arrays
• The simplest form of the multidimensional array is
the two-dimensional array.
• A two-dimensional array is, in essence, a list of
one-dimensional arrays.
• To declare a two-dimensional integer array of size
x,y, you would write something as follows:
type arrayName [ x ][ y ];
2
Declaring Two-Dimensional Arrays(cont.)
for (row=0;row<rowNo;row++)
{ for (int col=0;col<columnNo;col++)
cout<<matrix[row][col]<<“ “;
cout<<endl;
}
Input
•To input to all components of matrix
for (row=0;row<rowNo;row++)
for (col=0;col<columnNo;col++)
cin>>matrix[row][col];
•To input data into row number 4
row=4;
for (int col=0;col<columnNo;col++)
cin>>matrix[row][col];
Sum
•To sum all components of matrix
for (row=0;row<rowNo;row++)
{ for (col=0;col<columnNo;col++)
{ sum = sum +matrix[row][col];
}
}
Sum by Row
•To sum row number 4
row=4;
for (int col=0;col<columnNo;col++)
sum = sum +matrix[row][col];
Sum by Row
•To sum each individual row
for (row=0;row<rowNo;row++)
{ sum = 0;
for (col=0;col<columnNo;col++)
sum = sum +matrix[row][col];
cout<<“Sum of row”<< row + 1<<“=“<<sum<<endl;
}
Sum by Column
•To sum each individual column
for (col=0;col<colNo;col++)
{ sum = 0;
for (row=0;row<rowNo;row++)
sum = sum +matrix[row][col];
cout<<“Sum of column”<< col + 1<<“ = “<<sum<<endl;
}
•To sum column number 4
col=4;
for (row=0;row<rowNo;row++)
sum = sum +matrix[row][col];
Largest Element in Array
largest = matrix[0][0];
for (row=1;row<rowNo;row++)
for (col=1;col<colNo;col++)
{ if (largest < matrix[row][col])
largest = matrix[row][col];
}