1

I am supposed to take the following program fragment and use goto statements to show the flow control through the the loop:

for ( int i = n; i > 0; i-- ) {
    if ( x != A[i] )
    break;
}

I realize that goto statements should be avoided, but this is what the question is asking for. I think this is what it should be, so that the flow control is shown through the loop:

for ( int i = n; i > 0; i-- ) {
    if ( x != A[i] )
    goto xValue;
    break;
}

xValue: cout << "The value of x: \n" << x;

Is this correct? I am not positive about whether to place the goto statement before or after the break statement.

  • Q: Why don't you delete the "break"? Q: Shouldn't you also replace for "for" loop with a goto? – paulsm4 Mar 16 '16 at 05:17
  • So, you're saying replace `for` with `goto`, and remove the break statement entirely? @paulsm4 – ComputerScientist123 Mar 16 '16 at 05:19
  • I too would remove the for loop and replace it with explicit gotos. A for is just an init block, followed by an exit condition (which is basically an if and a goto), followed by a body, an increment operation and a goto back to the exit condition check. Obviously, just for the assignment ;) – Alberto Chiesa Mar 16 '16 at 05:22
  • Is this what you were thinking about? @paulsm4 @A.Chiesa `goto xValue ( int i = n; i > 0; i--) if ( x !=A[i] ) goto xValue;` – ComputerScientist123 Mar 16 '16 at 07:20

1 Answers1

0

I believe this is the correct solution for this question:

xValue ( int i = n; i > 0; i-- )
      If ( x !=  A[i] )
        goto xValue;