As part of a problem, I need to create a recursive function on a string.
Part of it is based on the nth element of Fibonacci.
The thing is that I need to get n ( the number of elements ) as an input, and only then I can create the array.
But I also need to create a recursive function that has to use the array.
I thought of adding the array to the function as a parameter but I'm not sure if that would decrease the function's efficiency.
So in case it would: Is there any way I can use that specific array in a function in c ?
I calculate the array like this:
#include <bits/stdc .h>
using namespace std;
char IOI(int n,int k) {
if (n<3) {
return n;
}
if (k<=fibo[n-2]) {
return IOI(n-2,k);
}
else {
return IOI(n-1,k-fibo[n-2]);
}
}
int main() {
int n,k;
cin >> n >> k;
int fibo[n 1];
fibo[0] = 0;
fibo[1] = 1;
for (int i = 2; i<n; i ) {
fibo[i] = fibo[i-1] fibo[i-2];
}
cout << IOI(n,k)
CodePudding user response:
Is there any way I can use that specific array in a function in c ?
Yes. Pass the array as an argument, using some form of indirection. Typically, this would be done using a parameter of type span.
cin >> n >> k; int fibo[n 1];
This isn't allowed. The size of an array variable must be compile time constant in C .
In order to use an array with dynamic size, the array must be allocated dynamically. The most convenient solution is to use std::vector.
CodePudding user response:
cin >> n >> k;
int * fibo = new int[n 1];
You can create array dynamically;
char IOI(int * fibo, int n,int k) {
...
}
And you can add the array as the function parameter.
