0% found this document useful (0 votes)
5 views

Lecture 6

Computer components
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 6

Computer components
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

INF102D: Programming

Lecture 6
Lecture Outline
• Arrays
• Accessing array elements
• Processing Arrays
• Parallel Arrays
• Multidimensional Arrays
Introduction
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• Suppose a class has 30 students, and we need to store all their
grades. Instead of creating 30 separate variables, we can simply
create an array.
double grades[30];
• Here, the name of the array is grades. The array can hold a maximum
of 30 grades (double).
• The size and type of arrays cannot be changed after its
declaration.
Arrays
• An array simply refers to a collection of variables of the same
type and referenced by the same name.
• It is a series or list of values in computer memory, all of which have
the same name and data type but are differentiated with special
numbers called subscripts.
• For example, a shopping list may include: milk, bread, wheat,
rice, gari, flour, …
• A subscript, also called an index, is a number that indicates the
position of a particular item within an array.
How Arrays Occupy Computer Memory
• When an array is created, you declare a structure that contains
multiple data items but with the same name and same data
type
• Each item in an array is one element that occupies an
area/space in memory next to or contiguous the other.
• You indicate the number of items with the size of the array:
datatype array_name [ size ];

data Item 1 Item 2 Item 3 … Item N


index 0 1 2 … (size – 1)
Single Dimensional Arrays
• To declare a single dimensional array:
• define the variable data type
• specify the name of the array followed by square brackets
• specify the number of elements it should store
datatype array_name [ size ];
• An array’s size declarator must be a constant integer expression
with a value greater than zero.
• E.g.: float temperatures [ 100 ]; // Array of 100 floats
int units [ 10 ]; // Array of 10 integers
string stu_Name [ 200 ]; // Array of 200 strings
Memory Requirements of Arrays
• The amount of memory used by an array depends on the array’s
data type and the number of elements.
• The size of an array can be calculated by multiplying the size of an
individual element by the number of elements in the array.
• Example: int scores [ 5 ];
• Number of elements: 5
• Size of each element: 4 bytes
• Size of array: 5 * 4 = 20 bytes
Accessing Array Elements
• The individual elements of an array are assigned unique
subscripts/index.
• These subscripts are used to access a specific element within the
array.
• The first element is assigned the subscript 0, the second
element is assigned 1, and so forth.
array_name [ index ]

data Item 1 Item 2 Item 3 … Item N


index 0 1 2 … (size – 1)
Example: Accessing Array Elements
int hours [ 5 ]; // Create an array of 5 elements
hours [0] = 12; // Assign 12 to first subscript
hours[ 0 ] hours[ 1 ] hours[ 2 ] hours[ 3 ] hours[ 4 ]
data 12 ? ? ? ?
index 0 1 2 3 4

hours [ 2 ] = 20; // Assign 20 to third position


hours [ 4 ] = 45; // Assign 45 to fifth position
hours[ 0 ] hours[ 1 ] hours[ 2 ] hours[ 3 ] hours[ 4 ]
data 12 ? 20 ? 45
index 0 1 2 3 4
Inputting and Displaying Array Elements
• Array elements may be used with the cin and cout objects like
any other variable.
#include <iostream> // Display the numbers
using namespace std;
cout << x [ 0 ];
int main ( ) {
int x [ 5 ]; cout << x [ 1 ];
cout << “Enter five numbers: ”; cout << x [ 2 ];
cin >> x [ 0 ]; cout << x [ 3 ];
cin >> x [ 1 ];
cout << x [ 4 ];
cin >> x [ 2 ];
cin >> x [ 3 ]; return 0;
cin >> x [ 4 ]; }
Inputting and Displaying Array Elements
• It is also possible to initialize an array during declaration.
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main ( ) { int main ( ) {
// declare and initialize and array // declare and initialize an array
int x [ 5 ] = {19, 10, 17, 9, 15}; int x [ ] = {19, 10, 17, 9, 15};
// Display the numbers // Display the numbers
cout << x [ 0 ]; cout << x [ 0 ];
cout << x [ 1 ]; cout << x [ 1 ];
cout << x [ 2 ]; cout << x [ 2 ];
cout << x [ 3 ]; cout << x [ 3 ];
cout << x [ 4 ]; cout << x [ 4 ];
return 0; return 0;
} }
Inputting and Displaying Array Elements
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main ( ) {
int main ( ) {
int numbers [ 5 ] ;
int numbers [ 5 ] = {7, 5, 6, 12, 35};
cout << ”Enter 5 numbers: ";
cout << "The numbers are: ";
for (int i = 0; i < 5; ++i ) {
// Printing array elements cin >> numbers [ i ];
for (int i = 0; i < 5; ++i ) { }
cout << numbers [ i ] << " "; cout << "The numbers are: ";
} for (int i = 0; i < 5; ++i ) {
return 0; cout << numbers [ i ] << " ";
} }
return 0;
}
Array Out of Bounds
• If we declare an array of size 10, then the array will contain
elements from index 0 to 9.
• However, if we try to access the element at index 10 or more
than 10, it will result in Undefined Behavior.
C++ Array Size
• To get the size of an array, you can use the sizeof( ) operator:
• The sizeof( ) operator returns the size of a type in bytes.

