Random length For Loop

Just starting out? Need help? Post your questions and find answers here.
User avatar
matalog
Enthusiast
Enthusiast
Posts: 305
Joined: Tue Sep 05, 2017 10:07 am

Random length For Loop

Post by matalog »

I'm trying to understand why this doesn't work:

Code: Select all

For x=1 To 501
  CreateFile(0,Str(x))
  For t=1 To 5+Random(50000)
    WriteByte(0,Random(255))
  Next
  CloseFile(0)
  Delay(100)
Next
I understand how to get it to work, but not why it doesn't work as it is. It produces files no bigger than 1kB.


The following code does what I wanted, but I don't know why the first didn't.

Code: Select all

For x=1 To 501
  CreateFile(0,Str(x))
  r.i=Random(50000)
  For t=1 To 5+r
    WriteByte(0,Random(255))
  Next
  CloseFile(0)
  Delay(100)
Next
Axolotl
Addict
Addict
Posts: 873
Joined: Wed Dec 31, 2008 3:36 pm

Re: Random length For Loop

Post by Axolotl »

Maybe I cannot explain it entirely.

Code: Select all

  For t=1 To 5+Random(50000)
The code always creates a new value for <expression2>.
If one value <expression1> is bigger than <expression2> the loop ends. This can perhaps always be with the same value.

In the second example the <expression2> is constant during the looping.
Just because it worked doesn't mean it works.
PureBasic 6.04 (x86) and <latest stable version and current alpha/beta> (x64) on Windows 11 Home. Now started with Linux (VM: Ubuntu 22.04).
Post Reply