Arrays

Content

We next focus on two things:

We also start to use header files instead of forward declaring external functions.

We consider

int
printf(const char *, ...);

int
main()
{
    int x[5];

    // init x
    for (int i=0; i<5; ++i) {
        x[i] = i+1;
    }

    // print x
    for (int i=0; i<5; ++i) {
        printf("%5d ", x[i]);
    }
    printf("\n");

    // sum elements of x
    int sum = 0;
    for (int i=0; i<5; ++i) {
        sum += x[i];
    }

    printf("sum = %d\n", sum);
}

Exercise

The above code does not use any functions. Extend the following code snippet for this purpose. Make meaningful declarations for function parameters (i.e. use const were appropriate):

int
printf(const char *, ...);

/* your code here */

int
main()
{
    int x[5];

    // init x
    init_array(5, x);

    // print x
    print_array(5, x);

    // sum elements of x
    int sum = sum_array(5, x);

    printf("sum = %d\n", sum);
}

Exercise

The array in the previous example is stored on the stack as it is defined locally. However, that requires that the array size is rather small. For some reason we do not want to define it as global variable (such that it would be stored in the data segment). Hence, we want to allocate memory dynamically. Extend the code snippet:

//int
//printf(const char *, ...);
#include <stdio.h>

//void *
//malloc(size_t size);
//
//void
//free(void *ptr);
#include <stdlib.h>

/* your code here */

int
main()
{
    unsigned int n = 5;

    /* your code here */

    // init x
    init_array(n, x);

    // print x
    print_array(n, x);

    // sum elements of x
    int sum = sum_array(n, x);

    printf("sum = %d\n", sum);

    /* your code here */
}