In this tutorial, we will write a C program to swap first and last element of an array. For example, if the given array is [1, 2, 3, 4] then the program should return an array [4, 2, 3, 1] with first and last element swapped.
C Program to swap first and last elements of an array
#include <stdio.h>
// Function to swap the first and last elements of an array
void swapFirstAndLast(int arr[], int size) {
// Swap only if the array has more than one element
if (size > 1) {
// Store first element in a temporary variable
int temp = arr[0];
// Assign the last element to the first position
arr[0] = arr[size - 1];
// Assign the temporary variable to the last position
arr[size - 1] = temp;
}
}
int main() {
int n;
// Prompt the user to enter the size of array
printf("Enter the size of array: ");
scanf("%d", &n);
// Check if the user entered array size is valid
if (n <= 0) {
printf("Array size should be greater than 0.\n");
return 1; // Exit the program with an error code
}
int arr[n];
// Prompt the user to enter the elements of the array
printf("Enter the elements of array:\n");
for (int i = 0; i < n; i++) {
// Read each element from the user
//store the entered elements in array arr[]
scanf("%d", &arr[i]);
}
// Print the original array
printf("Original array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Call the function to swap the first and last elements
swapFirstAndLast(arr, n);
// Print the array after swapping the first and last elements
printf("Array after swapping first and last elements:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0; // Exit the program successfully
}
Output:
Enter the size of array: 5
Enter the elements of array:
11 22 33 44 55
Original array:
11 22 33 44 55
Array after swapping first and last elements:
55 22 33 44 11
Explanation of the program:
swapFirstAndLast() Function:
- In this function, we first check whether the array has more than one elements, if not then do nothing.
- If the array has more than one elements then it stores the first element in a temp variable, copy the last element at first position and then copy the temp variable to the last position. This way, it swaps the first and last element of the array.
main() Function:
- Prompts user to enter the size of array and checks whether the entered size is valid or not.
- It then prompts user to enter the elements of array and stores the user entered elements in
arr[]
usingscanf
function. - It prints the original array.
- Calls
swapFirstAndLast(
) function to do the swapping. - Finally, it prints the modified array with first and last elements swapped.
Leave a Reply