Friday, January 22, 2010

Prime or Composite VB6 Program

Problem:
Create a Visual Basic 6 program that accepts an integer. Determine whether it is a prime or composite. The program should not accept letters.

Private Sub cmdDetermine_Click()
Dim intNumber As Long
Dim divisor As Long
Dim flag As Integer
Dim message As String

message = "1"
flag = 0

If Len(txtNumber.Text) = 0 Then
MsgBox "No Value Found in the textbox", vbOKOnly + vbInformation, "Input Error"
txtNumber.SetFocus
Exit Sub
End If

If IsNumeric(txtNumber.Text) Then

If Val(txtNumber.Text) > 2147483647 Then 'trap for memory overflow
MsgBox "Memory Overflow! " + vbCr + vbCr + "Input data is beyond the data range of the declared data type", vbOKOnly + vbCritical, "Memory Error"
Exit Sub
End If

If Val(txtNumber.Text) = 0 Then

lblDisplay.Caption = intNumber & " is neither prime nor composite."

ElseIf Val(txtNumber.Text) > 0 Then 'positive
intNumber = Val(txtNumber.Text)

Select Case intNumber
Case 1
lblDisplay.Caption = intNumber & " is neither prime nor composite."

Case Is >= 2
For i = 2 To intNumber Step 1
If intNumber Mod i = 0 Then
If i = intNumber Then
message = message & " and " & i
Else
message = message & ", " & i
End If
flag = flag + 1
End If
Next i

MsgBox message, vbOKOnly + vbInformation, "Number is divisible by"
If flag > 1 Then
lblDisplay.Caption = intNumber & " is composite."
Else
lblDisplay.Caption = intNumber & " is prime."
End If
End Select

Else ' negative

If Val(txtNumber.Text) < 0 Then
MsgBox "Input should be positive number", vbOKOnly + vbCritical, "Error"
txtNumber.SetFocus
Exit Sub
End If
End If

End If

End Sub


Private Sub txtNumber_KeyPress(KeyAscii As Integer)

If KeyAscii = 8 Or KeyAscii >= 48 And KeyAscii <= 57 Then
Exit Sub
Else
KeyAscii = 0
Beep
End If
End Sub

0 comments: