GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Why is the second while loop in KMP not a conditional statement?

When building the partial match table for KMP:

void buildBackTable() { 
    int i = 0, j = -1; b[0] = -1; 
    while (i < m) { 
        while (j >= 0 && P[i] != P[j]) j = b[j]; //Why is this a while loop!?
        i++; j++;
        b[i] = j;
    }
}   

How come that second while loop is not a conditional instead? Such as:

void buildBackTable() { 
    int i = 0, j = -1; b[0] = -1; 
    while (i < m) { 
        if (j >= 0 && P[i] != P[j]) j = b[j]; //Why not?
        i++; j++;
        b[i] = j;
    }
}   

In most of the examples I've tried, this statement is used to reset j to -1 when there is no match, so when the next iteration comes, we compare the first character of the string (P[j]) with the character at position i (P[i]). Is there an example where the while loop would be needed? I would love to see one. I've tried several samples of my own and changing the statement to a conditional would not make a difference (hence my question).

asked Aug 5, 2016 by net

1 Answer

 

The while loop is used to repeat a section of code an unknown number of times until a specific condition is met.It is a repetitive control structure.An if statement is not repetitive.

 

See this example http://quiz.geeksforgeeks.org/insertion-sort/

answered Aug 30, 2016 by 4nkush
edited Aug 30, 2016 by 4nkush
...