Alter
Alter

Reputation: 65

A simple iteration with if else

Iterating through an array of strings i want it to write a specific line if one of the elements coresponds to the condition. The problem is with the else condition. It is written as many times as the length of the array and i only need it written once

 public static void FindSandy(params string[] ocean)
    {
        for (int i = 0; i < ocean.Length; i++)
        {
            if (ocean[i] == "Sandy")
            {
                Console.WriteLine("We found Sandy on position {0}", i);
            }
            else
            {
                Console.WriteLine("He was not here");
            }


        }


    }

    static void Main(string[] args)
    {

        {
            FindSandy("Bob","Bella", "Sandy", "Nemo", "Dory");
        }
    }

Upvotes: 0

Views: 124

Answers (4)

Tor
Tor

Reputation: 631

What about if you just return if you found it?

public static void FindSandy(params string[] ocean)
{
    for (int i = 0; i < ocean.Length; i++)
    {
        if (ocean[i] == "Sandy")
        {
            Console.WriteLine("We found Sandy on position {0}", i);
            // Found, you can return from method.
            return; 
        }
    }

    // Not found, write the 'not found' message.
    Console.WriteLine("He was not here");
}

Upvotes: 3

Rufus L
Rufus L

Reputation: 37020

The simplest way to change your code to handle this is to create a variable that tracks the index where Sandy is found, initialize it to an invalid value (like -1), and then set it to the actual value in your if block (and we can also add a break; statement to exit the loop as soon as we find him).

Then, we output a string based on the value of the position variable:

public static void FindSandy(params string[] ocean)
{
    int position = -1;

    for (int i = 0; i < ocean?.Length; i++)
    {
        if (ocean[i] == "Sandy")
        {
            position = i;
            break;
        }
    }

    if (position > -1)
    {
        Console.WriteLine("We found Sandy on position {0}", position);
    }
    else
    {
        Console.WriteLine("He was not here");
    }
}

The code can be simplified a little with the System.Linq extension methods Select (to select the name and then index) and FirstOrDefault which returns the first item that meets a condidion, or the default for the type (which is null):

public static void FindSandy(params string[] ocean)
{
    var position = ocean?.Select((name, index) => new {name, index})
        .FirstOrDefault(item => item.name == "Sandy");

    Console.WriteLine(position == null 
        ? "He was not here" 
        : $"We found Sandy on position {position.index}");
}

Upvotes: 3

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

To solve your issue, you could add a new boolean variable (e.g. weFoundSandy): if you find an occurrence, set this variable to true, use the break statement (to reduce the iterations of the for) and, at the end, use this boolean variable to determine which message to display.

public static void FindSandy(params string[] ocean) {
  bool weFoundSandy = false;
  for (int i = 0; i < ocean.Length; i++) {
    if (ocean[i] == "Sandy") {
      Console.WriteLine("We found Sandy on position {0}", i);
      weFoundSandy = true;
      break;
    }
  }
  if (!weFoundSandy) {
    Console.WriteLine("Sandy was not here");
  }
}

or, you could simply use the C# Array.IndexOf method, e.g.:

public static void FindSandy(params string[] ocean) {
  int indexOfSandy = Array.IndexOf(ocean, "Sandy");
  if (indexOfSandy >= 0) {
    Console.WriteLine("We found Sandy on position {0}", indexOfSandy);
  } else {
    Console.WriteLine("Sandy was not here");
  }
}

Upvotes: 0

Therlysddd
Therlysddd

Reputation: 21

You can use the keyword break to exit the for loop :

public static void FindSandy(params string[] ocean)
    {
        for (int i = 0; i < ocean.Length; i++)
        {
            if (ocean[i] == "Sandy")
            {
                Console.WriteLine("We found Sandy on position {0}", i);
                break;
            }
            else if (i == ocean.Length - 1)
            {
                Console.WriteLine("He was not here");
                break;
            }
        }
    }

Upvotes: 1

Related Questions