Problem Set: Arrays of Strings in C


  1. void printstrs(char strarr[][51], int numstr) {
        int i;
        for (i = 0 ; i < numstr ; i++)
            printf("%s\n", strarr[i]);
    
    }
    
  2. int findSmallest(char strarr[][51], int numstr) {
        int small = 0;
        int i;
        for (i = 1 ; i < numstr ; i++)
            if (strcmp(strarr[small], strarr[i]) > 0)
                small = i;
        return small;
    
    }
    
  3. void removeNL(char strarr[][51], int numstr) {
        int i, k;
        int loc;
    
        // outer loop is for each string in the array
        for (i = 0 ; i < numstr ; i++) {
    
            //  inner loop is to find the null byte (has no body)
            for (k = 0 ; strarr[i][k] != '\0' ; k++);
    
            // if char before null byte is newline, replace it with null byte
            if (strarr[i][k-1] == '\n')
                strarr[i][k-1] = '\0';
        }
    }
  4. void toUpper(char string[]) {
        int i;
        for (i = 0 ; string[i] != '\0' ; i++)
    
            // check for lower case letter, and if so, subtract 32 to go
            // from ascii code of lowercase to ascii code of same letter in
            // uppercase
            if (string[i] >= 97 && string[i] <= 122)
                string[i] = string[i] - 32;
    }
    
  5. void readStrings(FILE *infile, char strarr[][51], int numstr) {
        int i;
        for (i = 0 ; i < numstr ; i++)
            fgets(strarr[i], 51, infile);
    }
    
  6. void printstrs(char [][51], int);
    void readstring(FILE *, char [], int);
    int findSmallest(char [][51], int);
    void removeNL(char [][51], int);
    void toUpper(char[]);
    void readStrings(FILE *, char [][51], int);
    
    int main(int argc, char** argv) {
        int i;
        char fileName[31];
        // array of 10 strings which can hold 50 char each
        char strings[10][51];
    
        puts("enter your file name");
        gets(fileName);
        FILE *infile = fopen(fileName, "r");
    
        readStrings(infile, strings, 10);
        printstrs(strings, 10);
        printf("\n");
        removeNL(strings, 10);
        printstrs(strings, 10);
        printf("\n");
        int small = findSmallest(strings, 10);
        printf("the smallest is %s in location %d\n\n", strings[small], small);
        printf("\n");
    
        for (i = 0 ; i < 10 ; i++)
            toUpper(strings[i]);
        printstrs(strings, 10);
        printf("\n");
    }
    


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2021