Array and matrix

Array is the basic data structure for storing, right? Let's take a look,

4.1 Traversing

In traversing, we will visit every single element. Why? Well, it's up to you. For now let's print!

#include <iostream>
using namespace std;

void traverse_1(int arr[], int lower_bound, int upper_bound) {
    int temp = lower_bound;
    while (temp <= upper_bound) {
        cout << arr[temp] << " ";
        temp++;
    }
    cout << endl;
}

void traverse_2(int arr[], int lower_bound, int upper_bound) {
    for (int i = lower_bound; i <= upper_bound; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

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

4.2 Insertion into an array

As arrays are stored linearly, so what if I want to insert something in the middle? yeah! We have to shift things around!

Here, commented lines are the implemention of the same while logic in if logic. Hope you got that!

4.3 Deletion in arrays

It's just like insertion but much simpler!

In above codes, I didn't include corner case handlers or any validators, so it's up to you. Nothing to worry much here, I guess.

4.4 Bubble Sort

As an example on how to do operation on array, let's sort. We will pick bubble buddy for now.

And for searching with O(n) complexity,

Accordingly, let's divide and conquer. Get your sword ready to slice the array into half, XD.

4.7 Matrix multiplication

And how about 2D array? Let's multiply 2 matrix,

So, we passed an array normally to do something, but what if I want back that array?

Pointer (2D array)

Here's the fun thing, pointer, which will pass as reference,

In this way, we can do more than just copy. Hope it helps :).

Last updated

Was this helpful?