I'm having problems with using a function within a function (i think it's called recursivity or recursion or something). Can anyone (preferably a COMP125 or greater student) have a look at my code and tell me what the problem is? I don't get any errors in compiling, but when i execute, after i input, the program calculates for half a sec, then just closes. Anyway here's the code:
#include <iostream.h>
#include <stdlib.h>
using namespace std;
int sdl(int a)
{
int dig1, dig2, r;
dig1=a/10;
dig2=a%10;
r=dig1*dig1+dig2*dig2;
if(r==1||r==4)
return (r);
else
return sdl(r);
}
int main()
{int n;
cin>>n;
cout<<sdl(n)<<endl;
Thanks for any help.
system("PAUSE");
return 0;
}
edit: i should probably tell you what i want it to do. A 2-digit number is inputted, and the program should separate the number up and square the two numbers, then sum them. This process should then be applied to the resulting value. (i.e. 14 is broken into 1 and 4, then 1^2+4^2=17, then 17 --> 1 and 7 --> 1^2+7^2=50 and so on.)
#include <iostream.h>
#include <stdlib.h>
using namespace std;
int sdl(int a)
{
int dig1, dig2, r;
dig1=a/10;
dig2=a%10;
r=dig1*dig1+dig2*dig2;
if(r==1||r==4)
return (r);
else
return sdl(r);
}
int main()
{int n;
cin>>n;
cout<<sdl(n)<<endl;
Thanks for any help.
system("PAUSE");
return 0;
}
edit: i should probably tell you what i want it to do. A 2-digit number is inputted, and the program should separate the number up and square the two numbers, then sum them. This process should then be applied to the resulting value. (i.e. 14 is broken into 1 and 4, then 1^2+4^2=17, then 17 --> 1 and 7 --> 1^2+7^2=50 and so on.)
Last edited: