swap havles of an array ( C Language) Please need these requirements in the code
ID: 3691011 • Letter: S
Question
swap havles of an array ( C Language)
Please need these requirements in the code ( you could use pointers) :
1-Make sure to implement function mirror() following the below signature. You are not allowed to use array notation, i.e. the symbols '[' and ']' are banned within mirror().
2-Your main() will make use of the mirror() function, but will pass in the right index ranges, which have been determined computationally. The input array can be hard-coded.
3-If the array has an odd number of elements, we want to assume that the second (not quite) half of the array contains an odd number of elements. For example, if you were supposed to swap this array: [1,2,3,4,5], the result would be [3,4,5,1,2].
4- Make sure to thoroughly comment and properly indent your code.
Here is the function to code :
Explanation / Answer
#include<stdio.h>
// function prototype
void mirror(int arr[], int size);
int main(){
int arr[] = {1,2,3,4};
int i;
mirror(arr, 4);
for(i=0; i<4; i++)
printf("%d ",arr[i]);
printf(" ");
return 0;
}
// function defination
void mirror(int *arr, int size){
int isOdd = 0;
int j =0;
if(size%2 == 1) // if size os odd, defining a flag for that
isOdd = 1;
int mid = size/2;
if(isOdd)
j = j + 1;
int i;
for(i=0; i<mid; i++){
int temp = *(arr + i);
*(arr + i) = *(arr + mid + j);
*(arr + mid+j) = temp;
j++;
}
if(isOdd){
int temp1 = *(arr + mid);
for(i=mid-1; i>=0; i--)
*(arr + i + 1) = *(arr+i);
*(arr) = temp1;
}
}
/*
sample run:
3 4 1 2
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.