Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Caesar shift in C

Tags:

c

I'm trying to create a simple Caesar shift program in C but I can't seem to figure it out. The program keeps crashing. Any help would be greatly appreciated.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int arc, const char* argv[])
{
    int shift = atoi(argv[1]);
    char message[256];
    strcpy(message, argv[2]);
    int i;
    for(i = 0; i < strlen(message); i++) {
        printf("%c", message[i] + shift);
    }
    putchar('\n');
    return 0;
}
like image 710
poopnugget Avatar asked Dec 10 '25 21:12

poopnugget


1 Answers

You're not correctly implementing the Caesar Cipher. Your code includes the following line, which is wrong:

printf("%c", message[i] + shift);

To do this correctly, you'll want to convert that to a function:

printf("%c", encrypt(message[i], shift));

And let's implement the function:

char encrypt(char input, int shift) {
    if (input >= 'a' && input <= 'z')
        return ((input - 'a' + shift) % 26) + 'a';
    if (input >= 'A' && input <= 'Z')
        return ((input - 'A' + shift) % 26) + 'A';
    return input;
}

And just to explain what the math is doing in that function:

  1. input - 'a' tells us what position in the alphabet the input is (assuming input is a lowercase letter). So if the input is 'c', then we will get a 2 back. If the input is 'z', we get 25.
  2. input - 'a' + shift gets us the new position of the character that we are using to do the cipher. Note that this could be a larger number than the alphabet (26 characters).
  3. So to solve that problem, we use modular arithmetic to bound that number between [0 - 25].
  4. Then adding 'a' to that character gets us the actual character we want to print.

Note that this only works because the character codes for a to z and A to Z are consecutive.

like image 72
Bill Lynch Avatar answered Dec 13 '25 16:12

Bill Lynch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!