OneBite.Dev - Coding blog in a bite size

Extract A Sub-Array From An Array In C++

Code snippet for how to Extract A Sub-Array From An Array In C++ with sample and detail explanation

In C++, with a little understanding of pointers and arrays, extracting a sub-array from an array can be accomplished quite easily. This article will present a simple tutorial on how to do this using a specific code snippet in the C++ language.

Code Snippet: Extracting a Sub-Array from an Array

Here is a simple code snippet in C++ that demonstrates how to extract a sub-array from a given array.

#include<iostream>

void subArray(int arr[], int start, int end)
{
    for (int i = start; i < end; i++)
    {
        std::cout << arr[i] << " ";
    }
}

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

Code Explanation: Extracting a Sub-Array from an Array

This example involves creating a function subArray() that takes an array, a starting index, and an ending index as arguments. This function is then called inside the main() function.

Let’s break down the code step by step:

  1. First, the iostream library is included to allow for input/output operations.
#include<iostream>
  1. Then, the subArray() function is defined. This function takes three parameters, an integer array, and two integers that will represent the start and end of our sub-array:
void subArray(int arr[], int start, int end)
  1. In the subArray() function, a for loop is implemented that begins at the ‘start’ index and ends just before the ‘end’ index. Inside this loop, each element inside the sub-array is printed to the screen:
for (int i = start; i < end; i++)
{
    std::cout << arr[i] << " ";
}
  1. Then, the main() function is defined. In this function, an array of 9 elements is declared and the subArray() function is called with parameters that define which part of the array to be printed:
int main()
{
    int array[] = {1,2,3,4,5,6,7,8,9};
    subArray(array, 2, 6);
    return 0;
}

Looking at the output, we can see that the elements of the array indexed from 2 to 6 (0-based index) are printed out. This forms our sub-array extracted from the main array.

c-plus-plus