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

Eeb 334-315 c++ Lecture 5 Arrays (3)

The document provides an overview of arrays in C++, including their definition, syntax, and types such as multidimensional and dynamic arrays. It explains how to declare, initialize, and access elements within arrays, as well as the importance of pointers in managing arrays. Additionally, it highlights common pitfalls like out-of-bounds access and includes examples of array traversal and dynamic memory management.

Uploaded by

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

Eeb 334-315 c++ Lecture 5 Arrays (3)

The document provides an overview of arrays in C++, including their definition, syntax, and types such as multidimensional and dynamic arrays. It explains how to declare, initialize, and access elements within arrays, as well as the importance of pointers in managing arrays. Additionally, it highlights common pitfalls like out-of-bounds access and includes examples of array traversal and dynamic memory management.

Uploaded by

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

EEB 334/315 COMPUTER PROGRAMMING I

By
Dr. Ebenezer Esenogho
ARRAYS

• Introduction to Arrays

• Syntax of Arrays

• Multidimensional Arrays

• Dynamic Arrays

• Pointers

• Alternatives to Arrays,
Introduction to Arrays
Before now, we have used variables to store a single value. C++
offers the flexibility to store multiple values of the same type, and
address them with a single name. The mechanism that enables this is
arrays.

An array is a collection of elements of the same type stored in


contiguous memory locations. Arrays allow you to store multiple
values under a single variable name, which you can access using an
index.

An Array is a variable that allows you to store multiple values of the


same type.
Let’s say you need to store three integer values. You can either create
three different integer variables or create an integer array that stores
three values.
Introduction to Arrays

Points to Note:

• Arrays are zero-indexed, meaning the first element is at index 0.

• Array elements must be of the same type.

• Arrays in C++ have a fixed size that you need to specify at the

time of declaration
Syntax of Arrays

• Similar to other variables, in C++, we need to define an array before


we can use it.

• Like other definitions, an array has a data type and a name. In


addition, you need to specify the size of an array.

• The size of an array is the no of values (data items) it will hold. It


immediately follows the array name and is enclosed in square
brackets “[]”.

Syntax for declaring an array is as follows:


datatype arrayname[size];

Let’s say you want to create an array that holds 3 integer values;
following is the definition:
Arrays Indexing

Each array element has an array index. You can use the array index to
reference each element individually. You can think of an array as a set of
boxes. Each box has a label and contains an article. The label on the box is
the array index and the article in the box is the array element.

A pictorial representation of the above example is as follows: For all arrays,


the array index begins from zero. So if you want to reference the 2 nd array
element its array index would be “1” and not “2”. Similarly, the array index
to reference the 3rd array element would be “2” (not 3).
arrayname[arrayindex]; for accessing array

int arr[5];

In the above example, the name of the array is “arr”, its data type is integer
and size is “5”

// Declare an array of integers with 5 elements


int arr[5];

// Declare and initialize an array of integers


int arr[5] = {1, 2, 3, 4, 5};
Pointer
// Accessing elements

int firstElement = arr[0]; // Access the first element (1)


int thirdElement = arr[2]; // Access the third element (3)
#include <iostream> // Include the iostream library to use std::cout

