June 26, 2024, 07:25:29 AM

News:

IonicWind Snippit Manager 2.xx Released!  Install it on a memory stick and take it with you!  With or without IWBasic!


FOR loops - a caution for Basic users

Started by John S, February 19, 2006, 09:50:37 AM

Previous topic - Next topic

0 Members and 3 Guests are viewing this topic.

John S

I ran into a conceptual issue with the FOR Loops.  I kept trying to make it work like Fortran and Basic's For, but it doesn't. 

Below is some spseudo-code for Basic/Fortran:

for n = 1 to 10          // initialize loop variable and test
                               // test is n for equality to 10 (n==10)
                               // if false continue with loop,  if true break loop
                               // by default n is incremented by 1

...something is repeated here

next n                      // terminal point of the loop, return increment and test n


Here's how it work's in Aurora:

for ( n = 1; n <= 10; n++ )  // initialize n to value of 1, test if n <= 10, if true loop, if false break loop
                                        // n++ increments n by 1
  {
     something is done
  }

The big difference is in the test part of the loop.  The user has much more control and it is much more clear as to the extent of the looping.  In the fortran/Basic loop, does it stop at n==10 with or without a loop.

In the Aurora example, the looping stop when n is not equal to or less than 10 (n>10).

My erroneous code read:
  for ( n = 1; n == 10; n++ )
   {
     something is done
   }

What happened was that the test n == 10 always fails and my bad for failed to loop
John Siino, Advanced Engineering Services and Software

GWS

February 19, 2006, 11:38:06 AM #1 Last Edit: February 19, 2006, 11:40:23 AM by GWS
I don't think there's a great problem John .. :)

In Basic:
for i = 1 to 5
print i
next i

will print 1,2,3,4,5 ..ÂÃ,  that is, the test for completion is done at the end of the loop, so the fifth pass is made.

Your statement:

for ( n = 1; n == 10; n++ )

will test and find n is less than 10, so it will not go through the loop.

Didn't you mean:

for ( n = 1; n <= 10; n++ )

all the best, :)

Graham

Tomorrow may be too late ..

Parker

The problem with testing for equality is something like this
for (i = 1.2; i <> 10; i++)
which will never break, since i will never equal ten (the i<>10 will always be true).

And Graham is right too, although the == isn't an Aurora operator, n=10 will never be true and the loop won't go through. Making it an <> demonstrates the problem.

The C style for loop gives programmers greater flexibility, something we might have to do with self controlled while loops in BASIC, but it's somewhat more dangerous, since BASIC ensures that it will exit (unless you explicitly make it not exit).

John S

there was no problem except with me and my thinking.  I was just trying to give others a heads up.   ;D
John Siino, Advanced Engineering Services and Software