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 character char encryptChar(char ch, int key) { if (isalpha(ch)) { char base = isupper(ch) ? 'A' : 'a'; return (char)(((ch - base + key) % 26) + base); } return ch; // Return non-alphabetic characters as is } // Function to decrypt a character char decryptChar(char ch, int key) { if (isalpha(ch)) { char base = isupper(ch) ? 'A' : 'a'; // Add 26 to handle negative results from (ch - base - key) return (char)(((ch - base - key + 26) % 26) + base); } return ch; // Return non-alphabetic characters as is } int main() { char message[100]; int key; // Step 1: Get input message from the user printf("Enter a message: "); fgets(message, sizeof(message), stdin); // Remove trailing newline character if present message[strcspn(message, "\n")] = 0; // Step 2: Get the encryption/decryption key printf("Enter the key (1-25): "); scanf("%d", &key); // Step 3: Normalize key to be within 0-25 range key = key % 26; if (key < 0) { // Handle negative keys to make them positive shifts key += 26; } // Step 4: Encrypt the message char encryptedMessage[100]; strcpy(encryptedMessage, message); // Copy original message to encrypt for (int i = 0; encryptedMessage[i] != '\0'; i++) { encryptedMessage[i] = encryptChar(encryptedMessage[i], key); } printf("Encrypted message: %s\n", encryptedMessage); // Step 5: Decrypt the message char decryptedMessage[100]; strcpy(decryptedMessage, encryptedMessage); // Copy encrypted message to decrypt for (int i = 0; decryptedMessage[i] != '\0'; i++) { decryptedMessage[i] = decryptChar(decryptedMessage[i], key); } printf("Decrypted message: %s\n", decryptedMessage); return 0; }
Output
Clear
ADVERTISEMENTS