Summary: This C program encrypts a string using a combination of Caesar cipher for alphabets and digit reversal for numeric characters. It maintains special characters unchanged and processes both lowercase and uppercase letters with a shift value.
#include <stdio.h>
#include <string.h>
void encryptString(char s[], int k) {
int n = strlen(s);
for (int i = 0; i < n; i++) {
// Check for lowercase letter
if (s[i] >= 'a' && s[i] <= 'z') {
s[i] = (s[i] - 'a' + k) % 26 + 'a';
}
// Check for uppercase letter
else if (s[i] >= 'A' && s[i] <= 'Z') {
s[i] = (s[i] - 'A' + k) % 26 + 'A';
}
// Check for digit
else if (s[i] >= '0' && s[i] <= '9') {
s[i] = 9 - (s[i] - '0') + '0';
}
// Special characters remain unchanged
}
// Print the encrypted string
printf("Encrypted string: %s\n", s);
}
int main() {
char s[1001]; // String of length up to 1000 + 1 for null terminator
int k;
// Get the input string
printf("Enter the string: ");
fgets(s, sizeof(s), stdin);
// Remove trailing newline character added by fgets
s[strcspn(s, "\n")] = 0;
// Get the shift value
printf("Enter the shift value: ");
scanf("%d", &k);
// Check constraints for k
if (k < 0 || k > 25) {
printf("Invalid shift value! Please enter a value between 0 and 25.\n");
return 1;
}
// Encrypt the string
encryptString(s, k);
return 0;
}
Program Overview:
This program encrypts a given string by applying a Caesar cipher to alphabets and reversing digits while keeping special characters unchanged.
encryptString()
:The function encryptString()
processes the string character by character and applies different transformations based on the type of character.
'a'
to 'z'
), the Caesar cipher formula is applied:s[i] = (s[i] - 'a' + k) % 26 + 'a';
k
positions in the alphabet.'A'
to 'Z'
), a similar Caesar cipher formula is applied:s[i] = (s[i] - 'A' + k) % 26 + 'A';
'0'
to '9'
), the digit is reversed using the formula:s[i] = 9 - (s[i] - '0') + '0';
'2'
becomes '7'
and '8'
becomes '1'
.k
for the Caesar cipher.fgets()
is used to read the string, and strcspn()
removes the trailing newline character.k
is between 0 and 25.encryptString()
function is called to process the input string.k
is less than 0 or greater than 25, an error message is displayed.O(n)
because the string is traversed once for encryption.O(1)
since the operations are performed in-place without extra space.