Reputation: 65
Today I was trying to do recursion with multiple functions and I was using some function and in that I was using a function which is declared below it
Here is my code :
#include<bits/stdc++.h>
using namespace std;
#define MOD 10
int f(int x){
if(x == 4) return 1;
return 3*f(((2*x+2)%11)-1);
}
int q(int x){
if(x == 7) return 1;
return f(x) + q((3*x)%MOD);
}
int g(int x){
if(x == 0) return 1;
return (g(x-1)+f(g(x-1)) + f(x-1) + h(x-1))%MOD;
}
int h(int x){
if(x == 0) return 1;
return (2*h(x-1) + g(x-1) + q(f(x-1)%10))%MOD;
}
int main() {
cout << g(4);
return 0;
}
The error is that in the function g(x)
, it is accessing h(x)
which is declared below and h(x)
function is using g(x)
function so not able to do anything
Please let me know what should I do to make this work.
Thanks a lot.
Upvotes: 1
Views: 886
Reputation: 3001
So you are seeing the problem that a function is defined after you used it, so your compiler can't see it. This "problem" is solved with a declaration of the function and then later to define it. In your case you could declare all functions above main and then define(implement it) after main:
#include <iostream>
using namespace std;
#define MOD 10
// declaration ***
int f(int x);
int q(int x);
int g(int x);
int h(int x);
// **************
// main ***
int main() {
cout << g(4);
return 0;
}
// **************
// definition ***
int f(int x){
if(x == 4) return 1;
return 3*f(((2*x+2)%11)-1);
}
int q(int x){
if(x == 7) return 1;
return f(x) + q((3*x)%MOD);
}
int g(int x){
if(x == 0) return 1;
return (g(x-1)+f(g(x-1)) + f(x-1) + h(x-1))%MOD;
}
int h(int x){
if(x == 0) return 1;
return (2*h(x-1) + g(x-1) + q(f(x-1)%10))%MOD;
}
// **************
Also do not include #include bits/stdc++.h
Upvotes: 4
Reputation: 78
You need to add a forward declaration of function h in order for your code to compile, something like:
#define MOD 10
int f(int x){
if(x == 4) return 1;
return 3*f(((2*x+2)%11)-1);
}
int h(int); // add this line and you will be alright! ;)
int q(int x){
if(x == 7) return 1;
return f(x) + q((3*x)%MOD);
}
...
Generally you can find out why this is needed here.
Upvotes: 1
Reputation: 32202
Declare your functions first.
#include<bits/stdc++.h>
#define MOD 10
// declaring your functions here makes sure that you can
// use them before they are fully defined.
int f(int x);
int q(int x);
int g(int x);
int h(int x);
// Now here below you can use the functions declared above
// at any place you wish.
int f(int x){
if(x == 4) return 1;
return 3*f(((2*x+2)%11)-1);
}
int q(int x){
if(x == 7) return 1;
return f(x) + q((3*x)%MOD);
}
int g(int x){
if(x == 0) return 1;
return (g(x-1)+f(g(x-1)) + f(x-1) + h(x-1))%MOD;
}
int h(int x){
if(x == 0) return 1;
return (2*h(x-1) + g(x-1) + q(f(x-1)%10))%MOD;
}
int main() {
std::cout << g(4);
return 0;
}
Upvotes: 1