• exam.c

  • §

    Jonas Altrock ew20b126@technikum-wien.at

    To overview.

    The whole source file exam.c.

    /* compile with -std=c99 */
  • §

    Include C-libraries for input/output.

    #include <stdio.h>
    #include <stdlib.h>
  • §

    CS1 exam

  • §

    Unfortunately, I don’t have a PDF of the exam questions / problem statement. This is the file I submitted plus a little more comments.

    int main1();
    int main2();
    int main3();
    char *day_suffix(int day);
    int is_even(int number);
    int sum_even(int n);
  • §

    main()

    int main(int argc, char **argv)
    {
  • §

    I built a switcher to execute the 3 subtasks by passing a command-line argument to the program. Super unnecessary, but I had the time.

        if (argc > 1) {
            int task = atoi(argv[1]);
    
            if (task == 1) return main1();
            if (task == 2) return main2();
            if (task == 3) return main3();
    
            printf("This exam has only 3 questions.\n");
    
            return 0;
        }
    
        printf("Please indicate which exam question you want to run as the first argument!\n");
    
        return 0;
    }
  • §

    main1()

    Read in three numbers, output as formatted date.

    int main1() {
        int day, month, year;
    
        scanf("%d %d %d", &day, &month, &year);
    
        printf("%d/%d %d%s\n", month, year, day, day_suffix(day));
    
        return 0;
    }
  • §

    day_suffix()

    char *day_suffix(int day) {
        if (day == 1 || day == 21 || day == 31) return "st";
        if (day == 2 || day == 22) return "nd";
        if (day == 3 || day == 23) return "rd";
        return "th";
    }
  • §

    main2()

    read in three numbers twice, then output the dot-product of the vectors

    int main2() {
        int v1[3];
        int v2[3];
  • §

    a bit inelegant but is quick to type and works…

        scanf("%i", &v1[0]);
        scanf("%i", &v1[1]);
        scanf("%i", &v1[2]);
    
        scanf("%i", &v2[0]);
        scanf("%i", &v2[1]);
        scanf("%i", &v2[2]);
    
        int dot = 0;
    
        for (int i = 0; i < 3; i++) {
            dot += v1[i] * v2[i];
        }
    
        printf("%i\n", dot);
    
        return 0;
    }
  • §

    main3()

    use is_even and sum_even to calculate the sum of all even number up to n

    int main3() {
        int n;
    
        scanf("%d", &n);
    
        printf("%d\n", sum_even(n));
    
        return 0;
    }
  • §

    is_even()

    int is_even(int number) {
        if (number % 2 == 0) {
            return 1;
        }
    
        return 0;
    }
  • §

    sum_even()

    int sum_even(int n) {
        int sum = 0;
    
        for (int i = 2; i <= n; i++) {
            if (is_even(i)) {
                sum += i;
            }
        }
    
        return sum;
    }