ispal.c

/*
 * ispal -- determines if a string is a palindrome
 * it loops, reading strings, and checking each one
 *
 * Matt Bishop, ECS 36A
 * * October 18, 2019: wrote program
 */
#include <stdio.h>
#include <string.h>

/*
 * pal(char *s, int b, int e)
 * s is string containing string to check
 * check s[b]..s[e] to see if it's a palindrome
 *
 * returns 1 if s[b]..s[e]is a palindrome, 0 if not
 */
int pal(char *s, int b, int e)
{
	/* base case, part 1: string is 0 or 1 long */
	/* it's a palindrome if so                  */
	if (b >= e)
		return(1);

	/* base case part 3: if chars at beginning, end */
	/* of string are different, not a palindrome    */
	if (s[b] != s[e])
		return(0);

	/* recursive case: if middle is a palindrome */
	/* the whole thing is a palindrome           */
	return(pal(s, b+1, e-1));
}

/*
 * the main routine
 */
int main(void)
{
	char line[1024];	/* buffer to hold input line */

	/* prompt the user for input */
	printf("> ");

	/*
	 * now loop reading input and checking it
	 * quit when user types EOF
	 */
	while(fgets(line, 1024, stdin) != NULL){
		/* clobber the trailing newline */
		if (line[strlen(line)-1] == '\n')
			line[strlen(line)-1] = '\0';
		/* now see if it's a palindrome */
		if (pal(line, 0, strlen(line)-1))
			printf("%s is a palindrome\n", line);
		else
			printf("%s is not a palindrome\n", line);
		/* prompt for more input */
		printf("> ");
	}

	/* done -- skip to next line and then quit */
	putchar('\n');
	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