C++ Program to Reverse Array, String, Number


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 follows

int 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:

  1. Start
  2. 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.
  3. Continue this process till original number is greater than zero.
  4. 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.
  5. Continue this process till counter to first character is less than size of string.
  6. 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>
  7. Define a swap function to swap to numbers in array using pointer.
  8. Call swap function to swap contents pointed by *pointer1 and *pointer2.
  9. With each swap increment *pointer1 and decrement *pointer2.
  10. Continue this process till *pointer1 is less than *pointer2.
  11. Write a main function to illustrate the use of above invertdata class to invert data.
  12. End.

C++ Program:

/* Aim: Define a class invertdata with three member function named invert to perform various operations on the data. */

using namespace std;

class Invertdata
	int invert(int x)
	int rev=0;

	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); 

int main()
	Invertdata I1;
	char str[10]="OLAH";
	int a[5]={50,40,30,20,10},*arr,i;


	cout<<a[i]<<" "; 
	return 0;

/* Output of above code:-

10 20 30 40 50