int main() {
// Declare an array of integers with 5 elements
int arr[5];

// Declare and initialize an array of integers


int arrInit[5] = {1, 2, 3, 4, 5};

// Accessing elements
int firstElement = arrInit[0]; // Access the first element (1)
int thirdElement = arrInit[2]; // Access the third element (3)

// Output the values to ensure they are correct


std::cout << "First element: " << firstElement << std::endl;
std::cout << "Third element: " << thirdElement << std::endl;

return 0; // End of the main function


Important Notes!
• If you do not initialize the array, the elements contain garbage values (in
C++).
• You can also partially initialize an array, and the rest will be set to 0.
• For example
int arr[5] = {1, 2}; // Array becomes {1, 2, 0, 0, 0}

• When you initialize an array in C++ with fewer elements than its
size, the remaining elements are automatically initialized to 0.
• This is a feature of C++ where any unspecified elements in the array
will default to 0.
• For the statement int arr[5] = {1, 2};, here's what happens:
• The array arr has a size of 5.
• The first element arr[0] is initialized to 1.
• The second element arr[1] is initialized to 2.
• The remaining elements (arr[2], arr[3], arr[4]) are automatically
initialized to 0.
#include <iostream> // Include iostream for console input/output

int main() {
// Declare and partially initialize an array of 5 integers
int arr[5] = {1, 2};

// Output the values of the array elements


for(int i = 0; i < 5; i++) {
std::cout << "arr[" << i << "] = " << arr[i] << std::endl;
}

return 0; // End of the main function


}
Multidimensional Arrays

Multidimensional arrays are arrays of arrays, meaning a multi-


dimensional array contains other arrays. The most common is the
two-dimensional array, often used to represent matrices or grids.

You can imagine of it as box that contains other smaller boxes in it.
A two-dimensional array is similar to a table or a grid.

It contains two arrays; the first array is used to reference the rows
and the second array the columns. Similar to a grid, you can access
the elements of an array using the row and column coordinates.

syntax for declaring a two-dimensional array is as follows:

datatype arrayname[no of rows][no of columns];

arrayName[rowIndex][columnIndex];
int newarr[2][3];

In the above statement , you have declared an array “newarr” that has
two rows and three columns. Now, let’s initialize the elements of the
array “newarr”:
Let’s say you want to print the value “4”. The element is in the row
“0”, and column “2”. The C++ statement to print the element “4” is as
follows:

int newarr[2][3]={{2,3,4},{8,9,10}}; //declare and initialise array

cout<<newarr[0][2]<<endl;

0 1 2

0
1
#include <iostream> // Include iostream for console input/output

int main() {
// Declare and initialize a 2D array with 2 rows and 3 columns
int newarr[2][3] = {{2, 3, 4}, {8, 9, 10}};

// Access and print an element from the array


std::cout << "Element at newarr[0][2]: " << newarr[0][2] << std::endl; // Access
element 4
std::cout << "Element at newarr[1][0]: " << newarr[1][0] << std::endl; // Access
element 8

// Output all the elements of the 2D array


std::cout << "The 2D array elements are: " << std::endl;
for(int i = 0; i < 2; i++) { // Loop through rows
for(int j = 0; j < 3; j++) { // Loop through columns
std::cout << newarr[i][j] << " "; // Print each element
}
std::cout << std::endl; // Move to the next line after each row
}

return 0; // End of the main function


}
#include <iostream> // Include iostream for input and output operations

int main() {
// Declare and initialize a 2D array with 2 rows and 3 columns
int newarr[2][3] = {
{2, 3, 4},
{8, 9, 10}
};

// Access and print specific elements


std::cout << "Accessing specific elements:" << std::endl;
std::cout << "newarr[0][2] = " << newarr[0][2] << std::endl; // Should print 4
std::cout << "newarr[1][0] = " << newarr[1][0] << std::endl; // Should print 8

// Print all elements in a matrix format


std::cout << "\nPrinting all elements in the array:" << std::endl;
for(int i = 0; i < 2; i++) { // Iterate through rows
for(int j = 0; j < 3; j++) { // Iterate through columns
std::cout << newarr[i][j] << " ";
}
std::cout << std::endl; // Newline after each row
}

return 0; // Indicate that the program ended successfully


}
3D Arrays
Syntax
type arrayName[depth][rows][columns];
#include <iostream> // Include iostream for console input/output

int main() {
// Declare and initialize a 3D array (2x2x2)
int cube[2][2][2] = {
{
{1, 2},
{3, 4}
},
{
{5, 6},
{7, 8}
}
};

// Access and print specific elements


std::cout << "Accessing specific elements:" << std::endl;
std::cout << "cube[0][1][1] = " << cube[0][1][1] << std::endl; // Should print 4
std::cout << "cube[1][0][0] = " << cube[1][0][0] << std::endl; // Should print 5

// Print all elements in the 3D array


std::cout << "\nPrinting all elements in the 3D array:" << std::endl;
for(int i = 0; i < 2; i++) { // Iterate through the first dimension (depth)
std::cout << "Layer " << i + 1 << ":" << std::endl;
for(int j = 0; j < 2; j++) { // Iterate through rows
for(int k = 0; k < 2; k++) { // Iterate through columns
std::cout << cube[i][j][k] << " ";
}
std::cout << std::endl; // Newline after each row
}
std::cout << std::endl; // Newline after each depth
}

return 0; // End of the main function


Dynamic Arrays
Static arrays have a fixed size, which must be known at compile-time.
However, sometimes the size of the array needs to be determined at
runtime, which is where dynamic arrays come into play. Dynamic
arrays can change size during execution, allowing for more flexible
memory management.

Creating a Dynamic Array


Dynamic arrays in C++ are created using pointers and the “new”
operator.

In C++, the name of an array acts as a pointer to its first element. This
means you can use pointers to access and manipulate array elements.
Therefore, there is a relationship between Pointers and Arrays
Syntax
int* array = new int[size];
#include <iostream> // Include iostream for console input/output

int main() {
// Dynamically create an array of 5 integers
int* numbers = new int[5];

// Initializing dynamic array


for(int i = 0; i < 5; i++) {
numbers[i] = i + 1; // Assign values 1, 2, 3, 4, 5
}

// Print the values to verify initialization


std::cout << "Values in the dynamic array: ";
for(int i = 0; i < 5; i++) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;

// Access specific elements


std::cout << "First element: " << numbers[0] << std::endl; // Should print 1
std::cout << "Third element: " << numbers[2] << std::endl; // Should print 3

// Free the dynamically allocated memory


delete[] numbers;

// Set the pointer to nullptr to avoid dangling pointer issues


numbers = nullptr;

return 0; // End of the main function


}
If you were using a dynamic array (like one created with new), or a std::vector, you
could manage elements more flexibly. For example, with std::vector, you can use the
erase method to remove an element:

#include <vector>
#include <iostream>

int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};

vec.erase(vec.begin() + 2); // Erase the third element

std::cout << "Vector after deletion: ";


for (int value : vec) {
std::cout << value << " ";
}
std::cout << std::endl;

return 0;
}
Array Boundary Issues Out-of-Bounds Access

