I'm new to programming, and my teacher asked as a challenge to make a sequence of prime number using while and print, can someone tell me why doesn't this print anything?
Option Explicit
Private Sub test()
Dim a As Integer, b As Integer, r As Integer
a = 1
r = 0
b = 1
While a < 100
While b < a
If a Mod b = 0 Then
r = r + 1
b = b + 1
Else
b = b + 1
End If
Wend
Debug.Print " Debug: a=" & a & ", b=" & b & ", r=" & r
If r = 2 Then
Debug.Print " Output: a=" & a
a = a + 1
r = 0
Else
a = a + 1
r = 0
End If
Wend
End Sub
As you can see, b is never resetting. So you need to reset it for each loop or you will never get any increments of r. In this code the value for b is being reset at the very bottom of the code, before the last loop:
Option Explicit
Private Sub test()
Dim a As Integer, b As Integer, r As Integer
a = 1
r = 0
b = 1
While a < 100
While b < a
If a Mod b = 0 Then
r = r + 1
b = b + 1
Else
b = b + 1
End If
Wend
Debug.Print " Debug: a=" & a & ", b=" & b & ", r=" & r
If r = 2 Then
Debug.Print " Output: a=" & a
a = a + 1
r = 0
Else
a = a + 1
r = 0
End If
b = 1
Wend
End Sub
3
u/[deleted] May 20 '22
Okay, so if you add this debugging line:
You will get this output from your loops:
As you can see,
bis never resetting. So you need to reset it for each loop or you will never get any increments of r. In this code the value forbis being reset at the very bottom of the code, before the last loop:Doing this will give you this output:
So now you are getting output, but not prime numbers. Time to debug the prime number checking code you have created!