Write a visual basic that calculates factors of a given number and display all the factors in alist box
Question
Write a Visual Basic that calculates factors of a given number and display all the factors in a list box.
Solution
Here is a simple Visual Basic program that calculates the factors of a given number and displays them in a ListBox:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim num As Integer
num = Integer.Parse(TextBox1.Text)
ListBox1.Items.Clear()
For i As Integer = 1 To num
If num Mod i = 0 Then
ListBox1.Items.Add(i)
End If
Next
End Sub
End Class
Here's a step-by-step explanation of the code:
-
The code begins with the declaration of the class
Form1
. This is the main form where the controls (like the TextBox and ListBox) are placed. -
Inside the class, a
Button1_Click
event is defined. This event is triggered when the user clicks onButton1
. -
Inside the
Button1_Click
event, an integer variablenum
is declared. This variable will hold the number entered by the user inTextBox1
. -
The
ListBox1.Items.Clear()
line clears the ListBox of any previous items. -
A
For
loop is then started which runs from 1 to the number entered by the user. -
Inside the loop, an
If
statement checks if the current numberi
is a factor ofnum
(i.e., ifnum
divided byi
leaves no remainder). -
If
i
is a factor ofnum
, it is added to the ListBox usingListBox1.Items.Add(i)
. -
The loop then continues with the next number.
-
The
End Sub
andEnd Class
statements mark the end of theButton1_Click
event and theForm1
class, respectively.
Similar Questions
List all the factors of $$85. Write them all on the one line separated by a comma.
List all the factors of $$110. Write them all on the one line separated by a comma.
HCFWrite a program to find out the Highest Common Factor for given two numbers.
In Visual Basic.net, there are 2 types of constants. Describe them using examples(6 Marks
Write a program to count the number of prime factors of a given positive integer and calculate the difference between the number and the lowest prime factor.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.