In: Computer Science
How can I make sure (test) a reverse program that returns the same array with the same values as you entered before, but just in reverse order?
Example of the program im talking about:
void reverseArray(int arr[], int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
Explanation:
How the function reverseArray works :
Note: Here start and end are not elements they are indexes
Code for testing function :
#include<iostream>
using namespace std;
// function for reverxing the array
// taking argumrnts array,startindex, end index
int revArray(int arr[] , int start,int end){
int temp ;
// loop for swaping first element and last element
until
// start < end
// it results the sorted array
while (start < end){
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// after swaping increment start
value and decrement end value
end--;
start++;
}
}
int main(){
// initialising array
int arr[20],size,i;
// asking size of the array
cout << "Enter size of the array: " ;
// storing length in size
cin >> size;
// asking user to enter elements in the array
cout << "\nEnter elements of the array: ";
for(i=0 ; i<size ; i++){
cin >> arr[i];
}
// printing array
cout << "Original Array is : " ;
for (i=0 ; i<size ; i++ ){
cout << arr[i] << " "
;
}
// calling the function revArray
// by passing array and initial index 0 and the end
index
// which is equal to the size-1
revArray(arr,0,size-1);
// printing the same array but this time it prints in
reversed order
// beacuse we called the functioin revArray() so
elements are reversed and prints here
cout << "\nReversed Array is : " ;
for (i=0 ; i<size ; i++ ){
cout << arr[i] << " "
;
}
}
Attachments:
Output:
Any queries comment, please
Thank you :)