Answers for "Caesar cipher code in c"

C
0

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;
}
Posted by: Guest on July-25-2021
0

caesar cipher in c program

#include <stdio.h>
#include <ctype.h>

#define MAXSIZE 1024

void encrypt(char*);
void decrypt(char*);

int menu();

int
main(void)
{

char c,
     choice[2],
     s[MAXSIZE];

 while(1)
 {
 menu();

 gets(choice);

 if((choice[0]=='e')||(choice[0]=='E'))
 {
  puts("Input text to encrypt->");
  gets(s);
  encrypt(s);
 }
 else if((choice[0]=='d')||(choice[0]=='D'))
 {
  puts("Input text to decrypt->");
  gets(s);
  decrypt(s);
 }
 else
    break;
 }

 return 0;
}

void encrypt(char*str)
{
	int n=0;
	char *p=str,
		 q[MAXSIZE];

	while(*p)
	{
	 if(islower(*p))
	 {
		 if((*p>='a')&&(*p<'x'))
			 q[n]=toupper(*p + (char)3);
		 else if(*p=='x')
			 q[n]='A';
		 else if(*p=='y')
			 q[n]='B';
		 else
			 q[n]='C';
	 }
	 else
	 {
		 q[n]=*p;
	 }
	 n++; p++;
	}
	q[n++]='\0';
	puts(q);
}

void decrypt(char*str)
{
	int   n=0;
	char *p=str,
		 q[MAXSIZE];

	while(*p)
	{
	 if(isupper(*p))
	 {
		 if((*p>='D')&&(*p<='Z'))
			 q[n]=tolower(*p - (char)3);
		 else if(*p=='A')
			 q[n]='x';
		 else if(*p=='B')
			 q[n]='y';
		 else
			 q[n]='z';
	 }
	 else
	 {
		 q[n]=*p;
	 }
	 n++; p++;
	}
	q[n++]='\0';
	puts(q);
}

int menu()
{
 puts("To encrypt, input e or E\n");
 puts("To decrypt, input d or D\n");
 puts("To exit, input any other letter\n");
 puts("Your choice:->\n");
 return 0;
}
Posted by: Guest on June-01-2021

Code answers related to "C"

Browse Popular Code Answers by Language