How to Implement Caesar's Cipher in C

Jinku Hu Mar 12, 2025 C C Algorithm
  1. What is Caesar’s Cipher?
  2. Implementing Caesar’s Cipher in C
  3. Implement Caesar Cipher to Process User-Provided String in C
  4. Conclusion
  5. FAQ
How to Implement Caesar's Cipher in C

Caesar’s Cipher is one of the simplest and most well-known encryption techniques. Named after Julius Caesar, who reportedly used it to communicate with his generals, this substitution cipher shifts the letters of the alphabet by a fixed number of places. Implementing Caesar’s Cipher in C is an excellent way to grasp fundamental programming concepts such as loops, conditionals, and character manipulation.

In this article, we’ll walk you through the steps to code this classic cipher in C, providing clear examples and explanations along the way. Whether you’re a beginner or looking to refresh your skills, this guide will help you understand how to implement Caesar’s Cipher effectively.

What is Caesar’s Cipher?

Before diving into the implementation, let’s briefly understand how Caesar’s Cipher works. The basic idea is to replace each letter in the plaintext with a letter found by moving a fixed number of places down the alphabet. For instance, with a shift of 3, A becomes D, B becomes E, and so forth, wrapping around to the beginning of the alphabet if necessary. This method is simple yet effective for basic encryption needs.

Implementing Caesar’s Cipher in C

Now, let’s get into the actual implementation of Caesar’s Cipher in C. We’ll create a program that takes a string input from the user and a shift value, then outputs the encrypted string.

Code Example

Here’s how you can implement Caesar’s Cipher in C:

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

void encrypt(char *text, int shift) {
    for (int i = 0; text[i] != '\0'; i++) {
        char c = text[i];
        if (c >= 'a' && c <= 'z') {
            text[i] = (c - 'a' + shift) % 26 + 'a';
        } else if (c >= 'A' && c <= 'Z') {
            text[i] = (c - 'A' + shift) % 26 + 'A';
        }
    }
}

int main() {
    char text[100];
    int shift;

    printf("Enter text to encrypt: ");
    fgets(text, sizeof(text), stdin);
    printf("Enter shift value: ");
    scanf("%d", &shift);

    encrypt(text, shift);
    printf("Encrypted text: %s", text);
    
    return 0;
}

Output:

Enter text to encrypt: Hello World
Enter shift value: 3
Encrypted text: Khoor Zruog

The program begins by including necessary libraries and defining the encrypt function. This function takes the input text and the shift value as arguments. It iterates through each character of the input string. If the character is a lowercase letter, it shifts it by the specified amount within the bounds of the lowercase alphabet. The same logic applies to uppercase letters. The main function handles user input and displays the encrypted text.

Explanation of Code

In the code above, we first declare a character array to hold the text and an integer for the shift value. The fgets function is used to read the input string, which allows for spaces in the text. The encrypt function processes each character, checking if it’s an uppercase or lowercase letter and applying the shift accordingly. The modulo operator ensures that the shift wraps around the alphabet, maintaining the correct character range. Finally, the encrypted text is printed to the console.

Implement Caesar Cipher to Process User-Provided String in C

Alternatively, we can reimplement the previous code sample to take both text and rotation position from the user input, verify them, and encrypt the given string. In contrast with the previous example, this version includes two fgets calls and malloc to allocate dynamic memory for the cleartext. This implementation also deals with lowercase strings and would not be able to encrypt a mixed string correctly.

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

enum { MAX_LEN = 1024 };

int main(void) {
  size_t len;
  int shift;
  char *text;
  char num[16];

  text = malloc(MAX_LEN);
  if (text == NULL) {
    perror("malloc");
    exit(EXIT_FAILURE);
  }

  printf("Input text to be encrypted (lowercase): ");
  fflush(stdout);
  if (fgets(text, MAX_LEN, stdin) == NULL) exit(EXIT_FAILURE);

  len = strlen(text);
  if (text[len - 1] == '\n') text[len - 1] = '\0';
  len -= 1;

  printf("Choose shift number [1-26]: ");
  fflush(stdout);
  if (fgets(num, 16, stdin) == NULL) exit(EXIT_FAILURE);

  shift = (int)strtol(num, NULL, 0);
  if (shift < 1 || shift > 26) {
    fprintf(stderr, "Shift number is out of range");
    exit(EXIT_FAILURE);
  }

  for (int i = 0; i < len; ++i) {
    if (!isspace(text[i]) || !isblank(text[i]))
      printf("%c", (((text[i] - 97) + shift) % 26) + 97);
    else
      printf("%c", text[i]);
  }

  exit(EXIT_SUCCESS);
}

Below is the brief explanation.

  1. User Input:
    • The program prompts the user to input a string to be encrypted (expected in lowercase).
    • It then asks for a shift number between 1 and 26.
  2. Memory Allocation:
    • The code uses malloc to dynamically allocate memory for the input string.
  3. Encryption Process:
    • It iterates through each character in the input string.
    • For non-space characters, it applies the Caesar Cipher by shifting the character’s ASCII value by the specified amount, wrapping around the alphabet if necessary.
    • Space characters are left unchanged.
  4. Error Handling:
    • The program checks for memory allocation failures and invalid shift numbers, exiting with an error message if either condition occurs.

This implementation is designed for lowercase strings and does not handle mixed-case strings correctly.

Conclusion

Implementing Caesar’s Cipher in C is a straightforward exercise that helps build foundational programming skills. By understanding how to manipulate characters and implement basic algorithms, you can create a simple yet effective encryption tool. This encryption technique may not be the most secure, but it serves as an excellent introduction to the world of cryptography. As you become more comfortable with C programming, you can explore more complex encryption methods and enhance your skills further.

FAQ

  1. What is Caesar’s Cipher?
    Caesar’s Cipher is a substitution cipher that shifts letters in the alphabet by a fixed number of places for encryption.

  2. Is Caesar’s Cipher secure?
    No, it is not secure by modern standards and can be easily broken with frequency analysis.

  3. Can I use Caesar’s Cipher for any type of text?
    While it works best with alphabetic text, it can also be applied to any characters by modifying the implementation.

  4. What programming concepts can I learn by implementing Caesar’s Cipher?
    You can learn about loops, conditionals, character manipulation, and basic string handling.

  5. Can I implement Caesar’s Cipher in other programming languages?
    Yes, Caesar’s Cipher can be implemented in virtually any programming language, making it a versatile exercise.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook