Adam Wayne
Adam Wayne

Reputation: 1

Having trouble with my code on searching for an element of an array in C#

I've been struggling with this bit of code for a while, I can't seem to find out where I'm going wrong. Basically I want to search through an Array using an Integer and if it matches an element inside that array, it returns a bool variant as true. It's quite self explanatory but can't for the life of me figure it out! Any ideas?

Here is the code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayProject
{
    class ArrayProgram
    {
        public bool ElementAt(int[] intArray, int valueToBeFound)
        {
            bool intAt = false;
            int numberTofind;

            Console.WriteLine("Please enter the number you wish to search for within the array: ");
            numberTofind = Convert.ToInt32(Console.ReadLine());


            foreach (int x in intArray)
            {
                if (x == numberTofind)
                {
                    intAt = true;
                }
                else
                {
                    intAt = false;
                }
            }
            if (intAt == true)
            {
                Console.WriteLine("{0} is in the array!", numberTofind);
            }
            else
            {
                Console.WriteLine("{0} is not in the array.", numberTofind);
            }

            return intAt;
        }
        public void RunProgram()
        {
            int[] intArray = { 20, 30, 40, 50, 60, 50, 40, 30, 20, 10 };
            int numberTofind = 0;

            ElementAt(intArray, numberTofind);

        }  // end RunProgram()

        static void Main(string[] args)
        {
            ArrayProgram myArrayProgram = new ArrayProgram();
            myArrayProgram.RunProgram();

            Console.WriteLine("\n\n===============================");
            Console.WriteLine("ArrayProgram: Press any key to finish");
            Console.ReadKey();
        }
    }
}

Upvotes: 0

Views: 81

Answers (4)

xplatinumx15
xplatinumx15

Reputation: 101

You could do this pretty easy with Linq.

using System.Linq;

public static string test(int[] numberArray, int find) 
{ 
            bool s = false;
            numberArray.ToList().ForEach(x => { if (x == find) s = true; }); 
            return s ? "It contains it." : "Can't find it.";
}

However there is a method for this. You can use .Contains with an array as a person said above me.

Upvotes: 1

Gabriel Em
Gabriel Em

Reputation: 133

If you want to keep your implementation, try this:

class ArrayProgram
{
    public bool ElementAt(int[] intArray, int valueToBeFound)
    {
        foreach (int x in intArray)     
            if (x == valueToBeFound)        // if you found your value in the array
                return true;                // you return true

        return false;   // otherwise, by this point the foreach has looped through all the elements and hasn't once entered in the above if (so it hasn't found your value) = you return false
    }

    public void RunProgram()
    {
        int[] intArray = { 20, 30, 40, 50, 60, 50, 40, 30, 20, 10,99 };
        int numberTofind;

        // I noticed that you're not using the numberTofind value either, so:

        Console.Write("Please enter the number you wish to search for within the array: ");
        numberTofind = Convert.ToInt32(Console.ReadLine());

        // and since you made a function that returns true if your value has been found, you might as well use it like this

        if(ElementAt(intArray, numberTofind)) // if the function returns true
            Console.WriteLine("{0} is in the array!", numberTofind);
        else
            Console.WriteLine("{0} is not in the array.", numberTofind);
    }  // end RunProgram()

    static void Main(string[] args)
    {
        ArrayProgram myArrayProgram = new ArrayProgram();
        myArrayProgram.RunProgram();

        Console.WriteLine("\n\n===============================");
        Console.WriteLine("ArrayProgram: Press any key to finish");
        Console.ReadKey();
    }
}

Upvotes: 0

TowerFan
TowerFan

Reputation: 210

The problem is that your loop continues checking elements and updating intAt even if it finds the element you're looking for.

If the array was {1, 2, 3, 4} and your code was searching for 1, it would first check index 0. This is a match, so intAt becomes true. Next it will try index 1. This one isn't a match, so it sets intAt to be false. Then it will try indices 2, 3, etc. never finding the match.

Upvotes: 1

Dmitriy Zapevalov
Dmitriy Zapevalov

Reputation: 1357

        int[] intArray = { 20, 30, 40, 50, 60, 50, 40, 30, 20, 10 };
        int numberToFind = 0;

        //variant 1 (using System.Linq):
        bool bInside1 = intArray.Contains(numberToFind);

        //variant2
        bool bInside2 = Array.IndexOf(intArray, numberToFind) >= 0;

And if you want to write your own function:

    bool IsInside(int[] arrToSearch, int nToSearch)
    {
        foreach (int n in arrToSearch)
        {
            if (n == nToSearch)
                return true;
        }
        return false; //not found
    }

Upvotes: 1

Related Questions