Caesar Cipher in C
Caesar Cipher in C
com/topics/caesar-cipher-program-in-
c/
The Caesar Cipher Program in C can be applied as given below. We will check each
character one by one to see if it is a lowercase character, an uppercase character, or a digit.
We have an above-derived formula for each of them which we can use to encrypt as per the
key given by the user.
Apply the above-derived formulae for each category. If the given character is an
alphanumeric value, only we try encoding it. Else we print an error message.
#include<stdio.h>
#include<ctype.h>
int main() {
int key;
scanf("%s", text);
ch = text[i];
// Check for valid characters.
if (isalnum(ch)) {
//Lowercase characters.
if (islower(ch)) {
ch = (ch - 'a' + key) % 26 + 'a';
}
// Uppercase characters.
if (isupper(ch)) {
ch = (ch - 'A' + key) % 26 + 'A';
}
// Numbers.
if (isdigit(ch)) {
ch = (ch - '0' + key) % 10 + '0';
}
}
// Invalid character.
else {
printf("Invalid Message");
}
return 0;
}
Output:
We first check if the character is alphanumeric using the isalnum() method, which returns
true if the given character is an alphanumeric value, i.e., either lowercase or uppercase
alphabets or numbers. Then we check if the character is lowercase, uppercase, or a number
using islower(), isupper(), and isdigit(), respectively. Accordingly, conversion is processed.
Lastly, the encrypted character is added to the text at its position.
Similarly, we can write Caesar Cipher Program in C for decoding. Instead of adding the key
subtract it and add 26 so that we don't get a negative value as our answer.
#include<stdio.h>
#include<ctype.h>
int main() {
int key;
scanf("%s", text);
return 0;
Output:
The example above returns the value we inserted to encode in the above encoding C code in
the previous section.