Skip to content
Laviyx Learn

Try

C Arrays, Strings and Structures Practice

Practise arrays, 2D arrays, C strings and the string.h functions, structs, files and bit manipulation in C.

Intermediate10 problemsUpdated

Review first: Arrays, Multidimensional Arrays, Strings, String Functions, Structures, File Handling, Bitwise Operators

  1. 1.Reverse an array and find its maximum

    Beginner

    Read 5 integers into an array, print the largest one and its position (index), then print the array in reverse order.

    Show hint

    Track the index of the largest element, not just its value. Print in reverse with for (int i = 4; i >= 0; i--).

    Show solution
    C
    #include <stdio.h>
    
    int main(void) {
        int a[5];
        for (int i = 0; i < 5; i++) {
            if (scanf("%d", &a[i]) != 1) return 1;
        }
        int best = 0;
        for (int i = 1; i < 5; i++) {
            if (a[i] > a[best]) best = i;
        }
        printf("max %d at index %d\n", a[best], best);
        for (int i = 4; i >= 0; i--) printf("%d ", a[i]);
        printf("\n");
        return 0;
    }
    Output
    12
    45
    7
    45
    30
    max 45 at index 1
    30 45 7 45 12
  2. 2.Row and column sums of a matrix

    Intermediate

    For int m[3][3] = {{4, 9, 2}, {3, 5, 7}, {8, 1, 6}}, print each row's sum, each column's sum and the main diagonal's sum. (This is a magic square, so they should all be equal.)

    Show hint

    Use nested loops. For column sums, put the row loop inside the column loop.

    Show solution
    C
    #include <stdio.h>
    
    int main(void) {
        int m[3][3] = {{4, 9, 2}, {3, 5, 7}, {8, 1, 6}};
        printf("rows:");
        for (int r = 0; r < 3; r++) {
            int s = 0;
            for (int c = 0; c < 3; c++) s += m[r][c];
            printf(" %d", s);
        }
        printf("\ncols:");
        for (int c = 0; c < 3; c++) {
            int s = 0;
            for (int r = 0; r < 3; r++) s += m[r][c];
            printf(" %d", s);
        }
        int d = 0;
        for (int i = 0; i < 3; i++) d += m[i][i];
        printf("\ndiagonal: %d\n", d);
        return 0;
    }
    Output
    rows: 15 15 15
    cols: 15 15 15
    diagonal: 15
  3. 3.Count vowels in a line

    Beginner

    Read a whole line with fgets and print the number of vowels (a, e, i, o, u, either case) and the number of other letters.

    Show hint

    Use tolower and strchr("aeiou", c) to test for a vowel, and isalpha for letters. Cast characters to unsigned char before passing them to <ctype.h> functions.

    Show solution
    C
    #include <ctype.h>
    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        char line[200];
        if (fgets(line, sizeof line, stdin) == NULL) return 1;
        int vowels = 0, consonants = 0;
        for (int i = 0; line[i] != '\0'; i++) {
            unsigned char c = (unsigned char)line[i];
            if (!isalpha(c)) continue;
            if (strchr("aeiou", tolower(c))) vowels++;
            else consonants++;
        }
        printf("vowels %d, other letters %d\n", vowels, consonants);
        return 0;
    }
    Output
    Learning C Is Fun
    vowels 5, other letters 9
  4. 4.Capitalise every word

    Intermediate

    Read a line and print it with the first letter of every word in uppercase and the rest in lowercase.

    Show hint

    Keep a flag that says whether the previous character was a space. Remove the newline fgets keeps with line[strcspn(line, "\n")] = '\0';.

    Show solution
    C
    #include <ctype.h>
    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        char line[200];
        if (fgets(line, sizeof line, stdin) == NULL) return 1;
        line[strcspn(line, "\n")] = '\0';
        int start = 1;
        for (int i = 0; line[i] != '\0'; i++) {
            unsigned char c = (unsigned char)line[i];
            if (isspace(c)) {
                start = 1;
            } else {
                line[i] = (char)(start ? toupper(c) : tolower(c));
                start = 0;
            }
        }
        printf("%s\n", line);
        return 0;
    }
    Output
    hELLO wORLD from c
    Hello World From C
  5. 5.Parse a CSV line

    Intermediate

    Split char data[] = "Pune,Chennai,Delhi,Kochi"; at the commas with strtok, print each city with its length, and print the longest city.

    Show hint

    Call strtok(data, ",") once, then strtok(NULL, ",") until it returns NULL. Store a pointer to the longest token.

    Show solution
    C
    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        char data[] = "Pune,Chennai,Delhi,Kochi";
        const char *longest = NULL;
        for (char *t = strtok(data, ","); t != NULL; t = strtok(NULL, ",")) {
            printf("%s (%zu)\n", t, strlen(t));
            if (longest == NULL || strlen(t) > strlen(longest)) longest = t;
        }
        printf("longest: %s\n", longest);
        return 0;
    }
    Output
    Pune (4)
    Chennai (7)
    Delhi (5)
    Kochi (5)
    longest: Chennai
  6. 6.Array of student structs

    Intermediate

    Define typedef struct { char name[20]; int marks[3]; } Student;. For three students, compute each average, print it, and print the name of the student with the highest average.

    Show hint

    Write double average(const Student *s) and call it with &list[i]. Inside, use s->marks[j].

    Show solution
    C
    #include <stdio.h>
    
    typedef struct {
        char name[20];
        int marks[3];
    } Student;
    
    double average(const Student *s) {
        return (s->marks[0] + s->marks[1] + s->marks[2]) / 3.0;
    }
    
    int main(void) {
        Student list[] = {
            {"Asha", {78, 85, 90}},
            {"Ravi", {88, 92, 79}},
            {"Meena", {95, 70, 81}},
        };
        int best = 0;
        for (int i = 0; i < 3; i++) {
            printf("%-6s %.2f\n", list[i].name, average(&list[i]));
            if (average(&list[i]) > average(&list[best])) best = i;
        }
        printf("top: %s\n", list[best].name);
        return 0;
    }
    Output
    Asha   84.33
    Ravi   86.33
    Meena  82.00
    top: Ravi
  7. 7.Sort structs by a field

    Advanced

    Store four products (name and price) in an array of structs and sort them by price, lowest first, using qsort. Print them in order.

    Show hint

    The comparison function receives pointers to two structs: convert with const Product *p = a; and compare p->price.

    Show solution
    C
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct {
        const char *name;
        double price;
    } Product;
    
    int by_price(const void *a, const void *b) {
        const Product *x = a, *y = b;
        return (x->price > y->price) - (x->price < y->price);
    }
    
    int main(void) {
        Product items[] = {
            {"Keyboard", 1299.0}, {"Mouse", 499.0}, {"Monitor", 8999.0}, {"Cable", 199.0},
        };
        qsort(items, 4, sizeof items[0], by_price);
        for (int i = 0; i < 4; i++) printf("%-9s %8.2f\n", items[i].name, items[i].price);
        return 0;
    }
    Output
    Cable       199.00
    Mouse       499.00
    Keyboard   1299.00
    Monitor    8999.00
  8. 8.Write and read back a file

    Intermediate

    Write three lines of text to notes.txt, then open it again for reading and print the number of lines and the number of characters (excluding newlines).

    Show hint

    Check every fopen for NULL. Read with fgetc until EOF, counting '\n' separately.

    Show solution
    C
    #include <stdio.h>
    
    int main(void) {
        FILE *f = fopen("notes.txt", "w");
        if (f == NULL) return 1;
        fputs("pointers\n", f);
        fputs("structs\n", f);
        fputs("files\n", f);
        fclose(f);
    
        f = fopen("notes.txt", "r");
        if (f == NULL) return 1;
        int c, lines = 0, chars = 0;
        while ((c = fgetc(f)) != EOF) {
            if (c == '\n') lines++;
            else chars++;
        }
        fclose(f);
        printf("%d lines, %d characters\n", lines, chars);
        return 0;
    }
    Output
    3 lines, 20 characters
  9. 9.Permission flags with bits

    Intermediate

    Using bit flags READ = 1, WRITE = 2 and EXEC = 4, start with no permissions, grant read and write, print the value, then revoke write and grant exec, and print the value and whether write is set.

    Show hint

    Grant with |=, revoke with &= ~FLAG and test with &.

    Show solution
    C
    #include <stdio.h>
    
    enum { READ = 1u << 0, WRITE = 1u << 1, EXEC = 1u << 2 };
    
    int main(void) {
        unsigned perms = 0;
        perms |= READ | WRITE;
        printf("perms = %u\n", perms);
        perms &= ~WRITE;
        perms |= EXEC;
        printf("perms = %u, write %s\n", perms, (perms & WRITE) ? "on" : "off");
        return 0;
    }
    Output
    perms = 3
    perms = 5, write off
  10. 10.Count the 1 bits

    Advanced

    Write int popcount(unsigned x) that counts the bits set to 1, and print the counts for 0, 7, 255 and 1024.

    Show hint

    x & (x - 1) clears the lowest set bit. Count how many times you can do that before x is 0.

    Show solution
    C
    #include <stdio.h>
    
    int popcount(unsigned x) {
        int count = 0;
        while (x != 0) {
            x &= x - 1;
            count++;
        }
        return count;
    }
    
    int main(void) {
        unsigned tests[] = {0, 7, 255, 1024};
        for (int i = 0; i < 4; i++) printf("%u -> %d\n", tests[i], popcount(tests[i]));
        return 0;
    }
    Output
    0 -> 0
    7 -> 3
    255 -> 8
    1024 -> 1