PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] Why output change when i change cout position after decrementing my function?

 August 18, 2022     c++, output, recursion     No comments   

Issue

Here is my code :

#include<iostream>
int x;
void gad(int x)
{
  if(x==0)
      return;
  else{

  std::cout<<"geek"<<" ";
  std::cout<<"for geeks ";

   gad(x-1);
  }
}
int main()
{
  gad(3);
  return 0;
}

The output is this

geek for geeks geek for geeks geek for geeks

Now if the change the position of 2nd std::cout From

std::cout<<"geek"<<" ";
  std::cout<<"for geeks ";

   gad(x-1);

to

   std::cout<<"geek"<<" ";
   gad(x-1);
   std::cout<<"for geeks ";

The output that came is this

geek geek geek for geeks for geeks for geeks

My question is why changing the position of std::cout changes the output like that?

I thought if I put cout after the function, due to recursion it won't give "for geeks" and come out of the recursive loop due to the if statement.


Solution

You're printing the first sentence, then going into a recursive call to the same function which will, in return, print the first sentence and go to another recursive call...etc. After the last function returns, it will continue with x=1 to print the second sentence...etc. To visualize what happens, this will be the call stack:

x=3 ---> print first statement

x=2 ---> print first statement

x=1 ---> print first statement

x=0 ---> return

x=1 ---> continue to print second statement and terminate

x=2 ---> continue to print second statement and terminate

x=3 ---> continue to print second statement and terminate



Answered By - Mohammed Deifallah
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing