ENCRYPT, DECRYPT

PHOTO EMBED

Fri Nov 15 2024 17:55:08 GMT+0000 (Coordinated Universal Time)

Saved by @coding1

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

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

void decrypt(char *text, int key) {
    // Decrypt by shifting in the opposite direction
    for (int i = 0; text[i] != '\0'; i++) {
        // Decrypt uppercase letters
        if (text[i] >= 'A' && text[i] <= 'Z') {
            text[i] = (text[i] - 'A' - key + 26) % 26 + 'A';  // +26 to handle negative
        }
        // Decrypt lowercase letters
        else if (text[i] >= 'a' && text[i] <= 'z') {
            text[i] = (text[i] - 'a' - key + 26) % 26 + 'a';  // +26 to handle negative
        }
    }
}

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

    printf("Enter the text to encrypt: ");
    fgets(text, sizeof(text), stdin);
    text[strcspn(text, "\n")] = 0; // Remove trailing newline

    printf("Enter the encryption key (shift): ");
    scanf("%d", &key);

    encrypt(text, key);
    printf("Encrypted text: %s\n", text);

    decrypt(text, key);
    printf("Decrypted text: %s\n", text);

    return 0;
}

content_copyCOPY