CNS Practical-2

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

void encrypt(char text[], int key) {
    char ch;
    for (int i = 0; text[i] != '\0'; ++i) {
        ch = text[i];
        if (isalnum(ch)) {
            if (islower(ch))
                ch = (ch - 'a' + key) % 26 + 'a';
            else if (isupper(ch))
                ch = (ch - 'A' + key) % 26 + 'A';
            else if (isdigit(ch))
                ch = (ch - '0' + key) % 10 + '0';
            text[i] = ch;
        } else {
            printf("Invalid character '%c' in message. Only alphanumeric characters are allowed.\n", ch);
            return;
        }
    }
    printf("Encrypted message: %s\n", text);
}

void decrypt(char text[], int key) {
    char ch;
    for (int i = 0; text[i] != '\0'; ++i) {
        ch = text[i];
        if (isalnum(ch)) {
            if (islower(ch))
                ch = (ch - 'a' - key + 26) % 26 + 'a';
            else if (isupper(ch))
                ch = (ch - 'A' - key + 26) % 26 + 'A';
            else if (isdigit(ch))
                ch = (ch - '0' - key + 10) % 10 + '0';
            text[i] = ch;
        } else {
            printf("Invalid character '%c' in message. Only alphanumeric characters are allowed.\n", ch);
            return;
        }
    }
    printf("Decrypted message: %s\n", text);
}

int main() {
    char text[500];
    int key, choice;

    printf("Enter 1 to Encrypt, 2 to Decrypt: ");
    scanf("%d", &choice);

    printf("Enter the message: ");
    scanf("%s", text);

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

    if (choice == 1) {
        encrypt(text, key);
    } else if (choice == 2) {
        decrypt(text, key);
    } else {
        printf("Invalid choice.\n");
    }

    return 0;
}


Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top