In: Computer Science
Encrypting Text with a Caesar Cipher
Write a C program caesar.c which reads characters from its input and writes the characters to its output encrypted with a Caesar cipher.
A Caesar cipher shifts each letter a certain number of positions in the alphabet.
The number of positions to shift will be given to your program as a command line argument.
Characters other than letters should not be encrypted.
Your program should stop only at the end of input.
Your program should contain at least one function other than main.
For example:
./caesar 1 This life well it's slipping right through my hands Uijt mjgf xfmm ju't tmjqqjoh sjhiu uispvhi nz iboet These days turned out nothing like I had planned Uiftf ebzt uvsofe pvu opuijoh mjlf J ibe qmboofe ./caesar 10 abcdefghijklmnopqrstuvwxyz klmnopqrstuvwxyzabcdefghij ABCDEFGHIJKLMNOPQRSTUVWXYZ KLMNOPQRSTUVWXYZABCDEFGHIJ ./caesar -42 Control well it's slipping right through my hands Myxdbyv govv sd'c cvszzsxq bsqrd drbyeqr wi rkxnc These days? Droco nkic?
Hint: handle upper and lower case letters separately
Hint: use %
Hint: use atoi to convert the first command-line argument to an int.
Hint:make sure you understand this example program which uses a atoi to convert command-line arguments to an ints.
Hint: create a function with a prototype like this:
int encrypt(int character, int shift);
which returns the character shifted by the specified amount
Manually Cracking a Caesar Cipher
Here is some (New Zealand) English text that has been encrypted with a Caesar cipher.
Z uf dp drbvlg ze jfdvsfup vcjv'j tri Nv fiuvi uzwwvivek uizebj rk kyv jrdv srij Z befn rsflk nyrk pfl uzu reu Z nreer jtivrd kyv kilky Jyv kyzebj pfl cfmv kyv svrty, pfl'iv jlty r urde czri
Use the program you have just written to discover the secret text?
Hint:: try different shifts until you see English.
ANSWER :-
GIVEN THAT :-
#include <stdio.h>
#include <string.h>
//Caesar method
void encrypt(char str[], int key)
{
int i;
char c;
key=key%26;
if (key <0)
key=key+26;
// defining new character array
char s[200];
// Iterating in String
for(i = 0; str[i] != '\0'; ++i){
c = str[i];
// Lowercase check
if(c >= 'a' && c <=
'z'){
c =
(char)((int)(str[i]+key-97)%26 +97);
}
//Upper case check
else if(c >= 'A' && c
<= 'Z'){
c =
(char)((int)(str[i]+key-65)%26 +65);
}
s[i]=c;
}
// Printing
printf("%s", s);
}
// Driver function
int main()
{
int n;
// Character array
char s[200];
scanf("%d \n",&n);
// string Input
fgets(s, sizeof(s), stdin);
// method call
encrypt(s,n);
return 0;
}
SCREEN SHOT :-
OUTPUT :-