WAP to check if number is in array using VBA.
Dim a(4), n, no As Integer
Console.WriteLine("Enter a no.")
For n = 0 To 4
a(n) = Console.ReadLine
Next
Console.WriteLine("Enter a no. to search")
no = Console.ReadLine
For n = 0 To 4
If a(n) = no Then
Console.WriteLine("No was found")
Else
Console.WriteLine("No wasn't found")
End If
Next
Console.ReadLine()
How can I make it effective?It prints found and not found for every integer.How make it print found once only?
Note that you have confused = with ==, so you are changing the array.
So, each no will be found, and then the other array elements will not match.
Do not execute a print each time through the loop; only print after you have checked the array.
Once you have found the number, set a flag and exit the loop.
Once out of the loop, check the flag, and print found/notfound depending on whether the flag has been set or not.
Dim a(4), n, no, found As Integer
Console.WriteLine("Enter a no.")
For n = 0 To 4
a(n) = Console.ReadLine
Next
Console.WriteLine("Enter a no. to search")
no = Console.ReadLine
For n = 0 To 4
If a(n) = no Then
found = True
Else
found = False
End If
Next
If found = True Then
Console.WriteLine("No was found")
Else
Console.WriteLine("No wasn't found")
End If
Console.ReadLine()
My input was 1,2,3,4,5 but it worked only with 5.why?
once you find it, you need to exit the loop.
Otherwise, all the misses will reset the flag.
Actually, you should set found = false before the loop.
Then, when you find a match, set it to true and exit the loop.
No need for an Else case at all. If you get past the loop, either found will still be false, or it will have been set to true exactly once.
To make the code print "No was found" once only, you need to add a flag variable that keeps track of whether the number was found or not. Here's an updated version of the code that achieves that:
```vba
Dim a(4) As Integer
Dim n, no As Integer
Dim found As Boolean
found = False
Console.WriteLine("Enter five numbers:")
For n = 0 To 4
a(n) = Console.ReadLine
Next
Console.WriteLine("Enter a number to search:")
no = Console.ReadLine
For n = 0 To 4
If a(n) = no Then
found = True
Exit For
End If
Next
If found Then
Console.WriteLine("Number was found.")
Else
Console.WriteLine("Number was not found.")
End If
Console.ReadLine()
```
In this updated code, we added a boolean variable called `found` that is initially set to `False`. Inside the `For` loop, if the number is found, we set `found` to `True` and exit the loop using the `Exit For` statement. After the loop, we check the value of `found` and print the appropriate message accordingly.