caesar-dec.c

/*
 * caesar-dec: program to decrypt for Caesar cipher
 * This simply subtracts 3 from each letter, circularly
 * To change the shift, change "key" -- do NOT make
 * it negative!!!!
 *
 * Matt Bishop, ECS 36A
 * April 12, 2024	original version
 */
#include <stdio.h>
#include <ctype.h>

/*
 * globals
 */
int key = 3;	/* amount of shift */

/*
 * decipher a letter -- the letter is 0 (A) to 25 (Z)
 */
int decipher(int n)
{
	return((n - key + 26) % 26);
}

/*
 * the main routine
 */
int main(void)
{
	int ch;		/* input character */
	int newch;	/* shifted character or input character */

	/*
	 * loop reading characters until you read an EOF
	 */
	while ((ch = getchar()) != EOF){
		/* see if it's a letter */
		if (isupper(ch)){
			/* capital letter -- shift it */
			/* and keep it a capital      */
			newch = decipher(ch - 'A') + 'A';
		}
		else if (islower(ch)){
			/* lower case letter -- shift it */
			/* and keep it a lower case      */
			newch = decipher(ch - 'a') + 'a';
		}
		else{
			/* not a letter -- leave it alone */
			newch = ch;
		}

		/*
		 * print the character
		 */
		putchar(newch);
	}

	/* all done */
	return(0);
}




UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh