In: Computer Science
This is C++ programing
Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array.Given an array a, an int variable n containing the number of elements in a, and two other intvariables, k and temp, write a loop that reverses the elements of the array.Do not use any other variables besides a, n, k, and temp.
//Program
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int
a[100],n,k,temp;
//declaring the variables
cout<<"Enter the length of array: ";
cin>>n;
//taking the length of array from user
k=n-1;
//initialising k=n-1
cout<<"\nEnter the array elements: \n";
for(int i=0; i<n;
i++)
//loop for the input of array elements
{
cin>>a[i];
}
for (int i = 0; i < n/2;
i++)
//loop for reversing the elements via swapping
{
temp = a[i];
a[i] = a[k];
a[k] = temp;
k--;
}
cout<<"Reversed Elements are: \n";
for (int i = 0; i < n;
i++)
//loop for printing the reversed elements
{
printf("%d\n",
a[i]);
//printing the reversed elements
}
return 0;
}
//Output: