Detailed Print – Computer Sir Ki Class  Solved Problem!#CPP#2697

## Problem Statement - Array to array data

Write output of the following code and explain its working.

```		#include <iostream>
#include <string.h>
using namespace std;
int a2a(char *a1,char *a2,int rev=1)
{
int i=0;
char ch;
int n=strlen(a1);
while((ch=*a1++)!='�')
{
if(rev) a2[n-i-1]=ch;
else a2[i]=ch;
i++;
}
return i;
}
int main()
{
char a="hello";
char b="";
int c=a2a(a,b);
cout<<b<<c<<endl;
c=a2a(a,b,0);
cout<<b<<c<<endl;
return 0;
} ```

## Run Output

``````olleh5
hello5
``````

## Solution

int a2a(char *a1,char *a2,int rev=1)
A function definition with character array reference of two strings and the third variable rev to mark a condition with default value as 1.
{
int i=0; char ch; //The declarations and initialisations
int n=strlen(a1); //Finding length of first array
while((ch=*a1++)!=’’)
This loop increments address of a1 (first character array) one by one and reads the value in character ch until it hits the null character. This is basically a loop traversing method using array address.
{
if(rev) a2[n-i-1]=ch;
If rev variable is set the loop will fill a2 (the second array as passed by pointer location) from the last location determined by n-i-1 and successively moved left.

else a2[i]=ch;
If variable is not set it would be simple copy operation.

i++; This moves the loop to next index of a1.
}
return i; //This will basically return the number of times a1 has been traversed, which is basically length of both a1 and a2.
}

int main() {
char a=”hello”;
char b=””;
int c=a2a(a,b);
Since a2a is called without third parameter, it will set the default value of rev as 1 to the reverse of a will be copied to b.

cout<<b<<c<<endl;
This should print olleh5   which is array b which is reversed of array a followed by returned array length.

c=a2a(a,b,0);
This will set third parameter as 0 which means normal array copy will happen from a to b.

cout<<b<<c<<endl;
This should print hello5 as b will now be just a copy of a and the figure 5 will be its length.

return 0;
}

## Notes

• This is a tricky program which can perform both string copy and string reversal quite easily.
• This program traverses the loop by moving the address pointer location rather than by array position movement as usually done. Address incrementing method is usually more efficient in practical implementations.

## Common Errors

• Student need to take additional care in putting brackets in address increment line in the while comparison condition in the loop.