C Program to split the array and add the first part to the end

December 13, 2022, Learn eTutorial

What is an Array?

An array is a collection of data items with the same data type stored in sequential memory locations, which is indexed by a common variable. A one-dimensional array is a list, and a two-dimensional array is a matrix. 

For example, int arr[20] is one-dimensional, and int mat[10][10] is two-dimensional. Here we are given an array and We have to split that into two using that key value and then add the first half to the end of the second half.

How to implement the array split logic in C program?

For that, we accept the values for the array from the user. Now we accept the position that the user wants to split and save that value in a variable. Start a nested for loop;

  • In the outer loop, we have to loop until the position we need to split the array. Add the first number to the end.
  • In the inner loop, change one element with the element just after that. This means a[j] has to replace with a[j+1]. which means shifting the whole array one position to the left side.

Finally, display the result. 


STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare the integer variables i, j, n, split_index, and the array number[30].

STEP 3: Read the value of n into the variable 'n'.

STEP 4:  Read the numbers from the user and save them into number[i] using for loop.

STEP 5: Read the position where the user wants to split into the variable split_index.

STEP 6: By using a for loop with the condition i < split_index

STEP 7: number[n] = number[0]

STEP 8: By using another for loop with the condition j < n

STEP 9: number[j] = number[j+1].

STEP 10: Increment j by 1 and do step 8.

STEP 11: Increment i by1 and do step 6.

STEP 12: Display the resultant as the number[i] using for loop.

To split an array, we use the below concepts in C programming, we recommend you to learn those for better understanding

C Source Code

                                          #include <stdio.h>

void main()
  int number[30];
  int i, n, split_index, j;
  printf("Enter the value of n\n"); /* enter the value */
  scanf("%d", & n);
  printf("enter the numbers\n");
  for (i = 0; i < n; ++i)
    scanf("%d", & number[i]);
  printf("Enter the position of the element to split the array \n"); /* accept the position where user wants to split */
  scanf("%d", & split_index );
  for (i = 0; i < split_index ; ++i)
    number[n] = number[0];
    for (j = 0; j < n; ++j)
      number[j] = number[j + 1]; /* changing the position of the elements */

  printf("The resultant array is\n");
  for (i = 0; i < n; ++i)
    printf("%d\n", number[i]);

} /* End of main() */


Enter the value of n

enter the numbers

Enter the position of the element to split the array

The resultant array is