caesar-enc.c

/*
 * caesar-enc: prgram to encrypt for Caesar cipher
 * This simply adds 3 to 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 */

/*
 * encipher a letter -- the letter is 0 (A) to 25 (Z)
 */
int encipher(int n)
{
	return((n + key) % 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 = encipher(ch - 'A') + 'A';
		}
		else if (islower(ch)){
			/* lower case letter -- shift it */
			/* and keep it a lower case      */
			newch = encipher(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: [email protected]
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