Search code examples
cstringfor-loopcomparison-operators

for loop not working - the outer loop not iterating


I want to make a program to reiterate through a string and get an overlapping (remove the first element of the parent string in each iteration) substring of 23 elements. I think the outer loop does not work. Please help me understand what's going on.

Here is the relevant part of the code I have used.

char *copy = (char*)malloc(sizeof(char)*(length+1));
strcpy(copy, seq);

printf("%s\n %d", copy, strlen(copy));  
char temp[26]= "";
int templen=0;
for (int k=0; k>length; k++)    
{   

    for (int i=0; i< 23; i++)   
    {
        templen = strlen(temp);         
        temp[templen]=copy[i];  
        templen++;                  
    } 

    temp[templen+1] = '\0';
    printf("%s\n", temp);
    temp[0]='\0';
    copy++;
    printf("%s\n %d", copy, strlen(copy));  
}

free(seq);

Solution

  • for (int k=0; k>length; k++) 
    

    This type of code will give you either

    1. infinite loop

    or

    1. non-hitting condition.

    Here, this is point 2. Considering length having value >= 0, the condition check in for loop will become a Failure, so it'll not execute the loop body.

    For case 1, If you initialize k with some value > that of length, you'll face the infinite loop, as the k>length will never become false then.

    You should change your condition check to for (int k=0; k < length; k++)

    Also, you should move templen = strlen(temp); outside inner for loop, or, you can omit that statement itself and initialize templen to zero before the inner for loop. You already have templen++; in your code.