Computer Systems Org I - Prof. Grishman

Lecture 15 - Oct. 27, 2004

C ... some differences from Java
functions
arrays
strings

Examples of C functions and arrays

Example 1:  a function with an integer parameter

#include <stdio.h>

void multiquack(int);

main () {
        int i, limit;
        limit = 0;
        printf("Enter an integer>");
        scanf("%d", &limit);
        printf("The integer is %d\n", limit);
        if (limit < 20)
                for (i=0; i<limit; i++)
                        printf ("i = %d\n", i);
        multiquack(5);
}

void multiquack (int i) {
        int j;
        for (j=0; j<i; j++)
                printf ("Quack.\n");
}

Example 2:  a function with an array parameter

#include <stdio.h>

int raysum (int[]);

main () {
        int ray[] = {1, 2, 3, 4, 5};
        int sum;
        sum = raysum(ray);
        printf ("Sum = %d", sum);
}

int raysum (int ray[5]) {
        int j;
        int sum = 0;
        for (j=0; j<10; j++)
                sum += ray[j];
        return sum;
}

Example 3:  a function with a string parameter

#include <stdio.h>

int ourstrlen (char[]);

main () {
        int len;
        char stg[10];
        printf ("Enter a string>");
        scanf ("%s", &stg);
        len = ourstrlen (stg);
        printf ("Length of %s = %d", stg, len);
}

int ourstrlen (char s[]) {
        int counter = 0;
        while (s[counter] != 0) counter++;
        return counter;
}