DEV Community

Aditya
Aditya

Posted on Originally published at techvaniai.blogspot.com

Arrays and Strings in C: Storing Many Values with Tested Programs (C Learning Guide, Part 6)

In Part 6 of our beginner C series the packing tool finally remembers a whole day instead of one number: eight hourly order counts live in one array, and text becomes a string - an array of char with a hidden stop mark.

What the full guide covers:

  • Declaration, indexing and bounds: why C counts from 0, what lives in a[5] when you skip the braces, and why the compiler will not stop you at the edge of an array.
  • Walking an array with a for loop: totals, averages, the busiest hour, and counting hours above capacity in one pass.
  • Strings: char arrays, the '\0' terminator you can actually print, and the four workhorse functions - strlen, strcpy, strcat, strcmp - with the exact reason a = b fails for arrays (the real gcc error is shown).
  • Classic string algorithms by hand: reversing "table" into "elbat" and checking that "level" is a palindrome, plus dry-run tables that trace every swap.
  • Every program compiled with a C17 compiler with warnings on, and every output block is the captured output of a real run - including the compiler errors and the format-warning demo.

A taste of the style - one pass over the day gives three answers:

#include <stdio.h>
int main(void) {
    int orders[8] = {4, 9, 7, 12, 6, 10, 3, 8};
    int capacity = 10;
    int total = 0;
    int busiest = 0;
    int over = 0;
    for (int i = 0; i < 8; i = i + 1) {
        total = total + orders[i];
        if (orders[i] > orders[busiest]) {
            busiest = i;
        }
        if (orders[i] > capacity) {
            over = over + 1;
        }
    }
    printf("total orders today: %d\n", total);
    printf("busiest hour: index %d with %d orders\n", busiest, orders[busiest]);
    printf("hours above capacity %d: %d\n", capacity, over);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

total orders today: 59
busiest hour: index 3 with 12 orders
hours above capacity 10: 1
Enter fullscreen mode Exit fullscreen mode

Read the full guide with every example and practice exercise: Arrays and Strings in C: Storing Many Values with Tested Programs - C Learning Guide, Part 6

New to the series? It starts from zero setup here: Programming in C - Learning Guide series index

Top comments (0)