2

I'm trying to write a caesar cipher program that takes an argument, converts it into an integer, and uses that as to shift the letters in a certain direction (positive numbers shift it forward and negative numbers shift it backwards. So far all the program works for all positive numbers but does not for negative numbers.

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


int encrypt(int character, int shift);

int main(int argc, char * argv[]) {

    int shift = atoi(argv[1]);
    if (shift >= 26) {
        shift = ((shift + 26) % 26);
    }

    int character = getchar();

    while (character != EOF) {
        int new_character = encrypt(character, shift);
        putchar(new_character);
        character = getchar();
    }

    return 0;

}

int encrypt(int character, int shift) {
    int ch = character;
    int negShift = shift;

    if (ch >= 'a' && ch <= 'z') {
        ch = ch + shift;
        if (ch > 'z') {
            ch = ch - 'z' + 'a' - 1;
        }
    } else if (ch >= 'A' && ch <= 'Z') {
        ch = ch + shift;
        if (ch > 'Z') {
            ch = ch - 'Z' + 'A' - 1;
        }
    }

    return ch;
}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328

1 Answers1

3

You could just add the 26 to ch when ch < 'a' or ch <'A'. Consider below example.

    if(ch < 'a')
     {
      ch  = ch + 26;
     } 

Full code.

int encrypt(int character, int shift) {
    int ch = character;
    int negShift = shift;

    if (ch >= 'a' && ch <= 'z') {
        ch = ch + shift;
        if (ch > 'z') {
            ch = ch - 'z' + 'a' - 1;
        }

         else if(ch < 'a')
         {
            ch  = ch + 26; //Here
         } 

    } else if (ch >= 'A' && ch <= 'Z') {
        ch = ch + shift;
        if (ch > 'Z') {
            ch = ch - 'Z' + 'A' - 1;
        }

        else if(ch < 'A')
        {
            ch = ch + 26; // Here 
        }

    }

    return ch;
}
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44