Skip to content

Instantly share code, notes, and snippets.

@pry0cc
Created February 6, 2015 23:26
Show Gist options
  • Save pry0cc/55aa9e70d593ac49b018 to your computer and use it in GitHub Desktop.
Save pry0cc/55aa9e70d593ac49b018 to your computer and use it in GitHub Desktop.
CaesarCipher in C! Will probably only work on Linux/Unix, I used the -std=c99 compiler.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
/*encypt.c*/
// Function prototypes
int CipherChar(char *s, int offset);
int CipherStr(char *s, int offset);
// Array of characters declared globally to avoid scope issues.
int alpha[26] = {'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'};
int main() {
char *input = malloc(100 * sizeof(char));
char c;
int count = 0;
int offset = 16;
printf("Please enter string to be encrypted >> ");
while( (c = getchar()) != '\n' ) {
input[count++] = tolower(c);
}
CipherStr(input, offset);
}
int CipherStr(char *message, int offset) {
for(int i = 0; i < strlen(message); i++) {
char cha = message[i];
printf("%c", CipherChar(&cha, offset));
}
printf("\n");
}
int CipherChar(char *s, int offset) {
int i;
for(i = 0; i < 26; i++) {
int total = i + offset;
if(*s == alpha[i]) {
while(total > 25) {
total = total -26;
}
return alpha[total];
}
}
if (*s != alpha[i]) {
return *s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment