How to call a function only once in a recursive function? - c++

I would like to call a recursive function only once. I tried it as we do for a static variable but it is throwing an error. Can anybody suggest a solution?
Say I have function recur(int j):
void recur(int x){
if(x==0)
return;
//want x to be xth fibnocci number,but only at initialization.
x=fib(x);
cout<<x<<" ";
recur(x-1);
}
The output of recur(5) should be {5,4,3,2,1} and not {5,3,1}. I want to do it inside the function only.

Any time you want to have a variable start a certain way in function (whether it be recursive or not), you should handle this through the function arguments. The function is already set up to have an initialization stage.
Example:
void recur(int x){
if(x==0)
return;
cout<<x<<" ";
recur(x-1);
}
int main() {
recur(fib(x));
return 0;
}

Related

Why are my function parameters not matching up?

I have a function called generate_all_paths, defined as such:
template <int size>
void generate_all_paths(vector<string> maze[][size], int x, int y) {
....
}
I am trying to call it in my main function as so:
int main() {
string s;
ifstream mazefile("maze.txt");
if (!mazefile) {
cout << "File not found. Please try again." << endl;
}
while (getline(mazefile, s)) {
mazevec.push_back(s);
}
generate_all_paths(mazevec, 0, 1);
return 0;
}
where mazevec is vector<string> mazevec;
But my IDE says that my call to generate_all_paths in main does not match the function definition. I'm a little confused why this is happening. mazevec is a vector string, so shouldn't the parameter data types match up?
The mazevec you are passing to the function is a vector<string>. Your function definition indicates that it expects a 2D vector array. In your function prototype, change it to this:
void generate_all_paths(vector<string> maze, int x, int y);
This should work.
You'll have to pass an array but you have passed a variable that is not an array. So they are treated as two different functions.
Please pass an array of type vector and try again.

array of pointer to functions c++

Can someone tell me what is wrong with this code?!
visual studio tells the operand of * must be a pointer...
(in line that we call operation)...
can someone tell how exactly declaring an array of pointer to functions is?
I'm really confused.
#include<iostream>
#include<conio.h>
using namespace std;
int power(int x)
{
return(x*x);
}
int factorial(int x)
{
int fact=1;
while(x!=0)
fact*=x--;
return fact;
}
int multiply(int x)
{
return(x*2);
}
int log(int x)
{
int result=1;
while(x/2)
result++;
return result;
}
//The global array of pointer to functions
int(*choice_array[])(int)={power,factorial,multiply,log};
int operation(int x,int(*functocall)(int))
{
int res;
res=(*functocall)(x);
return res;
}
int main()
{
int choice,number;
cout<<"Please enter your choice : ";
cin>>choice;
cout<<"\nPlease enter your number : ";
cin>>number;
cout<<"\nThe result is :"<<operation(number,(*choice_array[choice](number)));
}
This call
operation(number, (*choice_array[choice](number)))
is invalid.
You have to supply a pointer to a function as second argument. Either write
operation(number, choice_array[choice] )
or
operation(number, *choice_array[choice] )
The problem is that (*choice_array[choice](number)) isn't a function itself but a result of function call.
Did you mean (*choice_array[choice])?
operation takes a function as argument, but (*choice_array[choice](number)) is an int, cuz it's applying choice-array[choice] to number
just do operation(number, choice_array[choice])
EDIT : don't want to say something wrong, but it seems to me that
*(choice_array[choice])
(choice_array[choice])
are the same, (meaning pointer to the function IS (can be used as a call to) the function, and you cant "dereference" it)

What's the difference between declaring functions before or after main()?

What's the difference between:
void function();
int main()
{......}
void function()
{......}
vs
void function()
{.......}
int main();
It seems odd to declare a function before main then define it after main when you could just declare and define it before main. Is it for aesthetic purposes? My teacher writes functions like the first example.
It's just for code organization purposes ("aesthetics", I guess). Without forward declarations you'd need to write every function before it's used, but you may want to write the bodies of a function in a different order for organizational purposes.
Using forward declarations also allows you to give a list of the functions defined in a file at the very top, without having to dig down through the implementations.
Forward declarations would also be necessary in the case of mutually recursive functions. Consider this (silly) example:
bool is_odd(int); // neccesary
bool is_even(int x) {
if (x == 0) {
return true;
} else {
return is_odd(x - 1);
}
}
bool is_odd(int x) {
return is_even(x - 1);
}
Note I mean to make this answer supplementary, others have already given good answers to this questions.
Note that knowing how to forward declare things in C++ becomes very important. Once you begin using header files it basically becomes mandatory. Header files will allow you to build a prototype of functions and classes/structs then define them in a corresponding .cpp file. This is a very important organizational feature of C++.
// MyClass.h
class MyClass
{
public:
MyClass(int x);
void printInt();
private:
int myInt;
};
// MyClass.cpp
MyClass::MyClass(int x)
{
MyClass::myInt = x;
}
void MyClass::printInt()
{
std::cout << MyClass::myInt;
}
Doing things this way makes it so you're not completely bound to make a huge hodgepodge of code. Especially if you're writing real programs that will have a considerably large amount of source code.
So while in the question you asked forward declaring is really just more of a preference, later on it really won't be a choice.
Your first example is in the Top-Down style, the second in Bottom-Up style.
It's largely aesthetic, in that some people prefer one over the other.
For example, someone might prefer to get a high-level overview of the program before getting the details (top-down), while another might person might prefer to see the details first (bottom-up).
A tangible benefit of the declarations in the top-down approach is that you can more easily re-organize the function definitions without having to worry about ordering.
Look at this example:
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
where, int max(int num1, int num2) is behaving as a function.
Now, here we have a program
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result:
Max value is : 200
Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value.

