C Program To Divide/Split An Array Into Two At Specified Position

Lets write a C program to split or divide an array into two arrays at specified position.

Example: Expected Input/Output

Enter 10 integer numbers
-5
-4
-3
-2
-1
0
1
2
3
4
Enter position to split the array in to Two
4

Elements of First Array -> arr1[4]
-5
-4
-3
-2

Elements of Second Array -> arr2[6]
-1
0
1
2
3
4

Visual Representation

Video Tutorial: C Program To Divide/Split An Array Into Two At Specified Position



YouTube Link: https://www.youtube.com/watch?v=L4xLWpUmNvw [Watch the Video In Full Screen.]

Source Code: C Program To Divide/Split An Array Into Two At Specified Position

#include<stdio.h>

#define N 10

int main()
{
    int a[N], arr1[N], arr2[N], i, pos, k1 = 0, k2 = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    printf("Enter position to split the array in to Two\n");
    scanf("%d", &pos);

    for(i = 0; i < N; i++)
    {
        if(i < pos)
            arr1[k1++] = a[i];
        else
            arr2[k2++] = a[i];
    }

    printf("\nElements of First Array -> arr1[%d]\n", k1);
    for(i = 0; i < k1; i++)
        printf("%d\n", arr1[i]);

    printf("\nElements of Second Array -> arr2[%d]\n", k2);
    for(i = 0; i < k2; i++)
        printf("%d\n", arr2[i]);

    printf("\n");

    return 0;
}

Output:
Enter 10 integer numbers
1
2
3
4
5
6
7
8
9
1
Enter position to split the array in to Two
3

Elements of First Array -> arr1[3]
1
2
3

Elements of Second Array -> arr2[7]
4
5
6
7
8
9
1

Logic To Divide/Split An Array Into Two At Specified Position

We accept N integer numbers from the user and store it inside array variable a[N]. Now we ask the user to input the position at which we need to split the array and create two separate arrays. Next, we iterate through array elements of a, using for loop(loop counter variable i is initialized to 0 and for loop executes until i < N and for each iteration of for loop i value increments by 1) and transfer all the elements of array a to array variable arr1 until i is less than user input position. Once i is greater than or equal to user input position, we transfer elements of a to array variable arr2.

Note: We’ve initialized k1 and k2 to 0, as index starts from 0. Whenever we push / insert values inside arr1 and arr2, we increment the index value of k1 and k2 respectively.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert