Duck-Duck-Goose and Moduluse

There is no such word as moduluse, but the C language does feature the modulus operator, %. You can employ that operator do count off intervals, which allows you to manipulate information in a consistent and interesting way.

In my books, I’ve provided text-manipulation examples that replace specific characters in a string with an * or @ or some other character. That’s an easy substitution, but it’s based on the character itself. You can use the modulus operator to replace characters at predictable intervals in a string in much the same manner.

For a moment, forget about why such a thing is necessary: It’s the learning process that’s important!

The following code takes a string of text and replaces every third character with an underscore.

#include <stdio.h>

int main()
{
    char *string = "When in the Course of human events";
    int count = 1;

    while(*string)
    {
        if(count%3)
            putchar(*string);
        else
            putchar('_');
        count++;
        string++;
    }
    putchar('\n');

    return(0);
}

The count variable starts at 1 at Line 6. If it starts with 0 then the first character of the string would be turned into an underscore, which isn’t exactly what I wanted.

The meat of the code is found in the if decision at Line 10. The result of count%3 is true for those values not equally divisible by 3, but false for values divisible by three. In other words, every third item. In this case, the else part of the structure handles that third item, displaying the underscore.

Here is sample output:

Wh_n _n _he_Co_rs_ o_ h_ma_ e_en_s

If you’d rather insert the underscore instead of replacing, then you need to modify the code. Try that on your own to see if you fully understand the concept. When you’re ready, you can review my solution by clicking here.

Here is the sample output for my solution:

Whe_n i_n t_he _Cou_rse_ of_ hu_man_ ev_ent_s

Unlike the first sample output, all of the text from the original string is displayed. After every third character, however, an underscore is inserted. (Well, actually, the underscore is output; the original string is unmodified.)

The purpose of this lesson will become obvious when I unveil the horrible, arduous exercise for December. Stay tuned for that!

Leave a Reply