TIP: Click on subject to list as thread! ANSI
echo: aust_c_here
to: Sam Benson
from: Michael Stapleton
date: 1996-06-06 22:01:00
subject: Re: Understanding recursion

-=> Quoting Sam Benson to All <=-

Hello Sam,

SB> If I put line_in = "This is a test string.", why do I get output of

SB> ----CUT----
SB> This is a test string.

SB> .gnirts tset a si sih
SB> ----CUT----

SB> It keeps dropping the first letter in the last line.

It will also put two nuls (00 bytes) in there. Redirect the output &
look at a hex dump. The output below is from a 68xxx machine.

0000: 54686973 20697320 61207465 73742073    This is a test s
0010: 7472696E 672E0000 2E676E69 72747320    tring....gnirts
0020: 74736574 20612073 69207369 68          tset a si sih        

SB> Why?

Because your loop skips the initial byte of the string because of
the index++. :)

SB> The bit of code that is doing this is
SB> (with the value passed to index = 0)

SB> void reverse (char line_in[], int index)
SB> {
SB>     if (line_in[index])
SB>     {
SB>         printf ("%c", line_in[index]);
SB>         index++;
SB>         reverse (line_in, index);
SB>     }
SB>     printf ("%c", line_in[index]);
SB> }

SB> I'm using DJGPP 2.0 for a compiler and learning C from it.  Yes
SB> I know that is a hard way of doing it, but I'm learnig slowly.

You're a brave man! We'll try to help. :)

Try this; although you still get one null in the middle of the
string.

/* Reverse a string.  Public Domain.
By Michael Stapleton of Graphic Bits.
Tested Jun 6 1996 19:56:55 */

#include 
#include 

void reverse (char line_in[], int index)
{
    if (line_in[index])
    {
        printf ("%c", line_in[index++]);
        reverse (line_in, index--);
    }

    printf ("%c", toupper(line_in[index]));
}

int main(void)
{
	reverse("this is another test string", 0);

	return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * */

Not to mention...

/*
   A challenge - reverse the 1st argument
   in the smallest possible ANSI C program.
   The program must not contain any # or ?
   and at most 1 ; and 2 ,

   This solution from VinhHao Nguyen

main(int c, char **s)
{
    putchar(*--s[!*++s[1] || main(c, s)]);
}

Origin: Rapid Mail BBS - +32-71-591663 (2:293/3205.123) */

main(int c,char**s){putchar(*--s[!*++s[1]||main(c,s)]);}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * */

Michael Stapleton of Graphic Bits.

 * AmyBW v2.10 *
... "I just forgot to increment", he said, nonplussed.
--- AmyBW v2.10
* Origin: The Three Amigas - better than two (3:713/615)
SEEN-BY: 50/99 620/243 623/630 711/401 409 410 413 430 808 809 932 934
SEEN-BY: 712/508 515 713/111 317 601 611 615 618 700 826 888 914 714/906
SEEN-BY: 800/1
@PATH: 713/615 888 711/808 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.