开发者

Implementing Loops from Pseudocode

开发者 https://www.devze.com 2022-12-21 10:20 出处:网络
I was wondering if anyone could suggest to me how to implement this loop in the following pseudocode:

I was wondering if anyone could suggest to me how to implement this loop in the following pseudocode:

8: loop

9: while f[0] = 0 do

10: for i = 1 to N do

11: f[i ¡ 1] = f[i]

12: c[N + 1 - i] = c[N - i]

13: end for

14: f[N] = 0

15: c[0] = 0

16: k = k + 1

17: end while

18: if deg(f) = 0 then

19: goto Step 32

20: end if

......... ...... ....

31: end loop

My question is how I should implement the loop that starts on line 8 and ends on 31; I am comfortable with the statements between lines 8 to 31, but what kind of loop do I use on line 8, and what conditions do I give for the l开发者_如何学运维oop?

Thanks in advance.


That's an infinite loop. No conditions, just loop forever. The only way out is to get to step 19. In C-like languages you can write that as while (true) or for (;;):

for (;;) {
    // ...

    if (deg(f) == 0) {
        goto afterLoop;
    }

    // ...
}

afterLoop:
// ...

goto is frowned upon, though. It'd be better to replace goto Step 32 with a break statement, which exits a loop immediately:

for (;;) {
    // ...

    if (deg(f) == 0) {
        break;
    }

    // ...
}

For what it's worth, if you didn't have steps 21-30 you could use a do/while loop, where the loop condition goes at the bottom of the loop instead of the top:

do {
    // ...
}
while (deg(f) != 0);

That would work if lines 18-20 were the final lines in the loop. Since they're not, it looks like option #2 is the one to go with.


If you are going to write pseudocode in such detail, you might as well write in the target language. Pseudocode should be a much broader brush - something like this (not related to your code):

for each bank account
   check balance as of last month
   if balance greater than promotion limit
      send out valued customer pack
   endif
endfor
0

精彩评论

暂无评论...
验证码 换一张
取 消