COMP1511 19T2
COMP1511 19T2
  1. The tutorial will start with a code review.

    Your tutor has asked a lab pair to present their week 3 work.

    Discuss the good, the bad and the ugly aspects of their code.

    Please be gentle in any criticism - we are all learning!

  2. What is CS Paint and how does it draw to a canvas?
  3. How does CS Paint store a canvas and how can you access a single pixel?
    It's a two dimensional array of integers. You access a pixel by using its row coordinate as the first index and then its column coordinate as the second. Eg: canvas[row][column].
  4. Draw a 2D grid on a piece of paper or the whiteboard and decide which cells would be coloured in CS Paint with the following commands:
    • 1 1 1 1 6
    • 2 2 2 5 4
      Remember with these questions that the top left corner is 0,0 and that coordinates are given as row,column pairs rather than x,y coordinates. A horizontal line from 1,1 to 1,6 A rectangle between 2,2 and 5,4
  5. Discuss the errors in these while loops
    int i;
    
    while (i < 100) {
        printf("%d\n", i);
        i = i + 1;
    }
    
    Explanation of error: i is not initialized. dcc should warn you about this (or gcc -O -Wall if you are using gcc on your own machine).
    int i = 0;
    int j = 0;
    
    while (j = 1 || i < 100) {
        printf("%d\n", i);
        i = i + 1;
    }
    
    Explanation of error: j = 1 is an assignment statement, not a comparison.

    dcc should warn you about accidental uses of assignment in if/while conditions.

    int i = 0;
    int n = 10;
    while (i < n) {
        printf("%d\n", i);
        n = n + i;
        i = i + 1;
    }
    
    Explanation of error: loop does not terminate because the assignment n = n + i results in n growing faster than i.
    int i = 0;
    while (i < 10)
        printf("%d\n", i);
        i = i + 1;
    
    Explanation of error: missing braces mean the update statement, i = i + 1, is not part of the loop regardless of the indentation, and the loop is an infinite loop.
  6. What is an array?
    An array is a collection of elements with the same data type. Each element is accessed providing the name of the array and an index. The index range is from 0 through to N-1, where N is the number of elements in the array. This is also known as zero-based indexing.
  7. Give an expression that sums the first and third element of an array called numbers
    numbers[0] + numbers[2]
    Note third element is accessed using numbers[2] since C uses zero based indexing.
  8. If an array is declared as int numbers[20]; and your program assigns a value to each element in the array, what is the problem with the statement x = numbers[20]; ?
    Because arrays use zero-based indexing, accessing the element indexed 20 is accessing the 21st item in the array. This will access a value that is not within the boundaries of the array.

    Behaviour of a program that does this is undefined and it is possible, for example, that it will cause the program to terminate. Sometimes it will retrieve the value of another variable.

  9. How would you declare a variable squares to be an array of integers with 15 elements?
        int squares[15];
    

    Write a C code fragment to store, in each element of this array, the square of the index of that element, e.g., squares[5] would contain the value 25.

    Here is a complete program instead of a fragment.
    #include <stdio.h>
    
    #define ELEMENTS    15
    
    int main(void) {
        int squares[ELEMENTS];
    
        int i = 0;
        while (i < ELEMENTS) {
            squares[i] = i * i;
            i = i + 1;
        }
    
        i = 0;
        while (i < ELEMENTS) {
            printf("squares[%d] has the value %d\n", i, squares[i]);
            i = i + 1;
        }
        return 0;
    }
    
    
  10. Your lab partner worked too late last night and wrote some unusual C statements:
    #include <stdio.h>
    
    int main(void) {
        printf("%d\n", 13 < 42);
        printf("%d\n", 13 < 42 || 42 > 50);
        printf("%d\n", 13 < 42 && 42 > 50);
        printf("%d\n", 13 && 42);
        printf("%d\n", 13 || 42);
        return 0;
    }
    
    
    Obviously your partner's code has to be completely rewritten, but first figure out what it will print and why?
    It prints:
    1
    1
    0
    1
    1
    
    Remember C logical and comparison operators actually return an int, 0 for false, 1 for true.

    Revision questions

    The remaining tutorial questions are primarily intended for revision - either this week or later in session.

    Your tutor may still choose to cover some of the questions time permitting.

  11. Write a program that reads in an integer and prints out that many asterisks, each on a new line.
    ./asterisks
    Please enter an integer: 5
    *
    *
    *
    *
    *
    
    Sample solution for asterisks.c
    #include <stdio.h>
    
    int main(void) {
        int i, n;
    
        printf("Please enter an integer: ");
        scanf("%d", &n);
    
        i = 0;
        while (i < n) {
            printf("*\n");
            i = i + 1;
        }
    
        return 0;
    }
    
    
  12. Consider the following program square.c
    #include <stdio.h>
    
    int main(void) {
        int number;
        int row, column;
    
        // Obtain input
        printf("Enter size: ");
        scanf("%d", &number);
    
        row = 1;
        while (row <= number) {
            column = 1;
            while (column <= number) {
                printf("*");
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
    
        return 0;
    }
    
    
    The output if the user types in the number 5 is:
     ./square
    Enter size: 5
    *****
    *****
    *****
    *****
    *****
    
    Modify the program so that it prints out a triangle like this:
     ./triangle
    Enter number: 5
    ----*
    ---**
    --***
    -****
    *****
    

    Sample solution for triangle.c
    // Written 14/3/2017 by Andrew Taylor (andrewt@unsw.edu.au)
    // as a lab example for COMP1511
    
    // Print an nxn "triangle" pattern of asterisks and dashes
    //
    // For example here is the output for n == 9
    //
    // --------*
    // -------**
    // ------***
    // -----****
    // ----*****
    // ---******
    // --*******
    // -********
    // *********
    
    #include <stdio.h>
    
    int main(void) {
        int size, n_numbers_read;
        int row, column;
    
        printf("Enter size: ");
        n_numbers_read = scanf("%d", &size);
    
        if (n_numbers_read != 1) {
            // scanf failed to read a number
            return 1;
        }
    
        row = 0;
        while (row < size) {
            column = 0;
            while (column < size) {
                if (column > size - row - 2) {
                    printf("*");
                } else {
                    printf("-");
                }
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
    
        return 0;
    }
    
    
    Now modify so it prints the following pattern:
    ./diagonal
    Enter an integer: 10
    *---------
    -*--------
    --*-------
    ---*------
    ----*-----
    -----*----
    ------*---
    -------*--
    --------*-
    ---------*
    
    Sample solution for diagonal.c
    // Written 14/3/2017 by Andrew Taylor (andrewt@unsw.edu.au)
    // as a lab example for COMP1511
    
    // Print an nxn "diagonal" pattern of asterisks and dashes
    //
    // For example here is the output for n == 9
    //
    // *--------
    // -*-------
    // --*------
    // ---*-----
    // ----*----
    // -----*---
    // ------*--
    // -------*-
    // --------*
    
    #include <stdio.h>
    
    int main(void) {
        int size, n_numbers_read;
        int row, column;
    
        printf("Enter size: ");
        n_numbers_read = scanf("%d", &size);
    
        if (n_numbers_read != 1) {
            // scanf failed to read a number
            return 1;
        }
    
        row = 0;
        while (row < size) {
            column = 0;
            while (column < size) {
                if (row == column) {
                    printf("*");
                } else {
                    printf("-");
                }
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
    
        return 0;
    }
    
    
    Now modify so it prints the following pattern:
    ./bars
    Enter an integer: 9
    -*-*-*-*-
    -*-*-*-*-
    -*-*-*-*-
    -*-*-*-*-
    -*-*-*-*-
    -*-*-*-*-
    -*-*-*-*-
    -*-*-*-*-
    -*-*-*-*-
    
    Sample solution for bars.c
    // Written 14/3/2017 by Andrew Taylor (andrewt@unsw.edu.au)
    // as a lab example for COMP1511
    
    // Print an nxn "bars" pattern of asterisks and spaces
    //
    // For example here is the output for n == 9
    //
    // -*-*-*-*-
    // -*-*-*-*-
    // -*-*-*-*-
    // -*-*-*-*-
    // -*-*-*-*-
    // -*-*-*-*-
    // -*-*-*-*-
    // -*-*-*-*-
    // -*-*-*-*-
    
    #include <stdio.h>
    
    int main(void) {
        int size, n_numbers_read;
        int row, column;
    
        printf("Enter size: ");
        n_numbers_read = scanf("%d", &size);
    
        if (n_numbers_read != 1) {
            // scanf failed to read a number
            return 1;
        }
    
        if (size < 5 || size % 2 != 1) {
            printf("Error: size has to be odd and >= 5.\n");
            return 1;
        }
    
        row = 0;
        while (row < size) {
            column = 0;
            while (column < size) {
                if (column % 2 == 1) {
                    printf("*");
                } else {
                    printf("-");
                }
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
    
        return 0;
    }
    
    
  13. Write a program that reads two integers (height x length) and prints a rectangular, asterisk outline with the specified dimensions, for example:
    ./rectangle
    Enter rectangle height and length: 3 5
    *****
    *   *
    *****
    
    Sample solution for rectangle.c
    #include <stdio.h>
    
    int main(void) {
        int height, length;
        int row, column;
    
        printf("Enter rectangle height and length: ");
        scanf("%d", &height);
        scanf("%d", &length);
    
        row = 0;
        while (row < height) {
            column = 0;
            while (column < length) {
    
                // If the index is on one of the edges, print *.
                // Otherwise, print a space.
                if (row == 0 || row == height - 1 || column == 0 ||
                    column == length - 1) {
                    printf("*");
                } else {
                    printf(" ");
                }
    
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
        return 0;
    }
    
    

  14. For the program above consider and discuss the ways in which you would test their correct behaviour. Then extend the program to include error checking for, and handling of, invalid input.
    Sample solution for rectangle1.c
    #include <stdio.h>
    
    int main(void) {
        int height, length;
        int row, column;
        int values_read;
    
        printf("Enter rectangle height and length: ");
        values_read = scanf("%d%d", &height, &length);
    
        if (values_read != 2) {
            printf("Two integers must be supplied as input.\n");
        } else if (height < 1 || length < 1) {
            printf("It is impossible to draw a rectangle with the given "
                   "height and length.\n");
        } else {
            row = 0;
            while (row < height) {
                column = 0;
                while (column < length) {
    
                    // If the index is on one of the edges, print *.
                    // Otherwise, print a space.
                    if (row == 0 || row == height - 1 || column == 0 ||
                        column == length - 1) {
                        printf("*");
                    } else {
                        printf(" ");
                    }
    
                    column = column + 1;
                }
                printf("\n");
                row = row + 1;
            }
        }
    
        return 0;
    }
    
    
  15. Design and write a program that reads an integer n and prints a diamond asterisk outline with side length n, for example:
    ./diamond
    Enter side length: 3
      *
     * *
    *   *
     * *
      *
    ./diamond
    Enter side length: 6
         *
        * *
       *   *
      *     *
     *       *
    *         *
     *       *
      *     *
       *   *
        * *
         *
    
    Sample solution for diamond.c
    #include <stdio.h>
    
    int main(void) {
        int side;
        int row, column;
    
        printf("Enter side length: ");
        scanf("%d", &side);
    
        row = 0;
        while (row < side * 2 - 1) {
            column = 0;
            while (column < side * 2 - 1) {
                if (row <= (side - 1)) {
                    if (column == (side - 1) - row ||
                        column == (side - 1) + row) {
                        printf("*");
                    } else {
                        printf(" ");
                    }
                } else {
                    if (column == row - (side - 1) ||
                        column == 3 * (side - 1) - row) {
                        printf("*");
                    } else {
                        printf(" ");
                    }
                }
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
        return 0;
    }
    
    
  16. Write a program that repeatedly reads in integers until a non-integer is read in and then prints the number of integers read in. For example:
    ./read_ints
    Please enter some integers:
    10 -90 100 999 78hello
    You entered 5 integers
    
    ./read_ints
    Please enter some integers:
    1 2 3 4 5 6 7 8 9
    10 11 12 hello
    You entered 12 integers
    
    Sample solution for read_until_non_integer.c
    #include <stdio.h>
    
    #define N 10
    
    int main(void) {
        int n, return_code;
        int count;
    
        printf("Please enter some integers:\n");
        count = 0;
        return_code = scanf("%d", &n);
        while (return_code == 1) {
            count = count + 1;
            return_code = scanf("%d", &n);
        }
        printf("You entered %d integers\n", count);
    
        return 0;
    }
    
    
  17. Write a program that reads in an integer n, and then prints a nxn multiplication table. For example:
    ./multiplication_table
    Enter multiplication table size: 5
     1|   1    2    3    4    5
     2|   2    4    6    8   10
     3|   3    6    9   12   15
     4|   4    8   12   16   20
     5|   5   10   15   20   25
    
    Sample solution for multiplication_table.c
    #include <stdio.h>
    
    int main(void) {
    
        int row = 1, col = 1;
        int table_size;
    
        printf("Enter multiplication table size: ");
        scanf("%d", &table_size);
    
        while (row <= table_size) {
            col = 1;
            while (col <= table_size) {
                if (col == 1) {
                    printf("%2d|", row);
                }
                printf("%4d ", row * col);
                col = col + 1;
            }
            printf("\n");
    
            row = row + 1;
        }
        return 0;
    }
    
  18. Write a program (a small game), which generates a random number for the program-user to guess. For example:
    ./guess_number
    Random number is between 1 and 100.
    Enter your guess: 50
    Random number is between 1 and 50.
    Enter your guess: 40
    Random number is between 1 and 40.
    Enter your guess: 37
    
    Yay, you guessed the number 37 correctly!
    
    
    ./guess_number
    Random number is between 1 and 100.
    Enter your guess: 80
    Random number is between 80 and 100.
    Enter your guess: 90
    Random number is between 80 and 90.
    Enter your guess: 85
    Random number is between 80 and 85.
    Enter your guess: 83
    Random number is between 80 and 83.
    Enter your guess: 82
    
    Yay, you guessed the number 82 correctly!
    
    Sample solution for guess_number.c
    // let a user guesses a random number 1..100 inclusive .
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define MAX 100
    
    int main(void) {
        int guess;
    
        // seed pseudo-random number generator with current time
        srand(time(NULL));
    
        // rand() returns a  pseudo-random number
    
        int random_number = 1 + rand() % MAX;
        int min = 1;
        int max = MAX;
    
        // set guess to an impossible value so loop will be entered
    
        guess = -1;
        while (guess != random_number) {
            printf("Random number is between %d and %d.\n", min, max);
            printf("Enter your guess: ");
    
            // we should check the scan succeeds here
            scanf("%d", &guess);
    
            if (guess > random_number && max > guess) {
                max = guess;
            }
            if (guess < random_number && min < guess) {
                min = guess;
            }
        }
    
        printf("\n_yay, you guessed the number %d correctly!\n\n", guess);
    
        return 0;
    }
    
    
  19. What does precedence of an operator mean? Make the precedence explicit in the following expressions by adding parentheses:
    1. 3 + 5 * 10 - 12
      ( ( 3 + (5 * 10) ) - 12 )
    2. a > 5 || b < 3
      ( (a > 5) || (b < 3) )
    3. a = b > c && b || d
      a = ( ( (b > c) && b ) || (d) )
    4. !a || a && c
      ( (!a) || (a && c) )

    Figuring this out can be a bit tedious and prone to errors. The moral? In complex expressions make your intention explicit by using parentheses.

    Note: The precedence rules of arithmetic operators in C follow the conventions used in mathematics.

  20. This is a revision question, to make the difference between if and while statements clear. Consider the two code snippets below, what will be the output after execution of each of the programs for input_num = 3.
    int input_num, i;
    
    printf("Enter a number: ");
    scanf("%d", &input_num);
    
    i = input_num;
    
    if (i <= 5) {
      printf("%d\n", i * i);
      i++;
    }
    
    
    int input_num, i;
    
    printf("Enter a number: ");
    scanf("%d", &input_num);
    
    i = input_num;
    
    while (i <= 5) {
      printf("%d\n", i * i);
      i++;
    }
    
    
    The output of the first program:
    9

    The output of the second program:
    9
    16
    25

    Therefore, remember the instructions in the if statements are executed just once, given the condition in the round brackets is true. Whereas, instructions can execute more than once in a while statement (hence the term loop, iteration, repetition...).