array in c++ programming language - bowen university · an array to a function as a parameter. in...
TRANSCRIPT
Array in C++ Programming Language
Lecture Code: CIT 202
Bowen University, Iwo Nigeria
Learning Objectives: Students’ will learn different C++ array programming
statements, structure with sample solutions.
Targeted Students: 200 Level
Course Title: Computer Programming ||
Introduction to Array
An array is a list of elements of the same type
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
The elements, which are placed in a contiguous
memory locations referenced individually by
adding an index.
An Array identified by a pair of square brackets [ ]
Once an array is created, its length is fixed and cannot be changed.
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 Declaration
dataType arrayName[arraySize]; // arraySize can be a literal or a variable
// 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
Array Initialization
Elements of an Array
• 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.
For Instance: float mark[5];
15 25 35 45 55
mark[0] mark[1] mark[2] mark[3] mark[4]
int mark[5] = {15, 25, 35, 45, 55}
// take input from the user and insert in third elementcin >> mark[2];
// to store the value 55 in the 4th elementmark[3] = 9;
// to pass the value of the 4th element to a variable AA = mark[3] ;
// take input from the user and insert in (i+1)th elementcin >> mark[i];
// print first element of the arraycout << mark[0];
// print ith element of the arraycout >> mark[i-1];
How to access and print array elements?
15 25 35 45 55
mark[0] mark[1] mark[2] mark[3] mark[4]
C++ Multidimensional Arrays
Multidimensional arrays can be described as "arrays of 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.
A two-dimensional array is, in essence, a list of one-dimensional arrays.
sizeof(arrayName) returns the total bytes of the array
Sample C++ Arrays Function
sizeof(arrayName[0]) returns the bytes of first element
At some moment we may need to pass
an array to a function as a parameter.
In C++ it is not possible to pass a
complete block of memory by value as
a parameter to a function, but we are
allowed to pass its address. In practice
this has almost the same effect and it
is a much faster and more efficient
operation.get() :- This function is also used to access the elements of array.
at() :- This function is used to access the elements of array
size() :- It returns the number of elements in array
swap() :- The swap() swaps all elements of one array with other
empty() :- This function returns true when the array size is zero else returns false.
#include <iostream>using namespace std;
int test [] = {6, 25, 7, 40, 12, 71};int i, result=0;
int main (){
for ( i=0 ; i<5; i++ ){
result += test[i];}cout << result;return 0;
}
#include<iostream>
using namespace std;
int find_largest(int nums[], int n) {
return *max_element(nums, nums + n);
}
int main() {
int nums[] = { 5, 4, 9, 12, 8 };
int n = sizeof(nums) / sizeof(nums[0]);
cout << "Original array:";
for (int i=0; i < n; i++)
cout << nums[i] <<" ";
cout << "\nLargest element of the said array: "<<
find_largest(nums, n);
return 0;
}
Sample Examples One
What is the output of the following array examples?
#include <iostream>using namespace std;
void display(int score[5]);
int main(){
int score[5] = {77, 88, 99, 66, 55};display(score);return 0;
}
void display(int m[5]){
cout << "Displaying Students’ Score: "<< endl;
for (int i = 0; i < 5; ++i){
cout << "Student "<< i + 1 <<": "<< m[i] << endl;}
}
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;}
Displaying Students’ Score: Student 1: 77Student 2: 88Student 3: 99Student 4: 66Student 5: 55
Sample Examples Two
•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.
Tips to remember when working with arrays in C++
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 R. Rajaram.
4. Object –Oriented –Programming in C++ by Robert Lafore