Salta al contenuto
Note per Studenti Lab Exercises - Loops, Arrays, Structs and IO Report

Lab Exercises - Loops, Arrays, Structs and IO

In questa pagina 3

Two problem sets. The slides give statements and hints; the only worked solution is the string reversal (set B). Where no solution is given, the notes below list what each exercise requires and which tools from the other notes apply.

General method from the slides: define as many subproblems as possible, one function for each, solve one subproblem at a time, and check that the execution is correct before moving to the next (write main with the first function, test, then continue).

Set A - loops and arrays

A1. Series

Write the first 30 elements of a series: the first three elements are 1, each following one (i >= 4) is the sum of the elements i-1 and i-3.

Hint: use an array of integers or 4 int variables. Needs: loops, arrays (Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →), Control StructuresBasic syntax rules and the control structures of C: if/else, switch, the ternary operator, goto, symbolic constants and the while, for and do-while loops with break and continue.Control Structures →.

A2. Maximum, minimum and sorting from the command line

Given N > 0 (at most 10) different integers passed as command-line arguments, print the maximum and the minimum, the position at which each was inserted, and the sequence in ascending order.

Hints:

  • atoi (simpler) or strtol (more complete and robust) convert the string arguments to integers.
  • Loop over the arguments (the slide prints them like this):
c
for (int i = 1; i < argc; i++)
    printf("%s\t", argv[i]);

Needs: argc/argv, an int array of size 10, search and ordering, Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →.

A3. Alphabet shift (Caesar-style)

Transform a string into a new one in which every character is OFFSET positions further in the alphabet. Alphabet considered: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz, cyclic: after z comes A. With OFFSET = 4: a becomes e, X becomes b, x becomes B.

Difficulty noted by the slides: in ASCII the sequences 'A'..'Z' and 'a'..'z' (upper case first) are not consecutive, there is another set of characters in between, so the program must be broken into 2 ifs (one for each range).

Needs: char arithmetic, string traversal (Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →).

A4. Structs: courses and students

Define the type Course for language courses:

  • language: sequence of 10 characters;
  • level: integer;
  • numberEnrolled: integer;
  • teacherName: sequence of 30 characters;
  • the set of students (maximum 10); each student is a struct with studentName (10 characters), studentLastName (10 characters), studentAge (integer).

Then declare the variable school, able to hold the courses of a school (maximum 30 courses), and write the part of the algorithm that computes the average age of the students enrolled in the English language courses (assume school has been initialized with the information of 30 courses).

Needs: nested structs and arrays of structs, string comparison to select the language, numberEnrolled as the count of valid students in each course. See Command-Line Arguments and StructsHow main receives command-line arguments (argc, argv), converting them with atoi and strtol, parsing options with getopt, and grouping data with struct, typedef and union.Command-Line Arguments and Structs →.

Set B - strings, files, structs and enums

B0. Input and output recap (slides)

The second deck opens with the recap of getchar, putchar, redirection and pipes, and the lower program, see Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C →.

B1. Reverse a string (worked solution)

Statement: ask the user to type a string of N characters, read it from stdin until carriage return is pressed, invert it with a function to be implemented, and display the inverted string (Computer becomes retupmoC).

Hints: one function per subproblem; the line can be read with scanf(" %N[^\n]", str);, scanf(" %s", str); or fgets(str, N, stdin); (see Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C →, Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →).

Solution of the slides, assembled. Reading the string with getchar up to the newline, stopping at N-1 characters so there is room for '\0':

c
#include <stdio.h>
#include <string.h>
#define N 41

void exchange(char* a, char* b) {      // swaps two chars through pointers
    char aux;
    aux = *a;
    *a = *b;
    *b = aux;
}

void reverse(char v[]) {
    int i, l;
    l = (int)strlen(v);
    for (i = 0; i < l / 2; i++)        // swap symmetric pairs, only up to the middle
        exchange(&v[i], &v[l - i - 1]);
}

