Computer Science Canada

loop within a loop

Author:  iluvchairs112 [ Mon Feb 26, 2007 7:41 pm ]
Post subject:  loop within a loop

how does a loop within a loop work?

loop % start first loop

redx:=redx+10 %redx increases by 10
delay(50)
redy:=redy+10 %redy increases by 10
delay(50)

if redx=300
then
loop
redx:=redx-10
delay(50)
redy:=redy-10
delay(50)
end loop
end if

drawfilloval(redx, redy, redxr, redyr, 40)
drawfilloval(orangex, orangey, orangexr, orangeyr, 65)

end loop


basically what I want to happen is the red circle goes up until it reaches a certain point(when x=300) and then have it go back down again
it should be simple, but my code just stops it ... it doesn't continue back down
what am I missing?

Author:  Clayton [ Mon Feb 26, 2007 7:58 pm ]
Post subject:  Re: loop within a loop

Well, what does redx start off as? Once it enters that if statement, and that nested loop, it never gets out, because there is no exit condition.

Author:  BenLi [ Mon Feb 26, 2007 8:05 pm ]
Post subject:  Re: loop within a loop

a couple of issues, in order to see it, the drawoval needs to be in the nested loop as well. Even then, you won't see a difference because its going down the way it went up. Perhaps you meant something like this?

code:

var redx, redy := 0
loop % start first loop

    redx := redx + 10 %redx increases by 10
    delay (50)
    redy := redy + 10 %redy increases by 10
    delay (50)

    if redx = 300
            then
        loop
            redx := redx + 10
            delay (50)
            redy := redy - 10
            delay (50)
            drawfilloval (redx, redy, 10, 10, 40)
        end loop
    end if

    drawfilloval (redx, redy, 10, 10, 40)

end loop


However, a nested loops is not the best solution for your problem, consider something like this, where the y value increments by a negative or a positive value
code:


setscreen ("graphics:max,max")
var redx, redy := 0
var n := 10
loop % start first loop
    if redy < 0 then
        n := 10
    elsif redy > 300 then
        n := -10
    end if
    redx := redx + 10
    redy := redy + n
    drawfilloval (redx, redy, 10, 10, 40)
    delay (10)
end loop


Quote:

Well, what does redx start off as? Once it enters that if statement, and that nested loop, it never gets out, because there is no exit condition.


Good point, however, if he only wants to animate one time, he doesn't need to, however, its bad to have an infinite loop none the less


: