Home > Net >  What could I be doing incorrectly in this loop
What could I be doing incorrectly in this loop

Time:07-30

#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.

CodePudding user response:

You don't set i inside the for loop, so the condition of the while loop a[i] != '\0' remains false for n > 1 (so 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;
}

CodePudding user response:

The previous answer is correct but if you want to use your original approach with the while loop, you just need to add the statement i=0; inside the for loop, just before the while statement.

  • Related