I can't understand the increment portions of for loops in c language for specific problem

59 Views Asked by At
#include <stdio.h>
#include <conio.h>

int main(void)
{
    char ch;
    for(ch=getche(); ch!='q'; ch=getche());
    printf("Found the q");
    return 0;
}

I can't understand how the for loop here works . I can understand the initialization and the conditional test . But don't get why I have to use getche function again in increment portions .

3

There are 3 best solutions below

0
mkrieger1 On

It may help to rewrite this for loop into an equivalent while loop:

for(ch=getche(); ch!='q'; ch=getche());

becomes

ch = getche();
while (ch != 'q') {
    ch = getche();
}

So you repeatedly get a new character by calling getche, until the character you get is equal to 'q'.

Without the second ch=getche(), you would get only a single character and compare this to 'q' over and over again (leading to an infinite loop if it isn't 'q').

0
Vlad from Moscow On

To make it clear rewrite the for loop:

for(ch=getche(); ch!='q'; ch=getche());

the following way:

for(ch=getche(); ch!='q'; )
{
    ch=getche();
}

That is the statement in the body of the second for loop:

ch=getche();

is moved as an expression in the third part of the first for loop.

In the third part of for loop there may be used any expression not only an expression with the increment or decrement operator.

0
John Bode On

Remember how a for loop typically works:

for ( init-expressionopt ; test-expressionopt ; update-expressionopt )
  statement

init-expression (if present) is evaluated exactly once; it (typically) sets up the thing we’re testing against. In this case, it initializes the value the of ch by calling getche.

Before each loop iteration, test-expression (if present) is evaluated; if zero, the loop exits. In this case, the test is ch != 'q'.

After each loop iteration, update-expression (if present) is evaluated; it updates the thing we’re testing against. In this case, it updates the value of ch by executing another getche call. Without this step, the value of ch would not change and the loop would execute indefinitely.