All categories
    CIntermediate

    C Arrays & Strings

    Work with arrays and strings in C: declare arrays, loop over elements, measure string length, and compare strings with string.h.

    01Arrays

    main.c
    #include <stdio.h>
    
    int main() {
        int nums[5] = {10, 20, 30, 40, 50};
        printf("%d\n", nums[0]);
        printf("%d\n", nums[4]);
        return 0;
    }
    Output
    10
    50

    02Loop over an array

    main.c
    #include <stdio.h>
    
    int main() {
        int nums[4] = {2, 4, 6, 8};
        int sum = 0;
        for (int i = 0; i < 4; i++) sum += nums[i];
        printf("Sum = %d\n", sum);
        return 0;
    }
    Output
    Sum = 20

    03String length

    main.c
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char name[] = "Python";
        printf("Length: %lu\n", strlen(name));
        printf("%s\n", name);
        return 0;
    }
    Output
    Length: 6
    Python

    04Compare strings

    main.c
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char a[] = "cat";
        char b[] = "cat";
        if (strcmp(a, b) == 0) printf("Equal\n");
        else printf("Different\n");
        return 0;
    }
    Output
    Equal