Apr
13th
13th
I am in the process of learning to develop for the iPhone and of course the primary language is Objective-C.
One of my first assignments after an introduction to Objective-C was to create several console type apps. One of which was to display the first 20 values of the Fibonacci sequence.
I had no clue what Fibonacci was/is until Wikipedia explained it to me (see link). In the end, I was able to figure out the formula and put it in code.
The Code:
int i; // used in the "for" loop
int fcounter = 20; // specifies the number of values to loop through
int f1 = 1; // seed value 1
int f2 = 0; // seed value 2
int fn; // used as a holder for each new value in the loop
for (i=1; i<fcounter; i++){
fn = f1 + f2;
f1 = f2;
f2 = fn;
printf("%d: ", fn); // print each value of fn
}
The Answer:
1: 1: 2: 3: 5: 8: 13: 21: 34: 55: 89: 144: 233: 377: 610: 987: 1597: 2584: 4181:
Thanks for the simple code. By far, yours is the easiest to understand. I am trying to teach myself java, and in an assignment, the book asks to create a Fibonacci using for loop. I searched the web for clues, but was disappointed until I ran into your blog. Thanks for posting this.