Program to reverse an array | Program to reverse the elements of an array

Program to reverse an array | Program to reverse the elements of an array is discussed here. Given an array of integers, all the elements of the array are reversed.

For example, consider the array

Input:

arr = {1, 2, 3, 4, 5}

Output:

Reversed array : {5, 4, 3, 2, 1}

Algorithm to reverse an array

  • Input the number of elements of an array.
  • Input the array elements.
  • Traverse the array from the last.
  • Print all the elements.

Program to reverse an array is given below.

// C program to reverse an array

#include<stdio.h>
int main()
{
//fill the code;
int n;
scanf(“%d”,&n);
int arr[n];
int i;
for(i = 0; i < n; i++)
{
scanf(“%d”,&arr[i]);
}
printf(“Reversed array is:\n”);
for(i = n-1; i >= 0; i–)
{
printf(“%d\n”,arr[i]);
}
return 0;

}

#include<stdio.h>

void reverse(int n,int *a)
{
int i;
printf(“Reversed array is:\n”);
for(i=n-1;i>=0;i–)
{
printf(“%d\n”,a[i]);
}
}
int main()
{
int n,*a,i;
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
scanf(“%d”,a+i);
}
reverse(n,a);
return 0;

}

// C++ program to reverse an array

#include<iostream>
using namespace std;

int main()
{
int n;
cin >> n;
int arr[n];
int i;
for(i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << “Reversed array is:\n”;
for(i = n-1; i >= 0; i–)
{
cout << arr[i] << ” “;
}
cout << endl;
return 0;

}

// Java program to reverse an array

/* Java program to insert an element in an array */

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print(“Enter no. of elements you want in array:”);
n = s.nextInt();
int a[] = new int[n+1];
System.out.println(“Enter all the elements:”);

for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print(“Reversed array is : “);
for(int i = n-1; i >= 0; i–)
{
System.out.print(a[i] + ” “);
}

}
}

# Python program to reverse an array

n = int(input())
sum = 0
arr = []
for i in range(0,n):
temp = int(input())
arr.append(temp)
print(“Reversed array is : “, end = “”)
for i in range(n-1,-1,-1):
print(arr[i], end = ” “)

Output:

reverse an array