In this tutorial, we are going to learn to write a C program to reverse the Array. Here we are not just going to print the array in reverse order, but we will reverse the original array.
You can check our program in C to print the array in reverse order.
There are multiple ways to write the reverse array program like using the secondary array or without using any secondary array. We will see both ways.
C program to reverse an Array with the help of a second array
#include <stdio.h> int main() { int size, i, startIndex,lastIndex; printf("Enter size of the array: "); scanf("%d", &size); //taking size of the elements int arr[size], reverse[size]; //Taking the input in array for(i = 0; i < size; i++) { printf("Please give value for index %d : ",i); scanf("%d",&arr[i]); } startIndex = 0; lastIndex = size - 1; while(lastIndex >= 0) { //Copying value from the original array to //new reverse array staring from last index reverse[startIndex] = arr[lastIndex]; startIndex++; lastIndex--; } printf("Array After Reversing : \n"); for(i=0; i<size; i++) { printf("%d\t", reverse[i]); } return 0; }
Output
Reverse an Array without using second array and temp variable in C
#include<stdio.h> int main() { int size, i, startIndex,lastIndex; printf("C Program to reverse an Array \n"); printf("enter the size of an array : "); scanf("%d",&size); //Taking size of array array int arr[size]; //Taking the input in array for(i = 0; i < size; i++) { printf("Please give value for index %d : ",i); scanf("%d",&arr[i]); } startIndex = 0; lastIndex = size - 1; //Here is the logic to reverse an array //Logic we are following swapping two variable //without using 3rd variable while (startIndex < lastIndex) { arr[startIndex] = arr[startIndex] + arr[lastIndex]; arr[lastIndex] = arr[startIndex]- arr[lastIndex]; arr[startIndex] = arr[startIndex]- arr[lastIndex]; startIndex++; lastIndex--; } printf("Reversed array is \n"); for (i=0; i < size; i++) printf("%d \t", arr[i]); return 0; }
Output
[wpusb]