Max-heap implementation

Following code for max-heap implementation
#include<iostream>
#include<math.h>
using namespace std;
#define maxn 1000
int x[maxn];
int parent(int i){
return int(i/2);
}
int left(int i){
return 2*i;
}
int right(int i){
return 2*i+1;
}
void max_heap(int x[],int i,int size){
int largest;
int l=left(i);
int r=right(i);
if (l<=size && x[l]>x[i]){
largest=l;
}
else
{
largest=i;
}
if (r<=size && x[r]>x[largest]){
largest=r;
}
if (largest!=i) { int s=x[i];x[i]=x[largest];x[largest]=s;}
max_heap(x,largest,size);
}
int main(){
x[1]=16;
x[2]=4;
x[3]=10;
x[4]=14;
x[5]=7;
x[6]=9;
x[7]=3;
x[8]=2;
x[9]=8;
x[10]=1;
int size=10;
max_heap(x,2,size);
for (int i=1;i<=10;i++)
cout<<x[i]<<" ";
return 0;
}
When I run it, it writes such kind of warning:
1>c:\users\datuashvili\documents\visual studio 2010\projects\heap_property\heap_property\heap_property.cpp(36): warning C4717: 'max_heap' : recursive on all control paths, function will cause runtime stack overflow
Please tell me what is wrong?
The message tells you exactly what's wrong. You haven't implemented any checks to stop the recursion. One smart compiler.
max_heap function doesn't have base case, i.e., a return statement. You are just recursively calling the function but never saying when to break another successive call to the max_heap.
Also, in your example you are just calling the function with out satisfying any condition. Usually recursion is done or not done when a case is satisfied.
please tell me what is wrong?
Another problem that I see is that the size of your array x is 10. But the indices that you are using to set values are 1-10.
Put
max_heap(x,largest,size);
inside last check, like this:
if (largest!=i)
{
int s=x[i];
x[i]=x[largest];
x[largest]=s;
max_heap(x,largest,size);
}
and you're done!
There are many other problems with your code, but to answer your specific question, above change would do!

about return type from a function

Here I have written some code to get the square of a number from a function, but the return statement is not working as desired by me, it is giving me the same number which I have entered, I want to know the reason behind this, please if any one can explain this to me...
#include<iostream>
#include<conio.h>
using namespace std;
int square(int &i);
int main()
{
cout<<"enter the number whose square you want to find";
int a;
cin>>a;
square(a);
cout<<"the square of the number is"<<a;
_getch();
return 0;
}
int square(int &i)
{
return i*i;
}
You're ignoring the returned value. You should store it as:
int value = square(a);
cout<<"the square of the number is "<< value;
Also, as the type is just integral type, passing by reference doesn't give you much advantage. I would suggest to use pass by value for its readability sake:
int square(int i)
{
return i*i;
}
--
Or in case if you're experimeting with reference, and trying to learn it, then in that case I would say that you've to store the result of product in the argument itself, as:
int square(int &i)
{
i = i * i; //this updates i here, and at the call site as well
return i;
}
Or simply do this:
int square(int &i)
{
return i = i*i; //multiply, update, and return - all in one statement!
}
You do not obtain the result.
Your line should be:
a = square(a);
to fetch the result from the function.
The other possibility would be to write in the function
int square(int &i)
{
i = i * i;
return i;
}
The latter will alter the variable you passed to the function which justifies passing a reference.
To make it clear you want to alter the variable do something like:
void square(int &i)
{
i = i * i;
}
You see there is no return involved but it will alter the variables value.
You have a choice:
Modify the parameter you pass in, or
Return a value and assign it to something in the calling scope.
What you are doing in square is the second option. You seem to want the first.
If what you really want is to modify the passed-in value, then what you need is this:
void square(int &i)
{
i = i*i;
}
Either do it this way:
a = Square (a) ; // in main()
...
int Square (int i) // Pass by value -- doesn't change a in main
{
return i * i ;
}
or do it this way:
Square (a) ; // in main()
...
void Square (int& i) // Pass by reference -- changes a in main
{
i = i * i ; // No need for a return value
}
Make sure you understand the difference before you program anything else!
Judging by your comments on the answers, you've misunderstood what passing by reference does OR you've misunderstood return.
I'm assuming you're thinking that the variable i will be updated in your program. However, this is not the case. If you did something like...
i = i*i;
then yes, you would be correct. However, you did not assign any value to i, you simply multiplied it by itself and returned the result. Also, if you truly wanted to make this work based on a reference, there would be no need to return anything, as the variable would be updated via the reference.