int main() {
    char s[N], c;
    int i = 0;
    printf("Type the word to reverse:\n");
    while ((c = getchar()) != '\n') {
        s[i++] = c;
        if (i == (N - 1))
            break;
    }
    s[i] = '\0';
    printf("\nString to be inverted: %s", s);
    reverse(s);
    printf("\nReversed string: %s", s);
    return(0);
}

Notes:

B2. Alphabet shift on ASCII 32..126

Transform a string into a new one where each character is offset positions further in the alphabet. The alphabet is the characters from ASCII code 32 to 126, cyclic: after code 126 comes code 32. With offset = 4: a becomes e, X becomes \, x becomes |. The offset may be positive or negative.

Two versions:

  1. the string and the offset are passed as arguments to the program;
  2. the string is read from a file whose name is passed as argument, together with the offset.

Hints: many subproblems, one at a time; write main for the first subproblem, check the output, then proceed. Needs: argv, Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →, modular arithmetic on a range of 95 codes (32 to 126 inclusive).

B3. Physical characteristics: struct and enum

The data type Physical Characteristic describes a person with:

  • weight (in ounces),
  • height (in cm),
  • hair colour (blond, brown, black, white),
  • age.

Define a data type containing this data; use both struct and enum.

Write a program that:

  1. prints how many bytes each instance of the structure occupies (sizeof);
  2. reads from a file, redirected as standard input, at most 20 instances (one per row), whose elements are separated by ;;
  3. prints the information of all people with age <= 20;
  4. prints the information of all people whose hair colour is blond.

Hair colours are represented as: blond 1, brown 0, black 3, white 2 (other colours could exist too). So the enum gets explicit values, see Miscellaneous Syntax - Enums, Typedef, Preprocessor and Morescope and linkage of variables, extern and header files, storage classes (auto, static, register), const and volatile, enumerations, block structure, initialization, the C preprocessor with macros and conditional compilation, and recursion.Miscellaneous Syntax - Enums, Typedef, Preprocessor and More →.

Hint for splitting a row, with strtok:

c
char* t;
if ((t = strtok(row, ";")) != NULL) {
    // the string before ';' is stored in variable t
    if ((t = strtok(NULL, ";")) != NULL)
        // the next string after ';' is stored in variable t
}

Reading rows from standard input: fgets (Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →).

Further exercises in the slides

Short statement lists are in the notes where the topics are explained:

Versione ripasso

  • Method: split into subproblems, one function each; write main for the first, test it, then add the next.
  • A1 series: first three terms 1, then term i is term i-1 plus term i-3 (30 terms); array of ints or four variables.
  • A2: N <= 10 integers from argv (atoi simple, strtol robust, loop i = 1 .. argc-1); print max, min, their input positions and the sorted list.
  • A3 alphabet shift on A..Z a..z (cyclic): upper and lower case are not contiguous in ASCII, so two ifs; offset 4: a to e, X to b, x to B.
  • A4: structs Course (language[10], level, numberEnrolled, teacherName[30], up to 10 students with name[10], lastName[10], age) and school of up to 30 courses; average age of students in English courses.
  • B1 string reversal: read with getchar until '\n' (max N-1 chars), s[i] = '\0', reverse(v): for i < l/2 call exchange(&v[i], &v[l-i-1]); exchange swaps through pointers with aux.
  • B2 shift on ASCII 32..126 (cyclic, offset positive or negative): string from argv, then from a file given in argv; a to e, X to \, x to | for offset 4.
  • B3: struct with weight (ounces), height (cm), hair enum (brown 0, blond 1, white 2, black 3), age; print sizeof, read up to 20 rows ;-separated from redirected stdin (strtok(row, ";") then strtok(NULL, ";")), print people with age <= 20 and blond ones.
  • Typical errors: missing prototype for exchange, no room for '\0', using feof as loop condition, forgetting that upper and lower case ranges are separate.

See Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C →, Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →, Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →.

Teoria collegata