In: Computer Science
Write a C function to swap the first and last elements of an integer array. Call the function from main() with an int array of size 4. Print the results before and after swap (print all elements of the array in one line). The signature of the arrItemSwap() function is:
void arrItemSwap(int *, int, int); /* array ptr, indices i, j to be swapped */
Submit the .c file. No marks will be given if your pgm does not compile and run.
C code:
#include <stdio.h>
void arrItemSwap(int *arr, int i, int j){
//initializing a variable temp and storing
arr[i] in it
int temp=arr[i];
//setting arr[j] as arr[i]
arr[i]=arr[j];
//setting temp as arr[j]
arr[j]=temp;
}
int main()
{
//initializing a sample array
int arr[4]={1,2,3,4};
//printing Array before swapping
printf("Array before swapping: ");
//loop to print the elements
for(int i=0;i<4;i++)
//printing each element
printf("%d
",arr[i]);
//calling arrItemSwap function
arrItemSwap(arr,0,3);
//printing Array after swapping
printf("\nArray after swapping: ");
//loop to print the elements
for(int i=0;i<4;i++)
//printing each element
printf("%d
",arr[i]);
return 0;
}
Screenshot:
Output: