Week 07 Tutorial Questions

    Looking back on assignment 1

  1. Well done everyone for such a great effort in the first assignment.

    Take a moment to think about how you found the assignment, and what you learned in the process of working on it.

    If you could go back in time to the very start of the assignment, and give one piece of advice to your past self, what would you say?

    Marking will not have started on the assignment before your tutorial this week, but we expect to get most marks back to students by mid-week 9.

    You tutor will talk about how you will get feedback from the marking of assignment 1.

  2. Characters

  3. So far in this course we have learnt about two data types - int and double. What about a char variable? What is the size of this variable, and what possible values can it have? What do these values mean?

  4. Strings

  5. What is a string?

  6. What does the following function do?

    Can you explain the stopping case in the while loop? Why does it work and what is the significance of the '\0'?

    What does the char *word input mean? What's the relationship between an array and a pointer?

    int secret_function(char *word) {
        int i = 0;
        int result = 0;
        while (word[i] != '\0') {
            if (word[i] >= 'a' && word[i] <= 'z') {
                result++;
            }
            i++;
        }
        return result;
    }
    
  7. getchar() and putchar()

  8. So far in this course we have only used scanf and printf to scan input and print output in our programs.

    How do we use getchar and putchar? How does getchar signal to us that it has reached the end of the input?

    Why does getchar return an int instead of a char?

  9. Write a program sum_digits.c which reads characters from its input. When the end of input is reached it should print a count of the number of digits in its input and their sum.

    The only functions you can use are getchar() and printf().

    For example:

      ./sum_digits
      1 2 3 o'clock
      4 o'clock rock
      
      Input contained 4 digits which summed to 10
      ./sum_digits
      12 twelve 24 twenty four
      thirty six 36
      
      Input contained 6 digits which summed to 18
      
  10. fgets()

  11. How do we use fgets? What are the inputs given to fgets? How does fgets signal to us that it has reached the end of the input?

    When fgets scans in a line of text, will it include a '\n' at the end of the line? Is this always the case?

  12. Write a program echo_twice.c which reads lines from its input and prints them twice.

    The only functions you can use are fgets and printf. You can assume lines contain at most 4096 characters.

    For example:

        ./echo_twice
        My cat's breath smells like cat food.
        My cat's breath smells like cat food.
        My cat's breath smells like cat food.
        My eyes! The goggles do nothing!
        My eyes! The goggles do nothing!
        My eyes! The goggles do nothing!
        
        
  13. Command Line Arguments

  14. Another way your program can receive input is through command line arguments. How are command line arguments given to a program?

    What are argc and argv?

  15. If the following command were run, what would argc and argv contain?

        ./program these are command line arguments
    
    
  16. Testing

  17. Why is testing our code important? How can we test our code?

  18. The following code shows an add function that adds three numbers together. It also includes a test for the add function.

    • What should the test_add function do?
    • Complete the test_add function -- what does it output when you run the program?
    • Why would only testing for add(1,2,3); be a bad idea?
    // A program that tests adding three numbers
    // Written very badly by Tom Kunc 2020-10-25 (z5205060)
    // t.kunc@unsw.edu.au (please don't email me about this bad code)
    
    #include <stdio.h>
    
    #define MEETS_SPEC 1
    #define DOES_NOT_MEET_SPEC 0
    
    int add(int a, int b, int c);
    
    int test_add(void) {
        // TODO: Write tests for me!
        return MEETS_SPEC;
    }
    
    
    // This function returns the sum of a, b and c.
    int add(int a, int b, int c) {
        return a * b * c;
    }
    
    int main(void) {
        printf("Test whether `add` does the right thing: ");
        if (test_add() == MEETS_SPEC) {
            printf("MEETS SPEC\n");
        } else {
            printf("DOES NOT MEET SPEC\n");
        }
        return 0;
    }
    
  19. 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.

  20. #include <stdio.h>
    
    int main(void) {
        char str[10];
        str[0] = 'H';
        str[1] = 'i';
        printf("%s", str);
        return 0;
    }
    
    • What will happen when the above program is compiled and executed?

    • How do you correct the program?

  21. Write a program strip_comments.c which reads lines from its input and prints them after removing any C // style comments. In another words if the line contains // it does not print the // or anything after it.

    The only functions you can use are fgets and printf.

    You can assume lines contain at most 4096 characters.

    For example:

            ./strip_comments
                 x = x + 1;  // This means add one to the variable x
            x = x + 1;
            

    Also - is that a good comment to add to a C program?

  22. Write a program filter_empty_lines.c which reads lines from its input and prints them only if they contain a non-whitespace character.

    In another words remove lines are empty or contain only whitespace.

    The only functions you can use are fgets and printf.

    You can assume lines contain at most 4096 characters.

    You can assume there are only 3 white space characters, space, tab & newline.

    For example:

        ./filter_empty_lines
        full line
        full line
                 
        another no-empty line
        another no-empty line
        
  23. Write a C program reverse.c which reads lines and writes them out with the characters of each line in reverse order.

    It should stop when it reaches the end of input.

    For example:

        ./reverse
        The quick brown fox jumped over the lazy dog.
        .god yzal eht revo depmuj xof nworb kciuq ehT
        It was the best of times. It was the worst of times.
        .semit fo tsrow eht saw tI .semit fo tseb eht saw tI
        This is the last line.
        .enil tsal eht si sihT
        
        
  24. strlen is a function that returns the length of a string. Write your own C function to do the same.

    int myStrlen(char *string);
    
  25. Write a C function that is given two strings and returns 1 if they are both equal and 0 otherwise. This is a simplified version of strcmp, provided in the C library. Try writing one yourself.

    int myStrCmp(char *string1, char *string2);
    
  26. Write a C function that is given two strings and returns 1 if the first begins with the second (and 0 otherwise). For example, "APPLE" begins with "APP".

    int beginsWith(char *string1, char *string2);
    
  27. Write a C function that is given two strings and returns 1 if the first is a substring of the second (and 0 otherwise). For example, "APP", "E", "PL" are all substrings of "APPLE".

    int isSubstring(char *substring, char *string);
    
  28. Consider:

        char s[] = "Hello World!";
        char *cp = s;
        char *cp2 = &s[8];
        

    What is the output when the following statements are executed?

        printf("%s\n", cp);
        printf("%c\n", *cp);
        printf("%c\n", cp[6]);
        printf("%s\n",cp2);
        printf("%c\n",*cp2);
        
  29. Write a function, prototype below, that mirrors the behaviour of the library function strrchr. This function takes a string and a character as arguments, and returns a pointer to the last occurrence of the character c in the string s.

    It returns NULL if the character cannot be found.

        char *strrchr(char s[], char c)
        
  30. Write a program multiply.c that performs addition or multiplication of integers, as follows. Your program should continually read integers from the user until end-of-input is encountered. Then it should print either the sum or the product of the input numbers. The program behaviour is controlled by either of the following command-line arguments:

    -add, -multiply. If the wrong command-line argument(s) are supplied your program should do nothing.

  31. Write a C program thirteen_stdin.c which reads 2 integers from standard input and then prints all integers divisible by 13 between those numbers.

    Your program should behave like this:

        ./a.out 
        Enter start: 10
        Enter finish: 42
        13
        26
        39
        
  32. Modify the previous C program so that it instead takes 2 integers as command line arguments

    Your program should behave like this:

        ./a.out 10 42
        13
        26
        39
        
  33. Exam questions typically specify no error checking required.

    If error checking was required - what checking would you add to the programs from the previous 2 questions?

  34. Write a function, prototype below, that takes a string, and a character and removes the first occurrence of that character from the string. It should return 1 if the letter was found and removed, 0 otherwise. Write a main function that could test this function.

        int remove_char(char str[], char c)
        
  35. Write a function that takes an array of pointers to strings and prints out all the strings with more than a given number of characters.

    The prototype should be:

        // text - the array of strings
        // array_size - the number of strings in the array
        // num_chars - print out any strings in the array with more than this number
        // of characters
        void print_if_longer(int array_size, char text[array_size][MAX_LEN], int num_chars);
        
  36. Given the following code fragment:

        char goals[] = "All your goals belong to us.";
        char *a, *b, *c;
    
        a = goals + 5;
        b = &goals[10];
        c = goals + (b - goals) + (b - a);
        

    The fragment is valid C. It executes without error. Indicate clearly and exactly what the following expressions evaluate to:

    1. a == goals

    2. a > goals

    3. goals > c

    4. c - b

    5. goals - a

    6. a[0] != b[0]

    7. *c

    8. goals[a - goals] == *a

    9. c[a - b]

  37. Given the following code fragment:

        int i = 0;
        int j = 0;
        char *s = "ceded";
    
        while (s[i] != '\0') {
        j = j + s[i] - 'a';
        i = i + 1;
        }
        printf("%d %d\n", i, j);
        

    The fragment is valid C. It executes without error. Indicate clearly and exactly what output will be printed.

  38. Write a function,that takes a string along with a character and returns 1 if the character is found in the string and 0 otherwise. You must implement this function recursively. You may not use loops or C library functions. Write a main function that could test this function.