Caesar Cipher code in C#

Problem source:

Julius Caesar protected his confidential information from his enemies by encrypting it. Caesar rotated every alphabet in the string by a fixed number K. This made the string unreadable by the enemy. You are given a string S and the number K. Encrypt the string and print the encrypted string.

For example:
If the string is middle-Outz and K=2, the encoded string is okffng-Qwvb. Note that only alphabets are encrypted while symbols like - are untouched.
‘m’ becomes ‘o’ when alphabets are rotated twice,
‘i’ becomes ‘k’,
‘-‘ remains the same because only alphabets are encoded,
‘z’ becomes ‘b’ when rotated twice.

Input Format

Input consists of an integer N equal to the length of the string, followed by the string S and an integer K.

S is a valid ASCII string and doesn’t contain any spaces.

Output Format

For each test case, print the encoded string.

Sample Input


Sample Output


class Caesar_Cipher_Hackerrank
static void Main(string[] args)
int T = Convert.ToInt16(Console.ReadLine());
string str = Console.ReadLine();
int K = Convert.ToInt16(Console.ReadLine());
foreach (char ch in str)
Int16 chAscii = Convert.ToInt16(ch);
if (chAscii >= 65 && chAscii <= 90)
Console.Write(Convert.ToChar(65 + ((chAscii – 65) + K) % 26));
else if (chAscii >= 97 && chAscii <= 122)
Console.Write(Convert.ToChar(97 + ((chAscii – 97) + K) % 26));


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s