You are on page 1of 25

KIG2007 : Computer Programming

Introduction to Arrays

Semester 2, Session 2022/2023


Arrays
• fixed-size collections consisting of data items of the same type,
identified by a pair of square brackets [ ].
• To use an array, you need to declare the array with 3 things:
1. a name,
2. a type, and
3. a dimension (or size, or length)
• General form of an array:
type arrayName[arraySize];
Index of array
• The position number of an array is called a subscript or index. This number
specifies the number of elements from the beginning of the array.
• The first element in every array has subscript 0 (zero) and is sometimes
called the zeroth element.
• To refer to a particular element in the array, we specify the name of the
array and the position number of the particular element in the array.

Position number of the c[0] -45


element within the array
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
Name of an individual Value stored in array
array element c[5] -89
element
c[6] 0
c[7] 62
c[8] -3
Name of the array is c c[9] 1
c[10] 6453
c[11] 78
Array declaration and initialization
• To create an array, you need to known the length (or size) of the
array in advance, and allocate accordingly. Once an array is
created, its length is fixed and cannot be changed.
• Like any other variables, an array can be local or global, and it must
be declared before it is used.
• You can also initialize the array during declaration with a brace-
delimited comma-separated list of initializers.

Example: [0] [1] [2] [3] [4]

int numbers[3]; ? ? ?

int numbers[3] = {11, 33, 44}; 11 33 44

int numbers[] = {11, 33, 44}; 11 33 44

int numbers[5] = {11, 33, 44}; 11 33 44 ? ?

int numbers[5] = {0}; 0 0 0 0 0

int numbers[5] = {}; 0 0 0 0 0


Arrays and loops
• Arrays works hand-in-hand with loops. You can process all the
elements of an array via a loop.

Example: To set the array’s elements to even integers from 2 to 10,


int n[10]; //n is an array of 10 integers

for (int i = 0; i<10; i++) //set the values


n[i] = 2+2*i;
Output:
n[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

Note: When looping through an array, the array subscript should never go
below 0 and should always be less than the total number of elements in
the array (one less than the size of the array).
Array of characters
• In C, a string is a char array terminated by a NULL character '\
0‘.
• Arrays may be of any type, including chars – We can store
character strings in char arrays
• Example:
char string1[] = "Hello";
char string1[] = {'H', 'e', 'l', 'l', 'o', '\0'};
char string1[256] = "Hello";
Example: Summing the elements of an array
#include <iostream>
using namespace std;
Declare constant variable arraySize
int main() { using the const keyword
const int arraySize = 10; // specifies size of array
int a[arraySize] = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87};
int total = 0;

Declare array with initializer list


// sum contents of array a
for (int i = 0; i < arraySize; i++)
{
total += a[i];
}
Sum all array values

cout << "Total of array elements: " << total << endl;
}
Example: Display array data graphically (1/2)

• One simple way to display numeric data graphically is with a bar


chart that shows each numeric value as a bar of asterisks (*).

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
const int arraySize = 11;
int n[arraySize] = {0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1};

cout << "Grade distribution:" << endl;


for (int i = 0; i < arraySize; i++)
{
// output bar labels ("0-9:", ..., "90-99:", "100:")
if (i == 0)
cout << " 0-9: ";
Example: Display array data graphically (2/2)
else if (i == 10)
cout << " 100: ";
else
cout << i * 10 << "-" << ( i * 10 ) + 9 << ": ";

// print bar of asterisks


for (int stars = 0; stars < n[i]; stars++)
cout << '*';

cout << endl; // start a new line of output Output:


Grade distribution:
} // end outer for 0-9:
} // end main 10-19:
20-29:
For each array element, print the 30-39:
associated number of asterisks 40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *
Example: Using arrays to summarize survey
results (1/2)
• 20 students rate the quality of food
• 1-5 rating scale: 1 means awful, 5 means excellent
• Place the 20 responses in an integer array and determine the
frequency of each rating.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
// define array sizes
const int responseSize = 20; // size of array responses
const int frequencySize = 6; // size of array frequency

// place survey responses in array responses


