c++ - Wrapping chars in caesar cipher encode -


can please explain me how wrapping of chars between a-to-z , a-to-z happening in caesar shift code?

k %= 26;  for(int = 0; < n; i++){     int c = s[i];     if(c >= 'a' && c <= 'z'){         c += k;         if( c > 'z'){             c = 96 + (c % 122); // wrapping z a?         }     }     else if(c >= 'a' && c <= 'z'){         c += k;         if(c > 'z'){             c = 64 + (c % 90);         }     }     cout << (char)c; } 

k amount of shift , c char of string s.

is there better way same?

lets make couple changes code , easier see going on

for(int = 0; < n; i++){     int c = s[i];     if(c >= 'a' && c <= 'z'){         c += k;         if( c > 'z'){             c = 'a' + (c % 'z') - 1; // wrapping z a?         }     }     else if(c >= 'a' && c <= 'z'){         c += k;         if(c > 'z'){             c = 'a' + (c % 'z') - 1;         }     }     cout << (char)c; } 

so in c = 'a' + (c % 'z') - 1; if c larger z mod c z(122) how many characters a need go. same thing going on upper case letters. subtracting 1 here starting @ a instead of character before a original code does.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -