Ques:-1) Program to swap first and last element of an integer 1-d array

				
					#include<stdio.h>
#include<conio.h>
void main()
{
 int a[10],n,temp,i;
 clrscr();
 printf("Enter the number of elements in the array:\n");
 scanf("%d",&n);
 printf("\nEnter %d elements into the array\n",n);
 for(i=1;i<=n;i++)
 scanf("%d",&a[i]);
 printf("\nElements entered into array:\n");
 for(i=1;i<=n;i++)
 printf("%d",a[i]);
 temp=a[1];
 a[1]=a[n];
 a[n]=temp;
 printf("\nElements of array after swapping:\n");
 for(i=1;i<=n;i++)
 printf("%d",a[i]);
 getch();
}

				
			

Out Put

Here's a another simple program in C to swap the first and last elements of an integer 1D array:
				
					#include <stdio.h>

void swap(int arr[], int size) {
    if (size <= 1) {
        printf("Array has less than 2 elements, cannot perform swap.\n");
        return;
    }

    int temp = arr[0];
    arr[0] = arr[size - 1];
    arr[size - 1] = temp;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    swap(arr, size);

    printf("Array after swapping first and last element: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

				
			

This program defines a function swap() that takes an integer array and its size as input arguments. It swaps the first and last elements of the array. The main() function demonstrates its usage by creating an integer array, printing it, swapping the first and last elements, and printing the array again to show the result.

Scroll to Top