patterncMinor
Iterative Fibonacci sequence
Viewed 0 times
sequencefibonacciiterative
Problem
I implemented a function that prints all the numbers from the Fibonacci sequence until
max_num. The minimum value allowed is 0 (so, fib(0) prints 1). It works until 92, and I want to know how to improve the code, in general.void fib(unsigned int max_num)
{
unsigned long fib_num = 1;
unsigned long fib_temp = 0;
size_t count = 0;
if (max_num < 0)
{
fprintf(stderr, "Please, enter a non-negative number\n");
return;
}
for (; count <= max_num; count++)
{
printf("%lu\n", fib_num);
fib_num += fib_temp;
fib_temp = fib_num - fib_temp;
}
}Solution
Consider documenting this function with something like doxygen. At a quick glance, your function can be interpreted two different ways: Print out
will never happen. (Try calling
(Optional) Put
fib(0), fib(1), ..., or print out all Fibonacci numbers less than or equal to max_num. Documentation will clarify that.max_num will never be negative. It is defined as an unsigned int, which means it can never hold a negative value. So this:if (max_num < 0)
{
fprintf(stderr, "Please, enter a non-negative number\n");
return;
}will never happen. (Try calling
fib(-2), see what happens)(Optional) Put
size_t count = 0 inside the loop if you can? (You may have to add -std=c99 or something like that to make it work)for (size_t count = 0; count <= max_num; count++)
{
printf("%lu\n", fib_num);
fib_num += fib_temp;
fib_temp = fib_num - fib_temp;
}Code Snippets
if (max_num < 0)
{
fprintf(stderr, "Please, enter a non-negative number\n");
return;
}for (size_t count = 0; count <= max_num; count++)
{
printf("%lu\n", fib_num);
fib_num += fib_temp;
fib_temp = fib_num - fib_temp;
}Context
StackExchange Code Review Q#139400, answer score: 6
Revisions (0)
No revisions yet.