One of the common pitfalls when working with arrays is out-of-bounds


access.
C++ does not perform bounds checking on arrays, so accessing an
index outside the defined range of an array can lead to undefined
behaviour, including memory corruption or crashes.

int arr[5] = {1, 2, 3, 4, 5};


cout << arr[5]; // Out-of-bounds access (index 5 does not exist in a 5-
element array). What will be the outcome of this memory?

Undefined behaviour, including memory corruption or crashes


Multidimensional Array Traversal

Traversal of a 2D Array: When working with multidimensional arrays,


especially 2D arrays, it's essential to understand how to traverse them
efficiently. A common approach is to use nested loops.
#include <iostream>
using namespace std;

int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Traversing and printing the matrix


for(int i = 0; i < 3; i++) { // Iterate over rows
for(int j = 0; j < 3; j++) { // Iterate over columns
cout << matrix[i][j] << " ";
}
cout << endl;
}
int element = matrix[0][0]; // First row (index 0), second column (index 1)
cout << "The element at row 1, column 2 is: " << element << endl;
return 0;
}
Pointers
In C++ programing, a variable is used to store data (value). A variable
may store an integer value, a float value, a Boolean value, a string
value or a character and so on.

When you declare a variable, memory is kept aside (allocated) for that
variable. The size of the memory kept aside, depends on the data type
of the variable. We can consider of the memory of the computer, as a
succession of memory cells, where each cell has a unique address.

Syntax

Data type *variable name


look at this example:

int x =5;

In the above example, the value “5” is stored in the memory allocated
to the variable “x”. See a diagrammatic representation
#include <iostream>
using namespace std;

