I've been learning more programming in the past few years (C, Java, Arduino) for my hobbies. I read the "C for Dummies" book and found that it was good, but did not cover much - especially pointers... One of my friends from college (CS major) suggested a simple program exercise to see if I could figure out how to use pointers. Well, I had to refer to a pdf of Ritchie's text "The C Programming Language" to learn about pointers. He asked me to make a program that returns the Fibonacci sequence. A month or so ago, I sent him my program, but he hasn't had time to review it since he is very busy with work these days. Basically what I am wondering about my program is if it is redundant or "too verbose" - basically is it written efficiently? IMO, as a hobbyist programmer, it works just fine.
Below is the source code file he initially sent to me:
/**
* @file fibonacci.cpp
*
* @brief Prints out a partial Fibonacci sequence.
*/
#include <stdio.h>
// Function prototype for fibonacci()
unsigned int Fibonacci(unsigned int);
int main(int argc, char** argv)
{
printf("Fibonacci Sequence:\n");
for (unsigned int n = 0; n < 10; ++n)
{
unsigned int fib = Fibonacci(n);
printf("%d ", fib);
}
return 0;
}
// Computes the Nth Fibonacci number.
unsigned int Fibonacci(unsigned int N)
{
// Actual implementation goes here!!
}
Below is my version of the program that I sent to him for review:
/**
* @file fibonacci.cpp
*
* @brief Prints out a partial Fibonacci sequence.
*/
#include <stdio.h>
unsigned int n;
char nMax[3]; //user input for sequence up to and including value @ this index
int Nmax;
// Function prototype for fibonacci()
unsigned int Fibonacci(unsigned int);
int main(int argc, char** argv)
{
printf("Please input the Nth index of the last sequence value.\n");
printf("Program will return entire Fibonacci Sequence up to and including Nth value.\n");
gets(nMax);
Nmax =atoi(nMax);
for (n = 0; n < Nmax; ++n)
{
unsigned int fib = Fibonacci(n);
printf("%d ", fib);
}
return 0;
}
// Computes the Nth Fibonacci number.
unsigned int Fibonacci(unsigned int n)
{
// Actual implementation goes here!!
unsigned int N; //function output value
//declare a temp array of sequence values
unsigned int tempseq[100];
// declare two ptrs
unsigned int *prev; //pointer to previous or (n-1) value in sequence
unsigned int *prevprev; //pointer to previous previous or (n-2) value in sequence
if (n==0)
{ N = 1; //1st seed value
tempseq[n] = N;
}
else if(n==1)
{
N = 1; //2nd seed value
tempseq[n] = N;
}
else
{
prev = &tempseq[n-1]; //prev ptr points to n-1 array element
prevprev = &tempseq[n-2]; //prevprev ptr points to n-2 array element
N = *prev + *prevprev; //fibonacci recurrence relation
tempseq[n] = N; //add current value of N to the temp array
}
return N;
}
EDIT: Not to step on the toes of JS1 who recently replied, but I wanted to add an image here of my cmd line execution of my fibonacci.exe program to show that at least on my pc, it seems to work....