Hodor
Hodor

Reputation: 53

Caesar’s cipher encryption program in C

I am using this code for Caesar’s cipher encryption program. c = (alpha + k) % 26; //c = cipher text ASCII code, "alpha" alphabet ASCII code, "k" key for cipher text; this equation gives me zero(0) on all the 26 alphabets.

Thank You!

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

int main (int argc, string argv[]) {

    // took key from user and converted it to int
    int k = atoi (argv[1]);

    // get plaintext from user
    string p = GetString ();

    int c = 0, alpha = 0;

    for (int i = 0, n = strlen(p); i < n; i++)
    {
        // if it is alphabet else if not alphabet
        if (isalpha (p[i]) == true) {

            // if it is capital case else lower case
            if (isupper(p[i]) == true) {
                alpha = p[i] - 65;

                // add key to plaintext then take modulas
                c = (alpha + k) % 26;

                alpha = c + 65;
            } else {
                alpha = p[i] - 97;

                // add key to plaintext then take modulas
                c = (alpha + k) % 26;

                alpha = c + 97;
            }

        } else {
            alpha = p[i];
        }

        printf("%c \n",  alpha);
    }
}

Upvotes: 0

Views: 915

Answers (1)

Biruk Abebe
Biruk Abebe

Reputation: 2233

From documentation of isalpha

Each of these routines returns nonzero if c is a particular representation of an alphabetic character

So when you say if (isalpha (p[i]) == true) you are comparing what ever non-zero value returned by isalpha()(which may not be 1) with 1(true) which may not hold true and that if block will not be executed. The same goes for isupper(). So basically i don't think the equation is giving you zero, its just the if block the equation is in is not being executed.

You may want to do:

if (isalpha(p[i])
{

   if (isupper(p[i])
   {
      //your code
   }
   ...//your code
}

Upvotes: 2

Related Questions