Reputation: 55
I have created a console program using vb . Net to calculate an entered number factorial, but it only executes once before I exiting, how can I make the program run until the user wants to exit? Here is the code I used
Module factorial
Dim factorial = 1, i, num As Integer
Sub Main()
Console.Write("Enter a number to find a factorial of it : ")
num = Console.ReadLine()
factorial = 1
For i = 1 To num
factorial = factorial * i
Next
Console.WriteLine("Factorial of {0} is {1}", num, factorial)
End Sub
End Module
Upvotes: 0
Views: 90
Reputation: 4534
To process more than one input from the user, you need to put your code inside a loop. You will need a way for the user to indicate that it's time to finish (for example by typing "Quit" instead of a number.
You should also make sure the string entered by the user is valid before converting it to an Integer. You can do that by using Integer.TryParse.
Finally, you should allow for the possiibility that the factorial is very large. Using a Long instead of an Integer for the factorial will help, but the factorial may still be too large, so you can use Try/Catch to check for an Overflow and send an error message. If you want to handle numbers of any size, you can research BigInteger.
Module factorial
Sub Main()
Do
Console.Write("Enter a number to find its factorial, or Quit to end the program:")
Dim inString As String = Console.ReadLine
If inString.ToUpper = "QUIT" Then Exit Sub
Dim num As Integer
If Integer.TryParse(inString, num) Then
Dim factorial As Long = 1
Try
For i As Integer = 2 To num
factorial *= i
Next
Console.WriteLine("Factorial of {0} is {1}", num, factorial)
Catch ex As OverflowException
Console.WriteLine("Factorial of {0} is too large", num)
End Try
End If
Loop
End Sub
End Module
Upvotes: 1
Reputation: 4730
Console.ReadKey()
will allow you to make program waiting for pressing any key.
If you need your program calculating more and more factorials, you should wrap all the code into infinite loop like that:
Do
Something
Loop
Upvotes: 1