Exercises: 1. Fibonacci Numbers
Exercises: 1. Fibonacci Numbers
Exercises
1. Fibonacci numbers
Write a function that prints the first N numbers of Fibonacci sequence (where each number is the sum f the two
previous numbers: 1,1,2,3,5,8,13,21...), with N defined at the beginning of main().
2. Numbers
Given an array of N integer numbers let calculate different results:
1. Counting how many positive, negative numbers are in the array, and how many 0 values;
2. Print if sequence is increasing, decreasing or neither increasing nor decreasing.
Note: a sequence of numbers is increasing iff for each couple of consecutive numbers X[i] and X[i+1] the following
condition holds: X[i] < X[i+1] .
3. Figures
Write a program that given a number 'n' defined in method main() :
1. - visualizes a full square of asterisks large 'n' chars (see case 1 with n = 5)
2. - visualizes an empty square (see case 2 with n = 5)
3. - visualzies a triangle (see case 3 with n = 5)
Case 1
Case 2
Case 3
*****
*****
*****
*****
*****
*****
*
*
*
*
*
*
*****
*
**
***
****
*****
file:///E|/4.Teaching/AdvancedProgramming/work/2009/Week1-code/Ex1.htm[2013/9/11 20:06:25]
#include <stdio.h>
#include <stdlib.h>
/* fibonacci with iteration */
void fibonacci(int n) {
int p1=0, p2=1, p=1, i;
for (i=1; i<=n; i++) {
printf("%d ", p);
p = p1+p2;
p1 = p2; p2=p;
}
}
/* fibonacci with recursion */
int cont= 0, N = 10;
void fibonacci_rec(int a, int b) {
if (cont<N) {
printf("%d ", b);
cont++;
fibonacci_rec(b, a+b);
}
}
/* recursive function which returns
the n-th element of Fibonacci sequence */
long fib(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
// stopping cases
// recursive case
return fib(n - 1) + fib(n - 2);
}
int main(int argc, char *argv[])
{
/* fibonacci with iteration */
printf("fibonacci with iteration:\n");
fibonacci(15);
printf("\n\n");
/* fibonacci with recursion */
if (N>0) printf("1 ");
printf("fibonacci with recursion:\n");
fibonacci_rec(1, 1);
printf("\n");
printf("\n %d\n", fib(2));
system("PAUSE");
return 0;
}