Program Using C. Write a program called rearrange.c. that allows rearranging of
ID: 3850456 • Letter: P
Question
Program Using C.
Write a program called rearrange.c. that allows rearranging of the array elements by slicing the array at a specified position and put the second part of the array to the beginning of the array and then append the first part.
As part of the solution, write and call the function rearrange() with the following prototype. The rearrange function should rearrange the array a1 with slicing position s so that the elements before position s are moved to the end of the elements after position s.
void rearrange(int n, int *a1, int s, int *a2);
The rearrange() function should use pointer arithmetic – not subscripting – to visit array elements. In other words, eliminate the loop index variables and all use of the [] operator in the function.
In the main function, ask the user to enter the length of the array, declare the array with the length, read in the values for the array and the slicing position and call the rearrange function. The main function should display the result.
A sample input/output:
Enter the length of the array: 6
Enter the elements of the array: 3 4 9 8 7 2
Enter the slicing position: 3
Output:
The output array is: 9 8 7 2 3 4
Explanation / Answer
Code:
#include <stdio.h>
/* function declaration */
void rearrange(int, int*, int, int*);
int main()
{
int i, n, arr1[50], s, arr2[50];
printf(" Enter length of the array: ");
scanf("%d", &n);
printf(" Enter the elements of the array: ");
for(i = 0; i < n; i++)
scanf("%d", &arr1[i]);
printf(" Enter the slicing position: ");
scanf("%d", &s);
rearrange(n, arr1, s, arr2);
return 0;
}
/* slicing and rearranging elements */
void rearrange(int n, int* a1, int s, int* a2)
{
/* declaring variables */
int i;
int *p1, *p2;
/* storing the staring address of a1 and a2 in pointers p1 and p2 */
p1 = a1;
p2 = a2;
/* moving the address of a1 to the slicing position minus 1 because array starts with 0 */
a1 = (a1 + s - 1);
/* transferring all elements from s position to n into a2 */
for(i = s; i <= n; i++){
*a2 = *a1;
a1++;
a2++;
}
/* setting the pointer location of a1 to its starting address */
a1 = p1;
for(i = 1; i <= s-1; i++){
*a2 = *a1;
a1++;
a2++;
}
/* setting the pointer location of a2 to its starting address */
a2 = p2;
printf(" The output array is: ");
for(i = 1; i<= n; i++){
printf("%d ", *a2);
a2++;
}
printf(" ");
}
Execution and output:
Unix Terminal> ./a.out
Enter length of the array: 6
Enter the elements of the array: 3 4 9 8 7 2
Enter the slicing position: 3
The output array is: 9 8 7 2 3 4
Unix Terminal> ./a.out
Enter length of the array: 10
Enter the elements of the array: 1 2 3 4 5 6 7 8 9 40
Enter the slicing position: 4
The output array is: 4 5 6 7 8 9 40 1 2 3
Unix Terminal>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.