Jump to content

why the result is backwards...

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
noteeth

noteeth

    Newbie

  • Members
  • PipPip
  • 21 posts
hai everybody...its me noteeth...sorry long time no see :crying:
i hope u all fine...
i dont have any idea about this code...hope some1 can explain to me why this code give the output in backwards...
its that i need a mirror to invert it. :rolleyes:

#include<iostream>

Using name space std;


void print_backwards();


int main()

{

	 print_backwards();

	 cout << “\n”;


return 0;

}


void print_backwards()

{

char character;


cout << “Enter a character (‘.’ to end program): “;

cin >> character;

if (character != ‘.’)

{

		    print_backwards();

		    cout << character;

	}

}



#2
julmuri

julmuri

    Programmer

  • Members
  • PipPipPipPip
  • 139 posts
Its simple if you think about it.

That function is recursive.
istream >> ( char ) only takes one char at the time,
so anytime you enter a char that is not dot recursion happens
and the inputted charecter stays on the stack.
When you do input the dot the recursion ends and starts to return backwards.


void f( const int i )

{

	if ( i < 10 )

		// if smaller than 10

		// ...

	{

		f( i + 1 );

		// pass incremented i as arg exp

		// this will execute before we get to next block

		// so first called f will execute last and last called

		// f( i >= 10 ) will execute first


		std::cout << i << std::endl;

	} // if

}

int main( int argc, char* argv[] )

{

	f( 0 );


	return 0;

}


"Output" said:

9
8
7
6
5
4
3
2
1
0

Dont know if that explains it well, but it should be easy to figure out if you think about it procedurally.

#3
noteeth

noteeth

    Newbie

  • Members
  • PipPip
  • 21 posts
owh..like that...i will understand it..tq :)

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
What happens is this:
You enter 0123456789.
print_backwards reads '0' and calls print_backwards
  print_backwards reads '1' and calls print_backwards
    print_backwards reads '2' and calls print_backwards
      ...
    print_backwards prints '2' and returns
  print_backwards prints '1' and returns
print_backwards prints '0' and returns

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
noteeth

noteeth

    Newbie

  • Members
  • PipPip
  • 21 posts
tq...i really understand about the program flow.