User Input and Searching an Array

Page 1 of 1

9 Replies - 1601 Views - Last Post: 10 June 2013 - 04:47 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=322742&amp;s=ef8df4cdd3b5738f6d82be967d4107da&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 Semus

Reputation: 14
• Posts: 126
• Joined: 27-May 13

User Input and Searching an Array

Posted 10 June 2013 - 01:17 AM

Started reading the chapter on Arrays (very interesting) and I have come to the end of the chapter now. It has asked me to perform a couple of challenges.

These challenge get harder and harder as the book goes on, which I like.

The book has asked me to write a program whereby the user should enter 10 numbers and those numbers will get stored in a one dimensional array. After getting those numbers and storing them in the array, the program asks the user for one additional number. After the user enters the additional number, the program is to search the array to see if the last number entered matches any of the numbers in the array.

So this wasn't too difficult to do. Here's my code:

```            int[] ranNum = new int[10];
int checkNum;

for (int n = 0; n < 10; n++)
{
Console.Write("Number {0}: ", n + 1);
}
Console.WriteLine("You entered: ");
foreach (int x in ranNum)
{
Console.Write("{0} ", x);
}

Console.Write("Please enter one more number: ");
bool exists = ranNum.Contains(checkNum);

if (exists)
{
Console.WriteLine("Your number {0} is in the array!", checkNum);

}
else
{
Console.WriteLine("Your number {0} is not in the array!", checkNum);
}
```

As you can see, this code already works. It might not be the most elegant solution, but it works.

The second challenge has asked me to modify this program so if the number being searched for is found multiple times, display how many times it was found.

I have seen numerous solutions online, but none of them really address this specific issue and none of the solutions have really been covered in my book as of yet so I'm kinda lost.

I know that I'm not going to get a direct answer or any code here, but I was just wondering if there was a specific direction I should be looking towards for this.

One of the solutions I found involved this code:

```foreach(var grp in nums.GroupBy(x => x).OrderBy(grp => grp.Key))
{
Console.WriteLine("{0} was found {1} times", grp.Key, grp.Count());
}
```

The problem with this (apart from never even seeing some of these entries before) is that it displays how many times ALL of the numbers in the array have been entered or found in the array. Plus, it doesn't take the last number entered in, it only takes the first 10 and compares them to the array (I believe).

Anyhow, any suggestions would be appreciated. I'm trying to think about solutions, and if I come up with one I'll be sure to post it here so you can see my progress.

This post has been edited by macosxnerd101: 10 June 2013 - 06:49 AM
Reason for edit:: Please use a descriptive title

Is This A Good Question/Topic? 0

Replies To: User Input and Searching an Array

#2 Semus

Reputation: 14
• Posts: 126
• Joined: 27-May 13

Re: User Input and Searching an Array

Posted 10 June 2013 - 02:45 AM

After thinking about this problem, I have found a rather simple solution. Although, I know there is a much simpler solution (simpler as in writing less code)

Still, my solution does work.

I know.... it's ugly isn't it lol.

```            int[] ranNum = new int[10];
int checkNum;

for (int n = 0; n < 10; n++)
{
Console.Write("Number {0}: ", n + 1);
}
Console.WriteLine("You entered: ");
foreach (int x in ranNum)
{
Console.Write("{0} ", x);
}

Console.Write("Please enter one more number: ");
int l = 0;
if (checkNum == ranNum[0])
{
++l;
}
if (checkNum == ranNum[1])
{
++l;
}
if (checkNum == ranNum[2])
{
++l;
}
if (checkNum == ranNum[3])
{
++l;
}
if (checkNum == ranNum[4])
{
++l;
}
if (checkNum == ranNum[5])
{
++l;
}
if (checkNum == ranNum[6])
{
++l;
}
if (checkNum == ranNum[7])
{
++l;
}
if (checkNum == ranNum[8])
{
++l;
}
if (checkNum == ranNum[9])
{
++l;
}
Console.WriteLine("{0} is in the array {1} times", checkNum, l);

```

This code does work. It compares the last number you entered with each number in the array (which you also entered) and displays how many times that last number is in the array.

I know this probably isn't the solution the book was looking for, but it does work. I'd be curious to see other versions of this. I know I'm overlooking something.

EDIT: this is also more than likely bad code practice and that's why I posted it here to see if others had simpler solutions that didn't involve this many lines of code.

This post has been edited by Semus: 10 June 2013 - 02:48 AM

#3 MrShoes

Reputation: 331
• Posts: 512
• Joined: 13-June 12

Re: User Input and Searching an Array

Posted 10 June 2013 - 02:54 AM

