Course Content
Programming in C
About Lesson

An array is a data structure consisting of a collection of elements (values or variables), of same memory size, each identified by an array index. Let’s look at the following program that prints the digit count based on how many times each digit appears in input.

#include <stdio.h>

#define NUM_DIGITS 10

main()
{
    int digits[NUM_DIGITS], c, i;

    for (i = 0; i < NUM_DIGITS; i++)
        digits[i] = 0;

    while ((c = getchar()) != EOF) {
        if (c >= '0' && c <= '9') {
            digits[c - '0']++;
        }   
    }   

    for (i = 0; i < NUM_DIGITS; i++)
        printf("%d appears %d time(s).\n", i, digits[i]);
}

The declaration

int digits[NUM_DIGITS];

declares digits to be an array of 10 integers (NUM_DIGITS is 10). Array subscripts always start at 0 in C, so the elements are digits[0], digits[1], …, digits[9]. This is reflected in the for loops that initialise and print the array. A subscript can be any integer expression, which includes integer variables and integer constants. The statement

if (c >= '0' && c <= '9')

determines whether the character in c is a digit. This checks whether the ASCII code for character in c is between the ASCII codes of ‘0’ and ‘9’. Since, the ASCII codes for all the digits (0-9) have consecutive increasing values, we can use this logic. So, to find out the actual digit in variable c, we could subtract it with ‘0’ (ASCII code of character in variable c – ASCII code of ‘0’ = actual digit).

Scroll to Top