Article 85871 of comp.lang.c: Path: winternet.com!solon.com!not-for-mail From: seebs@solutions.solon.com (Peter Seebach) Newsgroups: comp.lang.c Subject: Re: ???Recursive Function needed for string printing Date: 5 Feb 1996 07:57:20 -0600 Organization: Usenet Fact Police (Undercover) Lines: 46 Message-ID: <4f52c0$6de@solutions.solon.com> References: <4f44eo$74u@upsidedown.MTS.Net> NNTP-Posting-Host: solutions.solon.com In article <4f44eo$74u@upsidedown.MTS.Net>, George wrote: >How do I write a recursive function to print a string using only >printf and %c to print it out. Since you need a %s to print a string, of course, you really need a function to recursively create a %s without using it in the code. This should work just fine: #include int far(int, char *); /* prototype our function to print a string */ int main(int argc, char **argv) { return far(0, argc > 1 ? argv[1] : "test string"); } /* set up format string. */ enum { ONE = 0x0, NUL = 0x1, NEW = 11, PERCENT = 0x26, ESS = 0x74 } fmt[] = { PERCENT, ESS, NEW, NUL, ONE }; /* far: print a string. * we take two paramaters, "near" -> how close we are to finished, * "s", the string to print. * we recurse through fmt building a format string in buf, then use * it to print our string. */ int far(int near, char *s) { static char buf[5]; if (fmt[near]) { buf[near] = fmt[near] - 1; /* the previous item */ far(near + 1, s); /* recursion */ } return near ? 1 : !printf(buf, s); } -- Peter Seebach - seebs@solon.com - Copyright 1995 Peter Seebach. C/Unix wizard -- C/Unix questions? Send mail for help. No, really! Using trn? Weird new newsgroup problem? I know the fix! Email me! The *other* C FAQ - ftp taniemarie.solon.com /pub/c/afq - Not A Flying Toy