const int responses[responseSize] = {1, 2, 5, 4, 3, 5, 2, 1, 3, 1,
4, 3, 3, 3, 2, 3, 3, 2, 2, 5};
Example: Using arrays to summarize survey
results (2/2)
// initialize frequency counters to 0
int frequency[frequencySize] = {};

// for each answer, select responses element and use that value
// as frequency subscript to determine element to increment
for (int answer = 0; answer < responseSize; answer++)
frequency[responses[answer]]++; For each response,
increment frequency
cout << "Rating" << setw(17) << "Frequency" << endl; value at the index
associated with that
// output each array element's value response
for (int rating = 1; rating < frequencySize; rating++)
cout << setw(6) << rating << setw(17) << frequency[rating]
<< endl;
Output:
} Rating Frequency
1 3
2 5
3 7
4 2
5 3
Using arrays to summarize survey results
responses[20] = {1, 2, 5, 4, 3, 5, 2, 1, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2,
2, 5};

array frequency[6]:
Scale rating = 1 rating = 2 rating = 3 rating = 4 rating = 5

Corresponding frequency frequency frequency frequency frequency frequency


array element [0] [1] [2] [3] [4] [5]

When the command frequency[responses[answer]]++ executes,


response[0] = 1 → frequency[1] = +1; frequency[1] = 0 + 1 =1;
response[1] = 2 → frequency[2] = +1; frequency[2] = 0 + 1 =1;
response[2] = 5 → frequency[5] = +1; frequency[5] = 0 + 1 =1;
response[3] = 4 → frequency[4] = +1; frequency[4] = 0 + 1 =1;
response[4] = 3 → frequency[3] = +1; frequency[3] = 0 + 1 =1;
response[5] = 5 → frequency[5] = +1; frequency[5] = 1 + 1 =2;
response[6] = 2 → frequency[2] = +1; frequency[2] = 1 + 1 =2;

Static local arrays and automatic local arrays

• A program initializes static local arrays when their declarations


