Reputation: 27
I'm new to programming and I've got confused on how to display the index number of a value in an array. I want to be able to type a random number and if the number I have entered is in the array, then it should tell me what the position (index) of the number is within the array.
For example if I enter the number 6, and 6 is in my array and it's index is 4, then the output should be "That number exists, it is positioned at 4 in the array". I've tried to do this but my code is the reverse of this, for example if I type in 6, then it looks for index 6 and outputs the number corresponding to index 6.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace searcharray
{
class Program
{
static void Main(string[] args)
{
int n = 10;
Random r = new Random();
int[] a;
a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = r.Next(1, 100);
for (int i = 1; i <= n; i++)
Console.WriteLine(" a [" + i + "] = " + a[i]);
Console.ReadLine();
Console.WriteLine("Enter a number: ");
int b = Convert.ToInt32(Console.ReadLine());
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + a[b]);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
Console.WriteLine();
Console.ReadLine();
}
}
}
Upvotes: 0
Views: 835
Reputation: 1
Array.IndexOf returns -1 if the item dont exists in the array
var itemIndex = Array.IndexOf(a, b);
if (itemIndex != -1)
{
Console.WriteLine("That number exists and the position of the number is: " + itemIndex);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
Upvotes: 0
Reputation: 696
You need to use Array.IndexOf() like below:
Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));
Upvotes: 1
Reputation: 5370
You can use Array.IndexOf
(gives you the index of given value in Array) instead of a[b]
like this:
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
Upvotes: 1