Programming in C

(Barry) #1
Defining an Array 103

As a point of discussion, you could have developed your program to use an array con-
taining precisely 10 elements.Then, when each response was keyed in by the user, you
could have instead incremented ratingCounters[response - 1].This way,
ratingCounters[0]would have contained the number of respondents who rated the
show a 1,ratingCounters[1]the number who rated the show a 2, and so on.This is a
perfectly fine approach.The only reason it was not used is because storing the number of
responses of value ninside ratingCounters[n]is a slightly more straightforward
approach.


Generating Fibonacci Numbers


Study Program 7.3, which generates a table of the first 15 Fibonaccinumbers, and try to
predict its output.What relationship exists between each number in the table?


Program 7.3 Generating Fibonacci Numbers


// Program to generate the first 15 Fibonacci numbers
#include <stdio.h>


int main (void)
{
int Fibonacci[15], i;


Fibonacci[0] = 0; // by definition
Fibonacci[1] = 1; // ditto

for ( i = 2; i < 15; ++i )
Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];

for ( i = 0; i < 15; ++i )
printf ("%i\n", Fibonacci[i]);

return 0;
}


Program 7.3 Output


0 1 1 2 3 5 8


13
21

Free download pdf