what does this code do

closed account (NbMiz8AR)
what does this code do and i want to know why using the % sysmbol is appropritate here. thank you for helping

int fib[] = {0,1,1};
for(int i=2; i<=n; i++)
{
fib[i%3] = fib[(i-1)%3] + fib[(i-2)%3];
}
return fib[n%3];
Last edited on
It seems that it is a calculation of Fibonacci numbers. Operator % is used to determine the index of the next element.

You have three elements in the array. Their indexes are 0, 1 and 2. So for any given number n you can get an index in the range [0, 2] by applying operator %.
Last edited on
OP for ref:

what does this code do and i want to know why using the % sysmbol is appropritate here. thank you for helping

int fib[] = {0,1,1};
for(int i=2; i<=n; i++)
{
fib[i%3] = fib[(i-1)%3] + fib[(i-2)%3];
}
return fib[n%3];
Topic archived. No new replies allowed.