COMP1511 17s1 Code Examples from Lectures on functions Introduction to Programming

Simplelecture example of using functions

#include <stdio.h>

void printManyMessages(int n);
void printMessages();

int main(int argc, char *argv[]) {
    int n;
    printManyMessages(1);
    printf("Repeat this how many times? ");
    scanf("%d", &n);
    printManyMessages(n);
    return 0;
}

void printManyMessages(int n) {
    while (n > 0) {
        printMessages();
        n = n - 1;
    }
}


void printMessages(void) {
    printf("C is good.\n");
    printf("C is great.\n");
    printf("We all love C.\n");
}

Simple example illustrating call by value

#include <stdio.h>

int f(int x) {
    int y;
    // these assignments will have no effect on variables
    // outside the function
    x = x + 1;
    y = 3;
    return x * y;
}

int main(int argc, char *argv[]) {
    int  x, y , z;
    x = 1;
    y = 2;
    z = f(y);
    // note the variables x & y are local to main
    // and are not changed by assignment to variables
    // of the same name in f
    printf("x=%d y=%d z=%d\n", x, y, z);
    return 0;
}

Simple example illustrating passing an array to a function

#include <stdio.h>

// passing an array to a function is equivalent to passing a pointer
// to its first element so changes to the array in the function
// will be visible outside the function

// note the array size does not need to be specified
// for an array  parameter
// but the function needs to know the array size
// so it is passed as a separate parameter

void exponentiate(double x, double powers[], int len) {
    int i;
    double power;
    power = 1;
    i = 0;
    while (i < len) {
        powers[i] = power;
        power = power * x;
        i = i + 1;
    }
}

#define ARRAY_SIZE 10

int main(void) {
    int i;
    double powerArray[ARRAY_SIZE];

    exponentiate(42, powerArray, ARRAY_SIZE);
    i = 0;
    while (i < ARRAY_SIZE) {
        printf("42^%d = %lf\n", i, powerArray[i]);
        i = i + 1;
    }

    return 0;
}

Simple recursive calculation of factorials & fibonacci numbers http://en.wikipedia.org/wiki/Factorial http://en.wikipedia.org/wiki/Fibonacci_number

Fibonacci calculation is very inefficient

#include <stdio.h>
#include <stdlib.h>

int fibonacci(int n) {
     if (n < 2) {
        return 1;
     }
     return fibonacci(n - 1) + fibonacci(n-2);
}

int factorial(int n) {
     if (n < 2) {
        return 1;
     }
     return n * factorial(n - 1);
}

int main(void) {
    int i = 1;
    while (i < 13) {
        printf("factorial(%d) = %d\n", i, factorial(i));
        printf("fibonacci(%d) = %d\n", i, fibonacci(i));
        i = i + 1;
    }
    return 0;
}