Write a program to encode text and to decode the encoded text.
Perfrom the encoding saccording to these replacements
\(\begin{array}{c c c c c c c c c c c c c c c c c c c c c c c c c c} a&b&c&d&e&f&g&h&i&j&k&l&m&n&o&p&q&r&s&t&u&v&w&x&y&z \\ m&n&k&g&h&d&t&a&b&w&v&u&p&r&q&c&z&j&x&i&e&y&f&l&o&s\end{array}\)
Example:
plain text: Program
Encoded text: Cjqtjmp
Decoded text: Program
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define SIZE 100
void main()
{
char plain[SIZE], encoded[SIZE], decoded[SIZE];
// the matching1 array contains the correspondance between the plain text and
// the encoded text. Example, 'm' will be in place of 'a' and so on
// matching2 array is the correspondance between the encoded and decoded text
char matching1[26]={'m','n','k','g','h','d','t','a','b','w','v','u','p','r','q','c','z','j','x','i','e','y','f','l','o','s'};
char matching2[26]={'h','i','p','f','u','w','d','e','t','r','c','x','a','b','y','m','o','n','z','g','l','k','j','s','v','q'};
int i;
printf("Enter a string : ");
gets(plain);
// we loop on the plain text
for(i=0; plain[i]!='\0'; i++)
// in case the character is a lower case
// we retreive the index of matching1 by substracting 'a'
// Example, if plain[i] is equal to 'b', 'b'-'a' will
// be equal to 1 and thus, we get the corresponding character
// in matching1 at index 1.
if(plain[i]>='a' && plain[i] <='z')
encoded[i]=matching1[plain[i]-'a'];
else
// if the character is an upper case, we do the same,
// to get the correspondance, however the array stores
// lowercase correspondance, we need to convert it to
// uppercase. it suffices to substract 'a' and add 'A'
encoded[i]=matching1[plain[i]-'A']-'a'+'A';
encoded[i]='\0';
for(i=0; encoded[i]!='\0'; i++)
if(encoded[i]>='a' && encoded[i] <='z')
decoded[i]=matching2[encoded[i]-'a'];
else
decoded[i]=matching2[encoded[i]-'A']-'a'+'A';
decoded[i]='\0';
printf("Plain text: %s\n", plain);
printf("Encoded text: %s\n", encoded);
printf("Decoded text: %s\n", decoded);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Recursively reverse a stack