rstrlen.c

/*
 * rstrlen -- get length of string recursively
 *
 * Matt Bishop, ECS 36A
 *
 * April 30, 2024
 *      -- original program written
 */

#include <stdio.h>

/*
 * macro
 */
#define MAXLEN	1024	/* max length of input */

/*
 * recursive string length calculation
 */
int rstrlen(char *s)
{
	/* base case: if string is empty, length is 0 */
	if (*s == '\0')
		return(0);

	/* recursion: lop off first char, get length of rest, add 1, return it */
	return(1 + rstrlen(s+1));
}

/*
 * main program
 */
int main(void)
{
	char buf[MAXLEN];	/* input buffer */
	char *b;		/* pointer used to find \n or end ofinput line */

	/*
	 * keep going until you get an EOF
	 */
	while(fgets(buf, 1000, stdin) != NULL){
		/* clobber the first newline (shouldbe at the end, if present) */
		for(b = buf; *b != '\0' && *b != '\n'; b++)
			;
		*b = '\0';
		/* print the string and itslength */
		printf("string '%s' is %d characters long\n",
							buf, rstrlen(buf));
	}

	/* do svidanya! */
	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