I need some help with my program - a simple caesar cipher program. I'll come clean and admit that this is for a college class I'm taking. The assignment was to build a program that could encrypt messages by rotating the characters. I've managed to get it to work with single letters, but not with strings. I have no programming experience whatsoever so please try to explain things to me as you would to a five year old.
Code:
#include <stdio.h>
main()
{
/*
char un;
char en;
int offset, i;
printf("Enter a letter: ");
scanf("%c", &un);
fflush(stdin);
for ( ;; )
{
printf("Enter offset [1,10]: ");
scanf("%d", &offset);
if ( offset >= 1 && offset <= 10 )
break;
else
continue;
}
if ( un >= 'a' && un <= 'z' )
en += (((un - 'a') + offset) % 26) + 'a';
else
en += (((un - 'A') + offset) % 26) + 'A';
printf("Unencrypted: %c\n", un);
printf("Encrypted: %c\n", en);
fflush(stdin);
getchar();
*/
int i, offset = 1, c;
char un[51];
char en[51];
printf("Input: ");
scanf("%[^\n]", un);
for ( i = 0; i < un[i]; i++ )
en[i] += (((un[i] - 'a') + offset) % 26) + 'a';
printf("Unencrypted text: %s\n", un);
printf("Encrypted text: %s\n", en);
fflush(stdin);
getchar();
}
The "first" program works as it should, but when I tried to extend the chars to whole strings I ran into some problems, and it just outputs garbage.
So my questions is basically - why?
Also - I need for someone to break this down for me: Exactly what happens here and why? Why does the lowercase alphabet get shifted to 0-25 when lowercase 'a' is removed? I understand that modulo rotates the a --> z part but again, I don't understand why it happens or why I should put back the lowercase 'a'.. I just don't get it.. I'm in desperate need of some assistance. Please, if you have some spare time, try to clarify this to me..
Code:
en[i] += (((un[i] - 'a') + offset) % 26) + 'a';
I'd really appreciate some help..