int main() {
// Declare and initialize an array of integers
int numbers[4] = {10, 20, 30, 40};

// Declare a pointer and point it to the first element of the array


int* ptr = numbers;

// Print the elements of the array using the pointer


cout << "Array elements using pointer:" << endl;
for (int i = 0; i < 4; i++) {
cout << "Element " << i << ": " << *(ptr + i) << endl;
// *(ptr + i) accesses the value at the i-th position in the array
}

// Increment the pointer and print the new element it points to


ptr++; // Move the pointer to the next element
cout << "After incrementing, element points to: " << *ptr << endl;
// *ptr now points to the second element (20)

return 0;
A pointer however, is a variable that stores the memory address as its value.

A pointer stores the memory address of another variable as its value. To be


able to store the memory address of a variable, you must know how to
retrieve it. The reference operator also known as the address operator,
denoted by the “&” sign, is used to retrieve the memory address of a
variable.

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

int main() {
string food = "Pizza";

cout << food << "\n";


cout << &food << "\n";
return 0;
#include <iostream>
using namespace std;

int main() {
// Declare and initialize the array
int arr[5] = {10, 20, 30, 40, 50};

// Declare a pointer and point it to the first element of the array


int* p = arr;

// Access and print the first element using the pointer


cout << *p << endl; // Outputs 10 (first element)

// Access and print the second element using pointer arithmetic


cout << *(p + 1) << endl; // Outputs 20 (second element)

// Increment the pointer to point to the second element


p++;
cout << *p << endl; // Outputs 20

// Access the third element using pointer arithmetic


cout << *(p + 1) << endl; // Outputs 30 (third element)

// Increment the pointer again to point to the third element


p++;
cout << *p << endl; // Outputs 30

// Access the fourth and fifth elements using pointer arithmetic


cout << *(p + 1) << endl; // Outputs 40 (fourth element)
cout << *(p + 2) << endl; // Outputs 50 (fifth element)

// You can also use the pointer directly in a loop to traverse the entire array
p = arr; // Reset pointer to the beginning of the array
cout << "Traversing the array using the pointer:" << endl;
for (int i = 0; i < 5; i++) {
cout << *(p + i) << " "; // Outputs 10 20 30 40 50
}
cout << endl;

return 0;
}
Passing Arrays to Functions

When you pass an array to a function, you actually pass a pointer to the first element of the array, not
a copy of the array. This means changes to the array inside the function affect the original array.

#include <iostream>
using namespace std;

void modifyArray(int arr[], int size) {


for(int i = 0; i < size; i++) {
arr[i] *= 2; // Double each element
}
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};

modifyArray(arr, 5); // Pass the array to the function

// Print the modified array


for(int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}

return 0;
}
Alternatives to Arrays

Vectors (std::vector): Vectors are dynamic arrays provided by the C++


Standard Template Library (STL). They can grow and shrink in size
dynamically, offer bounds checking, and come with a host of utility
functions.
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> vec = {1, 2, 3, 4, 5};

// Add an element at the end


vec.push_back(6);

// Access elements
cout << "First element: " << vec[0] << endl;
cout << "Last element: " << vec.back() << endl;

// Iterate over the vector


cout << "Vector elements: ";
for(int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;

return 0;
}
1. Write a C++ program that uses the “dynamic array” to store student
scores if the number of students is determined at runtime?

2. You are tasked with managing an inventory of products. Write a C+


+ program using arrays to store product IDs and their
corresponding quantities.
Take product-ID = [101, 102, 103, 104, 105]
Quantities =[50, 30, 20, 10, 60]

3. As a teaching assistant you task to write a C++ program that assign


grades to three students in four different subjects then find the
average of each student
Take grades of three student as in four subject as [{85, 90, 78, 92}; {88, 76, 85, 80} {91, 82, 88,
89}].

4. Imagine you are tasked with storing the daily temperatures of a


week and then calculating the average temperature.
Take daily temperature as {72, 75, 78, 73, 70, 74, 77}

You might also like