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

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

What is an array?

Here we are given an array and we have to split it from a specified position and move the first part of the array add to the end. 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 a[20], int m[10][10]. Here is a one-dimensional array, and m is a two-dimensional array.

How to split an array?

We have to split the array into two using that key value and then add the first half of the array to the end of the second half.

So here, we accept the values for the array from the user and add the numbers in the array. Now we get the position that the user wants to split the array 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 of the array.

Now in the inner loop, change one element with the element just after that. Means a[j] have to replace with a[j+1]. Finally, display the output as a result. 

ALGORITHM

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

STEP 2: Declare the integer variables i, n, a j, 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 of the Array where the user wants to split into the variable 'a'.

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

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

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

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 Array as the number[i] using for loop.

C Source Code

                                          #include <stdio.h>

void main()
{
  int number[30];
  int i, n, a, 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", & a);
  for (i = 0; i < a; ++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() */
                                      

OUTPUT

Enter the value of n
5

enter the numbers
30
10
40
50
60

Enter the position of the element to split the array
2

The resultant array is
40
50
60
30
10