Athena
Athena

Reputation: 27

The program does not seem to be exiting the loop. Why is that?

This is a simple for loop which the program cannot exit.

for(j=4;j<8;j++)
{
    label4:
    b=(rand()%100+1)/1000;
    temp1a[l]=(chrom[i][j]*(0.1-b))+(b*chrom[i+1][j]);
    temp2a[l]=(chrom[i+1][j]*(0.1-b))+(b*chrom[i][j]);
    if(temp1a[l]>0.1&&temp2a[l]>0.1)
    {
        l++;
        continue;
    }
    else
    {
        goto label4;
    }
}
printf("Initial temp arrays stored\n");

The end statement is not being printed and there is no output. Can someone please help me out.

Upvotes: 0

Views: 68

Answers (3)

John Bode
John Bode

Reputation: 123468

As pmg points out, you're always assigning a 0 to b due to using all integer operands in the division operation. That's likely contributing to the problem.

Based on your logic, it looks like you don't want to increment j unless l is also incremented, which only happens when temp1a[l] and temp2a[l] are above a threshold of 0.1.

There's a better way to structure the code such that you don't need either the continue or goto statements:

for(j=4;j<8;j++)
{
    do
    {
      b=(rand()%100+1)/1000.0;  // note at least one floating-point operand
      temp1a[l]=(chrom[i][j]*(0.1-b))+(b*chrom[i+1][j]);
      temp2a[l]=(chrom[i+1][j]*(0.1-b))+(b*chrom[i][j]);
    } while (temp1a[l] <= 0.1 || temp2a[l] <= 0.1)
    l++;
}

This will compute a new value for b and execute the subsequent calculations as long as either result is below the threshold value of 0.1. If both are above 0.1, the inner loop exits and l is incremented. Then the outer loop executes again.

Now, depending on what's in chrom, it's still possible that you may hit a situation where the inner loop never exits. You'll need to do some analysis to see what solutions lead to state where either temp1a or temp2a never rise above their threshold values, and then add some code to check for those states and not enter the loop.

Upvotes: 0

pmg
pmg

Reputation: 108938

b=(rand()%100+1)/1000;

The (rand()%100+1)/1000 part yields 0. Net effect:

b = 0;

Upvotes: 2

Sabrina Jewson
Sabrina Jewson

Reputation: 1518

The goto label4 is probably the culprit.

The first line inside the loop is a label. It doesn't do anything, it just says to the compiler 'This place in the code is called label4'. Then, later in the loop the if statement is failing, so the code goto label4 is executed.

That results in the code jumping back to label4. Something is causing the if statement never to succeed, and so the code eternally jumps back to label4 (the beginning of the loop).

Upvotes: 0

Related Questions