C Online Compiler
Example: Caesar Cipher Encryption and Decryption in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Caesar Cipher Encryption and Decryption #include <stdio.h> #include <string.h> #include <ctype.h> // For isalpha, isupper, islower // Function to encrypt a message using Caesar Cipher void encryptCaesar(char text[], int key) { int i; for (i = 0; text[i] != '\0'; ++i) { char ch = text[i]; // Encrypt uppercase letters if (isupper(ch)) { ch = (char)(((ch - 'A' + key) % 26) + 'A'); } // Encrypt lowercase letters else if (islower(ch)) { ch = (char)(((ch - 'a' + key) % 26) + 'a'); } // Non-alphabetic characters remain unchanged text[i] = ch; } } // Function to decrypt a message using Caesar Cipher void decryptCaesar(char text[], int key) { int i; for (i = 0; text[i] != '\0'; ++i) { char ch = text[i]; // Decrypt uppercase letters if (isupper(ch)) { ch = (char)(((ch - 'A' - key + 26) % 26) + 'A'); // Add 26 to handle negative results of (ch - 'A' - key) } // Decrypt lowercase letters else if (islower(ch)) { ch = (char)(((ch - 'a' - key + 26) % 26) + 'a'); // Add 26 for similar reasons } text[i] = ch; } } int main() { // Step 1: Declare variables for message and key char message[100]; int key; printf("Enter a message to encrypt: "); fgets(message, sizeof(message), stdin); message[strcspn(message, "\n")] = 0; // Remove trailing newline printf("Enter key (an integer): "); scanf("%d", &key); key = key % 26; // Ensure key is within 0-25 range for alphabet wrap-around // Step 2: Encrypt the message char encryptedMessage[100]; strcpy(encryptedMessage, message); // Copy original message to encrypt encryptCaesar(encryptedMessage, key); printf("Encrypted message: %s\n", encryptedMessage); // Step 3: Decrypt the message char decryptedMessage[100]; strcpy(decryptedMessage, encryptedMessage); // Copy encrypted message to decrypt decryptCaesar(decryptedMessage, key); printf("Decrypted message: %s\n", decryptedMessage); return 0; }
Output
Clear
ADVERTISEMENTS