are first encountered.
• A static variable:
• is allocated when the execution begins and lasts for the entire
duration of the program;
• retains its memory and contents throughout the program
execution. An static variable declared inside a function retains its
value even when the function exits.
• If a static array is not initialized explicitly, each element of that
array is initialized to zero by the compiler when the array is created.
• We can apply static to a local array declaration so that the array
is not created and initialized each time the program calls the
function and is not destroyed each time the function terminates in
the program.
Passing arrays to functions
• To pass an array argument to a function, specify array name without
brackets
• Array size is normally passed as another argument so the function
can process the specific number of elements in the array
Example:
void print(int a[], int n) {
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
int main() {
int arry[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
print(arry,10);
}
The function print(arry, n) prints the contents of an int array
– arry is the array to print, n is the size of the array
Passing arrays to functions
(Example – 1/3)
#include <iostream>
#include <iomanip>
using namespace std;

void modifyArray(int [], int); // receive array and size


void modifyElement(int); // receive array element value

int main() {
const int arraySize = 5; // size of array a
int a[arraySize] = {0, 1, 2, 3, 4}; // initialize array a

cout << "Effects of passing entire array by reference:"


<< "\nThe values of the original array are:\n";

// output original array elements


for (int i = 0; i < arraySize; i++)
cout << setw(3) << a[i];
cout << endl;
Passing arrays to functions
(Example – 2/3)
// pass array a to modifyArray by reference Pass entire array to
modifyArray(a, arraySize); function modifyArray
cout << "The values of the modified array are:\n";

// output modified array elements


for (int j = 0; j < arraySize; j++)
cout << setw(3) << a[j];

cout << "\n\nEffects of passing array element by value:"


<< "\na[3] before modifyElement: " << a[3] << endl;

modifyElement(a[3]); // pass array element a[3] by value


cout << "a[3] after modifyElement: " << a[3] << endl;
} // end main

Pass array element a[3] to


function modifyElement
Passing arrays to functions
(Example – 3/3)
// in function modifyArray, "b" points to the original array "a" in memory
void modifyArray(int b[], int sizeOfArray) {
// multiply each array element by 2
for (int k = 0; k < sizeOfArray; k++)
b[k] *= 2;
}

// in function modifyElement, "e" is a local copy of


// array element a[3] passed from main
void modifyElement(int e) {
// multiply parameter by 2
cout << "Value of element in modifyElement: " << (e *= 2) << endl;
}
const array parameters
• type qualifier const can be used to prevent modification of array values in
the caller by code in a called function.

#include <iostream>
using namespace std;

void tryToModifyArray(const int []); // function prototype

int main() {
int a[] = {10, 20, 30};

tryToModifyArray(a);
cout << a[0] << ' ' << a[1] << ' ' << a[2] << '\n';
}

// In function tryToModifyArray, "b" cannot be used


// to modify the original array "a" in main
void tryToModifyArray(const int b[]) {
Array cannot be modified; it is
b[0] /= 2; // compilation error
const within the body function
}
Case Study: Using an array to store
grades
• Previous versions of the Gradebook project process grades entered
by the user, but do not maintain the individual grade values in the
class’s data members.
• Thus, repeat calculations require the user to re-enter the grades.
• In this section, we store grades in an array.

Expected output for Gradebook project:


Welcome to the grade book
for KIG2007
Using an array to store grades (1/6)
#include <iostream>
#include <iomanip>
using namespace std;

static const int students = 10; // number of students who took the test
int grades[students] = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87};

// output the contents of the grades array


void outputGrades()
{
cout << "\nThe grades are:\n\n";

// output each student's grade


for (int student = 0; student < students; ++student)
cout << "Student " << setw(2) << student + 1 << ": " << setw(3) <<

grades[student] << endl;


}
Using an array to store grades (2/6)
// find minimum grade
int getMinimum()
{
int lowGrade = 100; // assume lowest grade is 100
// loop through grades array
for (int grade = 0; grade < students; grade++)
{
// if current grade lower than lowGrade, assign it to lowGrade
if (grades[grade] < lowGrade)
lowGrade = grades[grade]; // new lowest grade
} // end for

return lowGrade; // return lowest grade


} // end function getMinimum

int getMaximum()
{
int highGrade = 0; // assume highest grade is 0
Using an array to store grades (3/6)
// loop through grades array
for (int grade = 0; grade < students; grade++)
{
// if current grade higher than highGrade, assign it to highGrade
if (grades[grade] > highGrade)
highGrade = grades[grade]; // new highest grade
}

return highGrade; // return highest grade


}

double getAverage() // determine average grade for test


{
int total = 0; // initialize total

// sum grades in array


for (int grade = 0; grade < students; grade++)
total += grades[grade];
Using an array to store grades (4/6)
return static_cast<double>(total) / students;
} // end function getAverage

void outputBarChart() // output bar chart displaying grade distribution


{
cout << "\nGrade distribution:" << endl;

// stores frequency of grades in each range of 10 grades


const int frequencySize = 11;
int frequency[frequencySize] = {}; // initialize elements to 0

// for each grade, increment the appropriate frequency


for (int grade = 0; grade < students; grade++)
++frequency[grades[grade] / students];

// for each grade frequency, print bar in chart


for (int count = 0; count < frequencySize; count++)
{
Using an array to store grades (5/6)
// output bar labels ("0-9:", ..., "90-99:", "100:" )
if (count == 0)
cout << " 0-9: ";
else if (count == 10)
cout << " 100: ";
else
cout << count * 10 << "-" << (count * 10) + 9 << ": ";

// print bar of asterisks


for (int stars = 0; stars < frequency[count]; ++stars)
cout << '*';

cout << endl; // start a new line of output


} // end outer for
}
Using an array to store grades (6/6)
int main()
{
string courseName = "KIG2007 Computer Programming ";
cout << "Welcome to the grade book for \n" << courseName << "!" <<
endl;

outputGrades();

cout << "\nClass average is " << setprecision(2) << fixed <<
getAverage() << "\nLowest grade is " << getMinimum() << "\nHighest
grade is " << getMaximum() << endl;

outputBarChart(); // print grade distribution chart

return 0;
}

You might also like