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.
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?
4 answers
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()
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.
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.