Caesar Cipher
Completed
Read a shift k and a line. Shift letters by k (wrapping, keeping case); leave other characters unchanged.
Input
Line 1: k (0–25). Line 2: text.
Output
The encoded text.
Example
Input
3 Hello, World!
Output
Khoor, Zruog!
Editor
C
Hints
After scanf, getchar() eats the leftover new line before fgets.
Work with positions 0-25 and use % 26.
Solution explanation
Mixing scanf and fgets needs care: scanf leaves the new line behind.
Show solution
#include <stdio.h>
#include <string.h>
int main() {
int k;
char s[300];
scanf("%d", &k);
getchar();
fgets(s, 300, stdin);
s[strcspn(s, "\n")] = '\0';
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] >= 'a' && s[i] <= 'z') s[i] = 'a' + (s[i] - 'a' + k) % 26;
else if (s[i] >= 'A' && s[i] <= 'Z') s[i] = 'A' + (s[i] - 'A' + k) % 26;
}
printf("%s\n", s);
return 0;
}