Caesar cipher code in c
#include <stdio.h>
#include <string.h>
#include <malloc.h>
char *caesar(char t[], int l, int k, int a)
{
char *ct = malloc(l);
for (int i = 0; i < l; i++)
{
int offset = (t[i] >= 65 && t[i] <= 90) ? 65 : 97;
int im = (a == 0) ? (t[i] + k) : (t[i] - k);
ct[i] = (t[i] == 32) ? 32 : ((im - offset) % 26) + offset;
}
ct[l] = '\0';
return ct;
}
int main()
{
printf("Caesar Cipher");
int c = 0;
while (c != 3)
{
printf("\n\n1.Encrypt\n2.Decrypt\n3.Exit");
printf("\nSelect Option: ");
scanf("%d", &c);
switch (c)
{
case 1:
{
char pt[50];
int k;
printf("Enter plain text: ");
scanf(" %[^\n]%*c", pt);
printf("Enter the key: ");
scanf("%d", &k);
printf("\nCipher Text: %s", caesar(pt, strlen(pt), k, 0));
break;
}
case 2:
{
char ct[50];
int k;
printf("Enter cipher text: ");
scanf(" %[^\n]%*c", ct);
printf("Enter the key: ");
scanf("%d", &k);
printf("\nOriginal Text: %s", caesar(ct, strlen(ct), k, 1));
break;
}
case 3:
return 0;
default:
printf("\nInvalid Choice!");
}
}
return 0;
}