Week 10 Extra Sample Solutions

Information

  • This page contains extra exercises for week 10.
  • These exercises are not compulsory, nor do they provide any marks in the course.
  • You cannot submit any of these exercises, however autotests are available for them (Command included at bottom of each exercise).

Exercise
(●◌◌)
:

Overflow

INTERNAL ERROR MISSING SOURCE FILE: activities/overflow/index.md

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest overflow

Exercise
(●●◌)
:

Command Line Words

INTERNAL ERROR MISSING SOURCE FILE: activities/command_line_words/index.md

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest command_line_words
Sample solution for command_line_words.c
//
// Program to count to total number of words in the command line arguments.
// Separate arguments can contain multiple words!
//
// Written by Rory Golledge (z5308772) on 25-03-2022
//

#include <stdio.h>

#define FALSE 0
#define TRUE 1

int main(int argc, char *argv[]) {
    int total_words = 0;

    int arg_index = 1;

    // Loops for each argument
    while (arg_index < argc) {
        int letter_index = 0;

        int expecting_space = FALSE;
        // Loops for each character in the current argument
        while (argv[arg_index][letter_index] != '\0') {
            // Word is found if a space is found and a space is expected
            if (argv[arg_index][letter_index] == ' ' && expecting_space) {
                total_words++;
                expecting_space = FALSE;
            // When a non-space is found, we are in a word, hence we are
            // now expecting a space to complete the word
            } else if (argv[arg_index][letter_index] != ' ') {
                expecting_space = TRUE;
            }

            letter_index++;
        }

        // Standard case when there is no space at end of argument, as a word
        // still needs to be added
        if (expecting_space) {
            total_words++;
        }

        arg_index++;
    }

    // Print out final results
    printf(
        "There are %d command line arguments (Excluding program)!\n", argc - 1
    );
    printf("There were %d total words!\n", total_words);
}

Exercise
(●●●)
:

Valid C Brackets

INTERNAL ERROR MISSING SOURCE FILE: activities/valid_c_brackets/index.md

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest valid_c_brackets