Search code examples
cloopsnested-loops

What could I be doing incorrectly in this loop


#include <stdio.h>

void print_alphabet(void)
{
    char a[] = "abcdefghijklmnopqrstuvwxyz";
    int i = 0;
    int n;
    for (n = 0; n <= 9; n++)
    {
        while (a[i] != '\0')
        {
            putchar(a[i]);
            i++;
        }
        putchar('\n');
    }
    return;
}

int main(void)
{
    print_alphabet();
    return 0;
}

I am trying to print the alphabet 10 times with each series on a different line but, when I compile and execute my code, I only get one line of the complete alphabet and 9 blank new line.


Solution

  • You don't set i inside the for loop, so the condition of the while loop a[i] != '\0' remains false for n > 1. This means the body of the while loop doesn't get executed again. Use another for loop instead:

    #include <stdio.h>
    
    void print_alphabet(void) {
        const char a[] = "abcdefghijklmnopqrstuvwxyz";
        for (unsigned char n = 0; n < 10; n++) {
            for(unsigned char i = 0; a[i]; i++) {
                putchar(a[i]);
            }
            putchar('\n');
        }
        return;
    }
    
    int main(void) {
        print_alphabet();
        return 0;
    }