Write a program that encodes and decodes words. In an encoded word every letter
ID: 3721711 • Letter: W
Question
Write a program that encodes and decodes words.
In an encoded word every letter is replaced by a number followed by either U or L. THe number represents the position of the character in the alphabet, U or u indicates uppercase and L or l would represent lowercase. So for example: Hello would be encoded as 8U5L12L12L15L.
If user chooses option 1:
Program prompts the user to input a word and press enter when they are done. Reads the word one character at a time and output the encoded version of the word following the rules above.
If user chooses option 2
Program prompts the user to input an encoded word and press enter. The program needs to read that word two character at a time output the original word on the screen one character at a time.
MUST USE:
Void encode (char);
Void decode (int, char);
No arrays may be used
Explanation / Answer
Since you have not provided yourlanguage preference, i am providing the code in C.
#include <stdio.h>
#include <stdlib.h>
#define MAX 500
void encode(char *msg) {
char encoded[MAX];
int num[MAX];
int j=0;
int k=0;
for(int i=0; msg[i] != ''; i++) {
if(msg[i] >= 'A' && msg[i] <= 'Z') {
num[j ++] = ((int)(msg[i]) - 'A' + 1);
encoded[k ++] = 'U';
} else if(msg[i] >= 'a' && msg[i] <= 'z') {
num[j ++] = ((int)(msg[i]) - 'a' + 1);
encoded[k ++] = 'L';
}
}
encoded[k] = '';
printf("The encoded message is : ");
for(int i=0; encoded[i] != ''; i++) {
printf("%d%c", num[i], encoded[i]);
}
}
void decode(char *msg) {
char decoded[MAX];
int k=0;
for(int i=0; msg[i] != ''; i+=2) {
if(msg[i+1] == 'U') {
decoded[k ++] = (char)(msg[i] + 'A' - 1);
} else if(msg[i+1] == 'L') {
decoded[k ++] = (char)(msg[i] + 'a' - 1);
}
}
decoded[k] = '';
printf("The decoded message is : ");
for(int i=0; decoded[i] != ''; i++) {
printf("%c", decoded[i]);
}
}
int main() {
printf("1. Encode 2. Decode ");
int ch;
printf("Enter your choice: ");
scanf("%d", &ch);
char msg[MAX];
if(ch == 1) {
printf("Enter the plain message: ");
scanf("%s", msg);
encode(msg);
} else {
printf("Enter the encoded message: ");
scanf("%s", msg);
decode(msg);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.