0

It simply takes the string as input and encode in the two steps- index 1 and 2 are swapped,index 3 and 4 ,index 5 and 6...and so on.if the string is of odd length;then the last character remain as it is.After step1, letters are encoded accordingly- a to z,z to a,b to y..and so on

#include <iostream>
using namespace std;

char* encode(char* word,int N);
void swap(char* a,char* b);
int main()
{   
    int T,N;
    cin>>T;
    char word[100];
    while(T)
    {
        cin>>N;
        //char word[N];

        for(int i=0;i<N;i++)
            cin>>word[i];

        cout<<encode(word,N)<<"\n";

        for(int i=0;i<N;i++)
            word[i]=' ';   

        T--;
    }
    return 0;
}



char* encode(char* word,int N)
{
    int length;
    N%2==0?length=N:length=N-1;
    if(N%2!=0)
        word[N-1]=char(219-word[N-1]);

    for(int i=0;i<length;i=i+2)
    { 
        swap(word[i],word[i+1]);
        word[i]=char(219-word[i]);
        word[i+1]=char(219-word[i+1]);
    }

    return word;
}

void swap(char* a,char* b)
{
    char* temp;
    temp=b;
    b=a;
    a=temp;
}
DevSolar
  • 67,862
  • 21
  • 134
  • 209
  • Regarding `swap`, remember that assigning to a parameter has no effect on the object whose value you passed to the function; there is nothing special about pointers. As an added bonus, you're never using that function. – molbdnilo Mar 02 '20 at 09:58
  • Initialise your variables - `char word[100] = {};` - so the string is properly terminated, make sure that `N` is never greater than 99, and declare `word` inside the loop so you don't need that "reset loop" (which is wrong). – molbdnilo Mar 02 '20 at 10:04

2 Answers2

1

Your swap function doesn't work and cannot work. Also your array doesn't contain trailing zero, after that attempting to output string without trail zero may end badly..

swap(word[i],word[i+1]);

probably calls something else because your function isn't compatible with that call, std::swap because you're using namespace std. You didn't need to implement your own.

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42
0

First of all, replace:

using namespace std;

with:

using std::cout;
using std::cin;

See here why. Now you can see your code does not compile, because there is no swap function taking two chars. You have to change the line:

swap(word[i],word[i+1]);

into:

swap(&word[i],&word[i+1]);

Now you pass two adresses into the swap function, but it still does not do what you want. You have to change it into following:

char temp;
temp=*b;
*b=*a;
*a=temp;

Because you want to swap values instead of where the pointers point to. Lastly, initialize your word array with {}:

char word[100]{};

As pointed by @molbdnilo in the comments so it does end printing after 100 characters.

Hawky
  • 441
  • 1
  • 3
  • 10