LearnFrenzy
Sign in Take a free test

C Library Functions · Library Function Programs · Question 6

Caesar cipher using isalpha, isupper and islower in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Encrypt a message by shifting letters by 3 (keeping case and leaving other characters alone), then decrypt it again.

Solution
main.c
#include <ctype.h>
#include <stdio.h>

static void shift(char *s, int k) {
    for (; *s; s++) {
        unsigned char c = (unsigned char) *s;
        if (isalpha(c)) {
            char base = isupper(c) ? 'A' : 'a';
            *s = (char) (base + (c - base + k + 26) % 26);
        }
    }
}

int main(void) {
    char msg[] = "Meet at Gate 7, Zone B!";
    shift(msg, 3);
    printf("%s\n", msg);
    shift(msg, -3);
    printf("%s\n", msg);
    return 0;
}

Output Verified by compiling and running

Phhw dw Jdwh 7, Crqh E!
Meet at Gate 7, Zone B!

isalpha and isupper choose the alphabet and its base letter; the modulo wraps Z around to C. Adding 26 keeps the value positive when shifting back.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links