hey im trying to do a quick mod function, i know % exists but this will have other applications... Basically the main issues is when you return "num" it is a different value than if you look at num before it is returned...

Any ideas? thanks in advance

int mod(int num, int num2)
{
  if (num < num2)
    return num;
  mod(num-num2,num2);
}

Can you explain the problem more clearly? How/where are you looking at num?

Here is an example... why are num and ans not equal?

#include <iostream>
using namespace std;

int mod(int&,int&);

int main()
{
  int num = 2001,
      num2 = 5;
  int ans = mod(num,num2);
  cout << "The number returned by mod function = " << ans  << endl
       << "The number passed by num in mod function = " << num << endl
       << num << " != " << ans << endl;
  system("PAUSE");
  return 0;
}

int mod(int &num, int &num2)      
{
  if (num < num2)
    return num;
  num -= num2;
  mod(num,num2);
}

change :

int mod(int &num, int &num2)

to

int mod(int num, int num2)

So it works with the copy of num1 and num2 and not it indirectly.

2001 % 5 = 1 .... i was showing you that "num" was correct before returned... this has nothing to do with passing by reference... the returned number of function mod should be 1... not 923472947 << some random number. try running that code... you will see

Sorry, I still don't see what your problem is. You have changed the code but I'm not sure why. Originally your function signature was:

int mod(int num, int num2)

which is correct and in your example program returns the value 1.

But in post #3 you changed it to

int mod(int &num, int &num2)

This still runs correctly & returns the value 1, and it also modifies the value of the original argument num in the calling function. I just don't see why you would want to do that since you lose the original value apparently without gaining anything.

But either way, what is your question?

This article has been dead for over six months. Start a new discussion instead.