Question 6
Back to Exercise
Encrypt a message by shifting letters by 3 (keeping case and leaving other characters alone), then decrypt it again.
Solution
#include <ctype.h>
#include <stdio.h>
static void shift(char *s, int k) {
for (; *s; s++) {
unsigned char c = (unsigned char) *s;
if (isalpha(c)) {
char base = isupper(c) ? 'A' : 'a';
*s = (char) (base + (c - base + k + 26) % 26);
}
}
}
int main(void) {
char msg[] = "Meet at Gate 7, Zone B!";
shift(msg, 3);
printf("%s\n", msg);
shift(msg, -3);
printf("%s\n", msg);
return 0;
}
Phhw dw Jdwh 7, Crqh E! Meet at Gate 7, Zone B!
isalpha and isupper choose the alphabet and its base letter; the modulo wraps Z around to C. Adding 26 keeps the value positive when shifting back.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!