In: Computer Science
I am trying to write code for a program in Visual Studo using Visual Basic programming language that computes the factorial of an entered number by using a For Loop. My problem is that it keeps re-setting the variable for Factorial. Below is my code if anyone can help. I want it to multiply the given number by that number - 1, then continuing to do so until it hits zero without multiplying by zero.
Private Sub BtnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim Factorial As Integer = Integer.Parse(txtNumber.Text)
For i = Factorial To 2 Step -1
Factorial = i * (i - 1)
Next
txtFactorial.Text = Factorial.ToString()
End Sub
Answer :-
Your logic and code is correct but just look at main line Factorial = i * (i - 1) and process of for loop. In for loop the variable is initialized only once. So, for first time the i and factorial will be same and second and onwards i will be decreased by 1 but you are assigning each time the new calculated value to factorial that is i * (i - 1) and we need the old value for further calculation. which is stored in factorial variable. so, we can get the old calculated value in factorial variable. where as in i we will get only decremented value. and we need both decremented and the old calculated value. So, we will use factorial as well as the decremented value that is i for multiplication. And then the factorial variable will be updated with new calculation. And that new value also we will get in next iteration for again further calculation.
Change :- the line as Factorial = Factorial * (i - 1)
So, the code will be as follows :-
Private Sub btnCalculate_Click(sender As Object, e As EventArgs)
Handles btnCalculate.Click
Dim Factorial As Integer = Integer.Parse(txtNumber.Text)
For i = Factorial To 2 Step -1
Factorial = Factorial * (i - 1)
Next
txtFactorial.Text = Factorial.ToString()
End Sub