I’m trying to create a program where the size of array index and its elements are from user input.
And then the program will prompt the user to search for a specific element and will display where it is.
I’ve already come up with a code:
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main(String [] args)
{
int a;
Console.WriteLine("Enter size of index:");
a= int.Parse(Console.ReadLine());
int [] index = new int [a];
for (int i=0; i<index.Length;i++)
{
Console.WriteLine("Enter number:");
index[i]=int.Parse(Console.ReadLine());
}
}
}
}
The problem with this is that I can’t display the numbers entered and I don’t have any idea how to search for an array element.
I’m thinking of using if statement.
Another thing, after entering the elements the program should display the numbers like Number 0 : 1
Is this correct: Console.WriteLine("Number"+index[a]+":"+index[i]);?
And where should I put the statement? after the for loop or within it?
What is the last line
Console.WriteLine(index[i]);? It seems like you are using the loop variable outside the loop.To display entered numbers (ie. if I understand well, the numbers in the array), you have just to walk through the array like this:
Since you want display numbers only after every number is entered, you may put this code only after finishing the loop where the user is entering the numbers:
To search for a number, you can either walk through the array again and compare each element until finding a good one, or use Linq
TakeWhile()method. (I suppose that your intent is not to use Linq, so I don’t provide any further detail in this direction.)