Private Joker
Private Joker

Reputation: 21

C Caesar Chiper - error with big keys

I've searched the web quite long for a simple caesar chiper/encryption algorithm in C language. I found one but is wasn't perfect so I already changed the code. Still having problems, because a friend said that the programm should be able to handle big key's, too. For example text "Hello World" with a Key: 50... And if I do that I get the following: (Console output)

This tiny application encodes plain text to the Caesar Encryption
Type in some text to decode: Hello World
Type in the key/shifting of the letters:
50
`}ääç oçèä|

Which is wrong.... And maybe the problem is the char/array - I don't know...So I would be happy if you could help me with that :)

Here is the source code(with some comments):

#include <stdio.h>
#include <conio.h>
#include <wchar.h>

int main()
{
unsigned char array[100], shifting; //creating 2 arrays for the encryption
//I changed it to unsigned char because otherwise Z with key 6/7 dosen't work
int z; //This is our key
printf("This tiny application encodes plain text to the Caesar Encryption\n");

printf("Type in some text to decode :");
fgets(array, 100, stdin); //because gets() is bad I'am using fgets()
printf("Type in the key/shifting of the letters:\n");
scanf("%d", &z);

for (int i = 0; array[i] != '\0'; i++) 
{
    shifting = array[i]; //overgive values from array to shifting
    if (shifting >= 'a' && shifting <= 'z') { //check the containing lowercase letters
        shifting = shifting + z;

        if (shifting > 'z') {
            shifting = shifting - 'z' + 'a' - 1; // if go outside the ascii alphabeth this will be done
        }

        array[i] = shifting;
    }
    else if (shifting >= 'A' && shifting <= 'Z') { //the same for uppercase letters
        shifting = shifting + z;

        if (shifting > 'Z') {
            shifting = shifting - 'Z' + 'A' - 1;
        }

        array[i] = shifting;
    }
}

printf("%s\n", array);

return 0;
}

Upvotes: 0

Views: 126

Answers (1)

CiaPan
CiaPan

Reputation: 9570

The source of your problem is here:

    if (shifting > 'z') {
        shifting = shifting - 'z' + 'a' - 1; // if go outside the ascii alphabeth this will be done
    }

What's the length of the English alphabet? It's 26.

If you give z greater than 26, a single decrement by the alphabet length does not suffice. You should either make sure z does not exceed the length of alphabet, of repeat decrementing until the result fits the alphabet range.

Solution 1:

    int asciiAlphabetLength = 'z' - 'a' + 1;

    printf("Type in the key/shifting of the letters:\n");
    scanf("%d", &z);
    z %= asciiAlphabetLength;

Solution 2:

    shifting += z;

    while (shifting > 'z') {
        shifting -= asciiAlphabetLength; // while outside the ascii alphabeth reduce
    }

Upvotes: 2

Related Questions