Week 05 Tutorial Sample Answers

Arrays Practice

This week, we will discuss arrays, and complete a program to practice writing arrays.

Diagram of an array

Tutor Demo! (10 mins)

We have been provided the following program that intends to do the following steps but has some flaws.

Flowchart of activity

// part1_arrays.c, odd_only
//
// Written by YOUR-NAME (YOUR-ZID)
// on TODAYS-DATE 
//
// This program adds 1 to any odd element in an array and after prints 
// all elements in the array

#include <stdio.h>

#define SIZE 5

int main(void) {

    int array = {1, 2, 3, 4, 5};

    int i = 0;
    while (i < SIZE) {
        if (array.i % 2 == 0) {
            array.i += 1;
        }
    }

    int j = 1;
    while (j < SIZE) {
        printf("%c ", array.j);
    }

    printf("\n");

    return 0;
}

We will go through and debug the program so it executes as expected.

Ask students what an array is, briefly outline it's purpose and why we might use one. Draw an integer array on the whiteboard (similar to the one above), and explain what each component is. Show the flowchart describing what the program should do. Debug the program provided so than it performs as expected. While debugging show a few different debugging techniques: - Using printf to see what is happening at different points of the program - Reading dcc output and interpreting it - Utilising dcc-help - Utilising dcc-sidekick Solution below:
// part1_arrays, even_only
//
// Written by Sofia De Bellis, z5418801
// on March 2024
//
// This program adds 1 to any odd values in an array

#include <stdio.h>

#define SIZE 5

int main(void) {

    int array[SIZE] = {1, 2, 3, 4, 5};

    int i = 0;
    while (i < SIZE) {
        if (array[i] % 2 == 1) {
            array[i] += 1;
        }
        i++;
    }

    int j = 0;
    while (j < SIZE) {
        printf("%d ", array[j]);
        j++;
    }

    printf("\n");

    return 0;
}

Your turn!

Copy Array

Voice of the Student

✨ Help Us Improve Your Learning Experience ✨

Your feedback helps us understand what’s working well and what might need improvement. This quick, anonymous check-in has just two questions and takes less than a minute to complete.

Please answer honestly — your input makes a real difference.