int myNumbers [ 5 ] = {10, 20, 30, 40, 50};


sizeof ( myNumbers );

• To find out how many elements an array has, you have to divide the size
of the array by the size of the data type it contains:
int myNumbers [ 5 ] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof( myNumbers ) / sizeof( int );
cout << getArrayLength;
Partial Array Initialization
• When an array is initialized, it is possible to initialize part of the array.
• Example: int x [ 10 ] = {20, 9, 16, 12};

array x [0] x [1] x [2] x [3] x [4] x [5] x [6] x [7] x [8] x [9]
Data 20 9 16 12
Index 0 1 2 3 4 5 6 7 8 9

• When an array is initialized, it is possible to initialize part of the array.


• Example: int score [ 10 ] = {20, 9, 16, 12};
Parallel Arrays
• Sometimes it’s useful to store related data in two or more
arrays.
• It’s especially useful when the related data is of unlike types.
• Two corresponding arrays are parallel arrays if each element in
one array is associated with the element in the same relative
position in the other array
• When you use parallel arrays:
• Two or more arrays contain related data.
• A subscript relates the arrays. That is, elements at the same position
in each array are logically related.
Parallel Arrays
#include <iostream>
using namespace std;
int main () {
string name[5] = {“Yaw”, “Kwaku”, “Pete”, “Akosua”, “Afia”};
int age [5] = {12, 17, 18, 14, 15};
for(int index = 0; index < 5; index++){
cout << “My name is ” << name[index] << “ and I am ”;
cout <<age[index] << “ years old. \n”;
}
return 0;
}
Parallel Arrays
#include <iostream> for( int i = 0; i < SIZE; i++){
#include <iomanip> cout << “Hours worked by employee # ” << (i +
1) << “ : ”;
using namespace std; cin >> hours[i];
cout << “Hour rate for employee # ” << (i + 1)
int main () { << “ : ”;
cin >> payRate [i];
const int SIZE = 5;
}
int hours [SIZE] ;
cout << fixed << showpoint << setprecision(2);
double payRate [SIZE] ;
for( int i = 0; i < SIZE; i++){
cout << “Enter the hours worked by ”; double grossPay = hours[ i ] * payRate[ i ];
cout << SIZE << “ employees and their ”; cout << “Employee # ” << (i + 1) ;
cout << “ pay rates. \n”; cout << “ : GH ”<< grossPay << endl;
}
return 0;
}
Arrays as Function Arguments
• To pass an array as an argument to a function, pass the name of the array.
#include <iostream>
using namespace std; void showValues (int nums [], int size) {
for (int index = 0; index < SIZE; index++) {
void showValues (int [ ], int ); cout << nums [] << ” “ ;
cout << endl;
int main () { }
const int SIZE = 5; }
int numbers [SIZE] = {2, 5, 15, 10, 8};
showValues(numbers, SIZE);
return 0;
}
Multi-dimensional Arrays
• A multi-dimensional array is a collection of elements of the same types
stored in consecutive memory locations, all of which are referenced by
the same variable name using two subscripts.

Column 0 Column 1 Column 2 … Column N


Row 0 Scores [0] [0] Scores [0] [1] Scores [0] [2] … Scores [0] [N]
Row 1 Scores [1] [0] Scores [1] [1] Scores [1] [2] … Scores [1] [N]
… … … … … …
Row M Scores [M] [0] Scores [M] [1] Scores [M] [2] … Scores [M] [N]
Multi-dimensional Arrays
• Like a normal array, we can initialize a multidimensional array in more
than one way.
• int test[2][3] = { {2, 4, 5}, {9, 0, 19}};
• int test[2][3][4] = {
• { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
• { {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
• };
Multi-dimensional Arrays
#include <iostream>
using namespace std;

int main() {
int test[3][2] = { {2, -5}, {4, 0}, {9, 1} };
for(int row = 0; row < 3; row++ ){
for (int col = 0; col < 2; col++) {
cout << "test[" << irow << "][" << col<< "] = " << test [ row ][ col ] << endl;
}
}
return 0;
}
Multi-dimensional Arrays
#include <iostream> cout << "The numbers are: " << endl;
using namespace std; for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
int main ( ) { cout << "numbers[" << i ;
int numbers [ 2 ] [ 3 ]; cout << "][" << j << "]: " ;
cout << "Enter 6 numbers: " << endl; cout << numbers [ i ] [ j ] << endl;
}
for (int i = 0; i < 2; ++i) { }
for (int j = 0; j < 3; ++j) { return 0;
cin >> numbers [ i ][ j ]; }
}
}

You might also like