Array in ++

Lecture Code: CIT 202 Bowen University, Iwo Nigeria Learning Objectives: Students’ will learn different C++ array programming statements, structure with sample solutions.

Course Title: Computer Programming ||

Targeted Students: 200 Level Introduction to Array

An array is a list of elements of the same type An Array identified by a pair of square brackets [ ]

The elements, which are placed in a contiguous Once an array is created, memory locations referenced individually by its length is fixed and cannot be changed. adding an index.

An array is declared by base type (the type of each until of data) and number of units of memory (how much data).

For instance, 5 values of type int can be stored in an array without having to declare 5 different variables, with each one having different identifier Array Declaration

dataType arrayName[arraySize]; // arraySize can be a literal or a variable

Int scores[10]; // Declare an int array called scores with 10 elements double averageScore[20]; // Declare an double array of 20 elements const int Student = 15; float temps[student]; // Use const int as array length

// Some compilers support using variables for array size, e.g., int size; cout << "Enter the length of the array: "; cin >> size; float values[size]; Array Initialization

// Declare and initialize an int array of 3 elements int numbers [5] = {11, 33, 44, 55, 66};

// Please note that If an array size is omitted, the compiler counts the elements int numbers[] = {11, 33, 44, 55, 66};

// Kindly ensure that the number of elements in the initialization shall be equal to or less than length int numbers[8] = {11, 33, 44, 55, 66}; // Remaining elements are zero. Confusing! Don't do this int numbers[2] = {11, 33, 44}; // ERROR: too many initializers

// Use {0} or {} to initialize all elements to 0 int numbers[5] = {0}; // First element to 0, the rest also to zero int numbers[5] = {}; // All element to 0 too Elements of an Array

For Instance: float mark[5];

mark[0] mark[1] mark[2] mark[3] mark[4] 15 25 35 45 55

• Arrays have 0 as the first index not 1. In this 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. In this example, mark[4] is the last element.

• Suppose the starting address of mark[0] is 1120d. Then, the next address, mark[1], will be 1124d, address of mark[2] will be 1128d and so on. It's because the size of float is 4 bytes. How to access and print array elements?

int mark[5] = {15, 25, 35, 45, 55}

// take input from the user and insert in third element cin >> mark[2];

// to store the value 55 in the 4th element mark[3] = 9; mark[0] mark[1] mark[2] mark[3] mark[4] 15 25 35 45 55 // to pass the value of the 4th element to a variable A A = mark[3] ;

// take input from the user and insert in (i+1)th element cin >> mark[i];

// print first element of the array cout << mark[0];

// print ith element of the array cout >> mark[i-1]; C++ Multidimensional Arrays

Multidimensional arrays can be described as "arrays of arrays

A two-dimensional array is, in essence, a list of one-dimensional arrays. int x[3][4];

Here, x is a two dimensional array. It can hold a maximum of 12 elements.

You can think this array as table with 3 rows and each row has 4 columns. Sample C++ Arrays Function

sizeof(arrayName) returns the total bytes of the array At some moment we may need to pass an array to a function as a parameter. sizeof(arrayName[0]) returns the bytes of first element In C++ it is not possible to pass a complete of memory by value as at() :- This function is used to access the elements of array a parameter to a function, but we are size() :- It returns the number of elements in array allowed to pass its address. In practice this has almost the same effect and it swap() :- The swap() swaps all elements of one array with other is a much faster and more efficient get() :- This function is also used to access the elements of array. operation. empty() :- This function returns true when the array size is zero else returns false. Sample Examples One #include using namespace std; What is the output of the following array examples? int find_largest(int nums[], int n) { return *max_element(nums, nums + n); #include using namespace std; } int main() { int test [] = {6, 25, 7, 40, 12, 71}; int i, result=0; int nums[] = { 5, 4, 9, 12, 8 }; int n = sizeof(nums) / sizeof(nums[0]); int main () { cout << "Original array:"; for ( i=0 ; i<5; i++ ) for (int i=0; i < n; i++) { result += test[i]; cout << nums[i] <<" "; } cout << "\nLargest element of the said array: "<< cout << result; return 0; find_largest(nums, n); } return 0; } Sample Examples Two

#include using namespace std; double getAverage(int arr[], int size) { int i, sum = 0; void display(int score[5]); double avg;

int main() for (i = 0; i < size; ++i) { { sum += arr[i]; int score[5] = {77, 88, 99, 66, 55}; } display(score); avg = double(sum) / size; return 0; } return avg; } void display(int m[5]) { cout << "Displaying Students’ Score: "<< endl; Displaying Students’ Score: for (int i = 0; i < 5; ++i) Student 1: 77 { Student 2: 88 cout << "Student "<< i + 1 <<": "<< m[i] << endl; Student 3: 99 } Student 4: 66 } Student 5: 55 Tips to remember when working with arrays in C++

•You cannot return an array from a function. But I will discuss more about arrays and functions in the next lesson.

•You cannot output an array like you output a float or int or char or...

int score[10]; cout << score << endl;

• You cannot read into an array, i.e cin >> score;

• If you try to access array elements outside of its bound, let's say score[14], the compiler may not show any error. However, this may cause unexpected output. References

1. Object –Oriented –Programming in C++ by E Balagurusamy. .

2. OO Programming in C++ by Robert Lafore, Galgotia Publications Pvt. Ltd.

3. Object Oriented Programming and C++ By . Rajaram.

4. Object –Oriented –Programming in C++ by Robert Lafore