Search code examples
carraysfor-loopgetch

Importance of using getch() inside a for-loop


I just wanted to ask what the importance of using getch() is, especially in this array/for-loop example that our professor showed us:

int i;
char pw[7], ch;

printf ("\npw: ");

for (i=0; i<7; i++) {
    ch = getch();
    pw[i] = ch;
    printf ("%c", ch);
}

I tried removing the ch = getch() line and what happened when I ran the program was that the loop went on forever.

Why does that happen?

I only understand that getch() is used at the end of a program to not show a character on the screen (from online definitions).


Solution

  • getch() reads a character from the keyboard without echoing it.

    so your program is reading a character from the keybord (user input). and storing it in ch variable, then saving it in the string array pw[], at the end echoing it using printf("%c");

    by removing ch = getch();. your program stops reading from keyboard. and fills the pw[] with the same value of (uninitialized ) ch exactly 7 times, and then exit loop.

    according to what you posted, you program hangs elsewhere, where you are testing the validity of the password.