1

I am starting with test(2,8)

I think the output should be 4 7 Instead I am getting 6 6 4 7 since p1 = p2 i.e. 6 = 6 the cout statement should not be performed. Why am I seeing the 6 6 ?

 using namespace std;

 void test(int p1, int p2);

  void  main()
  {
     test(2, 8);
     return ;
   }


  void  test(int p1, int p2)
  {
   if (p1 != p2)
   {
    p1 = p1 + 2;
    p2 = p2 - 1;
    test(p1, p2);
    cout << p1;
    cout << p2;
   }
  }
2
  • 2
    6 6 4 7 is correct , I guess you are not getting the recursive flow of the code Commented Mar 4, 2015 at 2:51
  • 1
    Your recursive call to test(p1, p2) is occurring before your cout << p1 and count << p2 that you think might be outputting 4 7. Commented Mar 4, 2015 at 2:52

1 Answer 1

3

In first call to test p1 becomes 4 and p2 becomes 7. But before printing we again go into recursion , this time p1 becomes 6 and p2 also becomes 6. We again call recursion but as p1 is same as p2 it returns without printing anything ( does not enter if condition ). Then it prints 6 6 and when it returns to the most above level call to test function it prints 4 7. So output is 6 6 4 7.

Sign up to request clarification or add additional context in comments.

3 Comments

What is confusing me is the cout is in the IF statement, so since 6 = 6 how is the cout being executed?
@Herbie 4 7 is printed from within the if ( 2 != 8 ), and 6 6 is printed from within the if ( 4 != 7 )
as @MattMcNabb said 6,6 is printed when arguments 4 , 7 are passed to test

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.