Array
UNIT 12 : Array
An array is a group or collection data of same data types. For example an int array
holds the elements of int types while a double array holds the elements of double types.
C Array – Memory representation
One-Dimensional Array is represented by a row with several columns.
https://beginnersbook.com/2014/01/c-arrays-example/
Two-Dimensional Array
https://www.geeksforgeeks.org/multidimensional-arrays-c-cpp/
An array of arrays is known as 2D array. The two dimensional (2D) array in C.
Programming is also known as matrix. A matrix can be represented as a table of rows and
columns.
99
Array
Three-Dimensional Array
https://www.geeksforgeeks.org/multidimensional-arrays-c-cpp/
Three-Dimensional array is same as that of Two-dimensional arrays. The difference is
as the number of dimension increases so the number of nested braces will also increase.
Learning Objectives
After successful completion of this lesson, you should be able to:
1. Declare and initialize an array.
2. Put values in the array.
3. Manipulate the contents of an array
Course Materials
12.1 An array is a collection of data of the same type stored at contiguous memory location.
Each data can be accessed individually by using an index. The size of the array is declared at
the beginning of the program and cannot be change during the program execution. Array must
accommodate all data to be processed, so, it is better to declare an array of bigger size if you
do not know exactly the number of data items to process.
98 78 83 88 79 93 89
0 1 2 3 4 5 6
Array indices
100
Array
An array index always starts with 0. So, if the size of the array is 7 the last index is 6 or if
size is 100 then last index is 99.
Why do we need an array?
More often than not program process the same type of data repeatedly. Let’s say, there
are 50 students in the class and you need to compute their final grade and then later on you
want to list their names with their grades alphabetically or in descending (highest to lowest)
order based on the grade. Before, we only use one variable for the name and one variable for
the grade that can only hold one value at time and then we use looping so we could enter
another set of name and grade, but when another value was entered the previous value is
erased in the memory and will be replaced by the new value entered. We can declare 50
variables for the name, 50 for the grade, but, that will be tedious. The solution for this kind of
process is to use an array. We use the same name of variable for all students just imagine that
it will be divided into how many times you want it to be.
For now, let us concentrate on one-dimensional array.
12.2 Array Declaration and Initialization
Syntax:
data_type arrayName[size];
OR data_type arrayName[] = {list of elements};
OR data_type arrayName[size] = {list of elements};
Examples:
int age[10];
0 1 2 3 4 5 6 7 8 9
int age[] = {6,72,47,13,23};
6 72 47 13 23
0 1 2 3 4
//size depends on the number of items listed during declaration
101
Array
int age [10] = {0};
0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
int age[10] = {6,72,47,13,23};
2
6 72 47 13 0 0 0 0 0
3
0 1 2 3 4 5 6 7 8 9
char initial[3] = {‘‘};
0 1 2
float price[5] = {0.0};
0. 0. 0. 0. 0.
0 0 0 0 0
0 1 2 3 4
string studName[50] = {“ “};
0 1 2 3 4 5 6 … 48 49
12.3 Assigning Value to an array
Direct:
studName[3] = “Beniah”;
Allowing user to enter values for the array:
int i, size =5;
string stud_name[5] = {" "};
int age[5] = {0};
float grade[5] = {0.0};
102
Array
for(i=0; i<size; i++)
{
cout << "\n Input student name #" << i+1 <<": ";
getline(cin, stud_name[i]);
cout << "\n Input age: ";
cin >> age[i];
cout << "\n Input student grade: ";
cin>> grade[i];
//to clear one or more characters from the input buffer
cin.ignore(1);
}
12.4 Asking the User to Enter the Size of Array
You can ask the user to enter the exact or estimated size of the array.
// get array size
int size = 0;
cout << “Please enter size of array: “;
cin >> size;
int memberAge[size] = {0};
if this won’t work with your compiler try this format:
data_type *arrayName = new data_type[size];
// get array size
int size = 0;
cout << “Please enter size of array: “;
cin >> size;
int *memberAge = new int[size];
Getting the sum and average of an array
// getting sum and average
// declare variable to get the total
int sumGrade=0.0, sumAge=0;
// variable to hold average
float aveGrade=0.0, aveAge=0;
103
Array
for (i=0; i<size; i++)
{
sumAge += age[i]; // sumAge = sumAge + age[i];
sumGrade += grade[i]; // sumGrade =sumGrade + grade[i];
}
aveAge = sumAge/size;
aveGrade = sumGrade/size;
cout << "\n\n Average age of students: " << aveAge;
cout << "\n\n Average grade of students: " << aveGrade;
12.6 Finding the highest and lowest value
// finding highest and lowest value
// assuming all grades are unique
// make the first element the lowest and the highest value
float highGrade = grade[0];
float lowGrade = grade[0];
string studHigh = stud_name[0];
string studLow = stud_name[0];
for(i=1; i<size; i++)
{
// determine if value higher than previous
if (grade[i] > highGrade)
{
highGrade = grade[i];
studHigh = stud_name[i];
}
// determine if value lower than the previous
if (grade[i] < lowGrade)
{
lowGrade = grade[i];
studLow = stud_name[i];
}
}
cout << "\n\n Student with highest grade: " << studHigh << " -
" << highGrade;
cout << "\n\n Student with lowest grade: " << studLow << " -
" << lowGrade;
104
Array
12.7 Counting – based on the criteria count how many in the array met the criteria.
// counting how many passed or failed the subject
int passed=0, failed=0;
for (i=0; i< size; i++)
{
if (grade[i] >= 75)
passed++;
else
failed++;
}
cout << "\n\n PASSED: " << passed;
cout << " \n FAILED: " << failed;
12.7 Searching an array – finding data that match the given requirement.
// print names of students who failed the subject
for (i=0; i<size; i++)
{
if (grade[i] < 75)
cout << stud_name[i] << ”-“ << grade[i] << endl;
}
Sorting – arranging data in ascending or descending order.
Note: Declare variable/s of same data type with the array to hold the data temporarily
when swapping the values. For ascending order, use > in the if statement and < for descending
order.
There are different methods of sorting data, one is Bubble Sorting, It is the simplest sorting
algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
// An optimized version of Bubble Sort
int j;
int holdAge=0;
float holdGrade=0.0;
string holdName = " ";
105
Array
bool swapped;
stud_name
Zel Ina Roi Bea
0 1 2 3
age
19 20 17 21
0 1 2 3
grade
97 90 88 80
0 1 2 3
swapped = false, true, false, true, false
for (i = 0; i < size-1; i++) // i = 0 1 2 <3
{
swapped = false; // false
for (j = 0; j < size-i-1; j++) // j = 0 1 2 3 <3 0 1 2 < 2 0 1 < 1
{
if (grade[j] < grade[j+1]) // < descending > ascending
{
// do swapping
holdName= stud_name[j]; // Roi, Ina
stud_name[j] = stud_name[j+1];
stud_name[j+1] = holdName;
holdAge= age[j]; // 17 20
age[j] = age[j+1];
age[j+1] = holdAge;
holdGrade= grade[j]; // 88 90
grade[j] = grade[j+1];
grade[j+1] = holdGrade;
swapped = true;
}
} // for j
// IF NO two elements were swapped by inner loop, then break
if (swapped == false)
break;
} //for i
106
Array
cout <<"\n\n Student List ";
cout <<"\n\n Name\t\t Age\t\t Grade\n\n" ;
for (i=0; i < size; i++)
cout << i+1 << ". " << stud_name[i] << "\t\t" << age[i] << "\t\t"
<< grade[i] << endl;
Activities
A. Write an array declaration that will store the following data:
1. 50 letter grades
2. commissions of ten salesmen
3. daily temperature in Celsius for the month of August
4. number of population of each region in the Philippines
5. names of 50 students
B. Write a program segment for the following:
1. count how many A letter grades in array # A 1
2. Get the average commission in array #A2
3. Display the day with highest and lowest temperature in array #A3
4. Display name of region with population more than 1 million
5. Display the names of students in alphabetical order
Programming
One-dim Array
1. Write a program that will ask the user to enter a name and then display the letters that
appeared more than once and the number of their occurrence.
Enter a name: Elyse Raina Villanueva
a - 4
e - 3
i - 2
l - 3
n - 2
v - 2
107
Array
2. Profiling of Customer – write a C++program that will store the profile of 15 customers in
arrays. Input the name of the customer, gender (F and M only) and the age. After
inputting the data, display the following information – how many are male, how many are
female, how many are minors (less than 18years old), senior (60 years and above) and
adults (those that were not considered as minor and senior).
Profiling of Customer
Input:
Name:_____
Gender(M or F):____
Age( in number):____
Output:
# of Male Customer:___
# of Female Customer:___
Minor s(Less than 18 years old):___
Adults(19-59 years old):____
Seniors(60 and above): _____
3. Monthly Household Expense – Create arrays (size 15) that will hold the following
information: category and amount). Allow the user to enter the category (ex. Water bill)
and the corresponding amount spent on it. After the data entry, display the household
categories and its corresponding amount in descending order (highest amount first) and
the total amount spent in a month.
Monthly Household Expense
Enter Category #1:___
Amount Spent:___
Enter Category #2:___
Amount Spent:____
:
Enter Category #15:___
Amount Spent:___
Category Amount
______ ______
______ ______
: :
108
Array
______ ______
Total: ______
4. There are 15 candidates for the position of Barangay Captain. Using an array, write a
program that will ask the user to enter the names of the candidate and the total votes
he/she received. After the data entry, display the data in descending order based on the
votes of the candidates. Compute and display also the total votes cast for this election.
Online References
https://beginnersbook.com/2014/01/c-arrays-example/
https://www.geeksforgeeks.org/arrays-in-c-cpp/
https://www.tutorialspoint.com/cplusplus/cpp_arrays.htm
109