C++ Program to Reverse Array, String, Number
Problem:
Write a program to implement a class 'Invertdata'. Also do function overloading by defining three member functions with the same name 'invert'. The function prototypes are as followsint invert (int) - returns the inverted integer e.g. invert(2345) will return 5432.
void invert(char *) - reverse the string e.g. (say) if str="Computer Science AI" then invert(str) will make original string in str as "IA ecneicS retupmoC".
void invert(int *) - will reverse the array order e.g. An array[8,2,3,4] will be inverted to [4,3,2,8]
Algorithm or Solution:
- Start
- Declare a function to invert the number. For this declare and initialize variable rev=0. Get the last digit of original number, multiply rev by 10, add this multiplication and last digit and store it in rev.
- Continue this process till original number is greater than zero.
- Declare a function to invert the string. Use built in swap to swap first and last characters or the string. Increment counter to first character and decrement counter to last character.
- Continue this process till counter to first character is less than size of string.
- Declare a function to invert array. Declare and initialize two pointer *pointer1 with base address of array and *pointer2 with base address + array_size -1>
- Define a swap function to swap to numbers in array using pointer.
- Call swap function to swap contents pointed by *pointer1 and *pointer2.
- With each swap increment *pointer1 and decrement *pointer2.
- Continue this process till *pointer1 is less than *pointer2.
- Write a main function to illustrate the use of above invertdata class to invert data.
- End.
C++ Program:
/* Aim: Define a class invertdata with three member function named invert to perform various operations on the data. */ #include<iostream> #include<string.h> using namespace std; class Invertdata { public: int invert(int x) { int rev=0; while(x>0) { rev=rev*10+x%10; x/=10; } return rev; } void invert(char *str) { int n = strlen(str); for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } void swap1(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } // Function to reverse the array through pointers void invert(int array[], int array_size) { // pointer1 pointing at the beginning of the array int *ptr1 = array, // pointer2 pointing at end of the array *ptr2 = array + array_size - 1; while (ptr1 < ptr2) { swap1(ptr1, ptr2); ptr1++; ptr2--; } } }; int main() { Invertdata I1; char str[10]="OLAH"; int a[5]={50,40,30,20,10},*arr,i; cout<<I1.invert(2345)<<endl; I1.invert(str); cout<<str<<endl; I1.invert(a,5); for(i=0;i<5;i++) { cout<<a[i]<<" "; } cout<<endl; return 0; } /* Output of above code:- 5432 HALO 10 20 30 40 50 */