In: Computer Science
Write a c program
Write a function to swap two elements of an integer array. Call the
function to swap the first element, i[0] with last element i[n],
second element i[1] with the last but one element i[n-1] and so on.
Should handle arrays with even and odd number of elements.
Call the swap function with the following arrays and print results in each case before and after swapping.
i. int arr1[] = {0, 1, 2, 3, 30, 20, 10, -1};
ii. int arr2[] = {11, 12, 13, 14, 15};
Code:
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int i,j;
int arr1[]={0,1,2,3,30,20,10,-1},n=8;
int arr2[]={11,12,13,14,15},n1=5,n2=5;/*Declarig variables*/
printf("Array One before swapping: ");
for(i=0;i<8;i++)
{
printf("%d ",arr1[i]);
}/*printing first array*/
for(i=-1;i<8/2;i++)
{
swap(&arr1[i],&arr1[n]);/*Calling the swap function*/
n--;
}/*Swapping the array*/
printf("\nArray One After swapping: ");
for(i=0;i<8;i++)
{
printf("%d ",arr1[i]);
}/*Printing the array after swapping*/
printf("\nArray Two before swapping: ");
for(i=0;i<5;i++)
{
printf("%d ",arr2[i]);
}/*Array 2 before swapping*/
for(i=-1;i<(5/2);i++)
{
swap(&arr2[i],&arr2[n1]);
n1--;
}
printf("\nArray Two After swapping: ");
for(i=0;i<5;i++)
{
printf("%d ",arr2[i]);
}
}
Output:
Indentation: