C program to split an array and add the first half after the second half of the array

Here, we are going to learn how to split an array and add the first half after the second half of the array in C programming language?
Submitted by Nidhi, on July 10, 2021

Problem Solution:

Here, we will create an integer array then split the array based on entered position and shift the first half of the array after the second half and print the updated array on the console screen.

Program:

The source code to split an array and add the first half after the second half of the array is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to split an array and add the first half
// after the second half of the array

#include <stdio.h>

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

    int i = 0;
    int j = 0;
    int p = 0;

    printf("Enter the position of the item to split the array: ");
    scanf("%d", &p);

    //Split the array and shift first half to the end of second half.
    for (int i = 0; i < p; i++) {
        int x = arr[0];
        for (j = 0; j < 9; ++j)
            arr[j] = arr[j + 1];
        arr[9] = x;
    }

    printf("Result is: ");
    for (i = 0; i <= 9; ++i)
        printf("%d ", arr[i]);

    printf("\n");

    return 0;
}

Output:

Enter the position of the item to split the array: 3
Result is: 3 4 5 6 7 8 9 0 1 2

Explanation:

Here, we created an array arr with 10 elements, and then we entered the position of the element to split the array. After that, we split the array and add the first half of the array after the second half of the array, and printed the updated array on the console screen.

C One-Dimensional Array Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.