Get a number from the user and store it in a variable. In this case I've called in "inputNumber". To get the count:
```var count = numArray.Where(n => n == inputNumber).Count();
```

#4 Semus

Reputation: 14
• Posts: 126
• Joined: 27-May 13

Re: User Input and Searching an Array

Posted 10 June 2013 - 02:58 AM

MrShoes, on 10 June 2013 - 02:54 AM, said:

Get a number from the user and store it in a variable. In this case I've called in "inputNumber". To get the count:
```var count = numArray.Where(n => n == inputNumber).Count();
```

My code actually does get the number from the user and store it in a variable (checkNum).

Unless you meant something else?

Also, just a heads up, I have never seen .Where, =>, or .count use in code before. Yes, I can look them up and see what they do, but I'm just giving you a fair warning that your code won't make much sense to me unless I've studied those attributes more.

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

Re: User Input and Searching an Array

Posted 10 June 2013 - 03:10 AM

Hint. Look at the method overloads on .Count

#6 Semus

Reputation: 14
• Posts: 126
• Joined: 27-May 13

Re: User Input and Searching an Array

Posted 10 June 2013 - 03:24 AM

Adam, I'll have to get back to you when I know more about what "methods" are for and what "overloading" is. I have watched a couple of videos on the subjects, but both are slightly beyond my comprehension at the present time.

Might be awhile before I understand all of this.

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

Re: User Input and Searching an Array

Posted 10 June 2013 - 03:51 AM

.Where is part of the LINQ extension methods.

They work on IEnumerable<T> which is an interface that objects can implement if they support a way IEnumerator<T> of generate a sequence of T's.

The <T> part is called generic type parameter, and replaced with the type you need or it can inferred.

```var xs = new list<int>(); /* Implements IEnumerable<int> */
var ss = new list<string>(); /* Implements IEnumerable<string> */

```

This allow you to write method that can be applied to all types and still be type-safe and give you intellisense support, where as if you Object it could be anything.

There are example re-implementations
```public static IEnumerable<T> Where<T> (this IEnumerable<T> xs, Func< T, Bool> pred )
{
foreach(T x In xs)
{
if ( pred(x) ) { yield x };
}
}

public static IEnumerable<T> Count<T> (this IEnumerable<T> xs, Func< T, Bool> pred )
{
int c = 0;
foreach(T x In xs)
{
if ( pred(x) ) { c++; };
}
return c;
}

```

The type of the parameter pred (predicate) Func<T, Bool> is asking for function the takes in a T for input and returns a Boolean (True or False).

Lambda Functions allow to supply or define this function as an argument

Numbers.Where( n => (x % 2) == 0 ) will produce a sequence of containing odd numbers.

You also have to be aware the LINQ method are lazy evaluated. This mean they don't do any actual work of producing the answer, until you ask for it (or rationalise it).
Ie it do the generate a expression that is then use to produce / generate the answer.

This happens when you go from the IEnumerable into a more "concrete" type like:-
.ToList() /* produces a List<T> */
or .Count; /* produces an int */.

This post has been edited by AdamSpeight2008: 10 June 2013 - 03:57 AM

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

Re: User Input and Searching an Array

Posted 10 June 2013 - 03:57 AM

Eg Console.WriteLine( ) and Int.Parse

Methods are either a:-
• subroutine
returns void
``` void WriteLine( )
{
}

```

• function return something non- void
```int Count()
{
}

```

#9 Witchking

Reputation: 68
• Posts: 189
• Joined: 17-February 13

Re: User Input and Searching an Array

Posted 10 June 2013 - 04:13 AM

LINQ and lambda expressions might be beyond him at this point.

A method is a piece of code you can "call" meaning you execute that code. You might have seen something like static void nameofthemethod() { ... } or public int nameofthemethod(string s) { ... } before. You can declare these methods inside a class. For example:
Spoiler

Edit: Seems a lot of this was already covered by others, but repetition can't hurt learning i guess.

This post has been edited by Witchking: 10 June 2013 - 04:20 AM

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

Re: User Input and Searching an Array

Posted 10 June 2013 - 04:47 AM

Or based on what you've learnt so for from the book would be to use a loop of some kind (not foreach)

```  int CountMatchingNumbers( List<int> nums, int toNum )
{
int count = 0;
for(int x=0; x< nums.Count; x++)
{
if(nums[x] == lnum ){ count++; };
}
return count;
}

```

In use.
```int Found = CountMatchingNumbers( ranNum, checkNum );

```

This post has been edited by AdamSpeight2008: 10 June 2013 - 05:17 AM