Search Program on this blog

Wednesday 26 August 2015

Write a function called codeit that takes a string txt as input and returns another string coded as output. The function reverses the alphabet: It replaces each 'a' with 'z', each 'b' with 'y', each 'c' with 'x', etc. The function must work for uppercase letters the same way, but it must not change any other characters. Note that if you call the function twice like this str = codeit(codeit(txt)) then str and txt will be identical.

function coded = codeit(txt)
%Input txt is a string
%Output coded is a string
%Example coded=codeit('azAZ')
code=double(txt);
s=length(code);
for i=1:s
    if code(i)>=65 && code(i)<=90 %for uppercase  letters
        m=code(i)-65;
        code(i)=90-m;
    elseif code(i)>=97 && code(i)<=122 %for lowercase  letters
        m=code(i)-97;
        code(i)=122-m;
    end
end
coded=char(code);

2 comments: