1

I need to find the smallest value which is larger than 0 among all integers stored in an array. I tried some of the ways of doing that on stackoverflow, but my minimal value still equals to 0 in all cases. What should I change in my code to make it work?

int[] userInput = new int[1000];
        int counter;

        Console.WriteLine ("Please input some numbers");

        for (counter = 0; counter < userInput.Length; counter++) {
            string line = Console.ReadLine ();

            if (line == "" || line == "stop") {
                break;
            } else {
                int.TryParse (line, out userInput [counter]);
            }
        }
        int min = 0;
        for(int i = 0; i < userInput.Length; i++)
        {
            if(userInput[i] > 0)
            {
                userInput[i] = min;
                break;
            }
        }
        for(int i = 0; i < userInput.Length; i++)
        {
            if(userInput[i] < min && userInput[i] > 0)
            {
                min = userInput [i];
            }
        }
        Console.WriteLine(min);
    }
}

}

I would like to do it without using LINQ.

8
  • 2
    The first for loop overwrites all values that are greater than 0 with 0. After that, it's no wonder, that you get 0 as the result... Commented Sep 2, 2013 at 12:19
  • @DanielHilgarth there is break there. Only the first item.. Commented Sep 2, 2013 at 12:19
  • are you getting correct values in your input array? since you are using int.TryParse and if an exception happens while converting the "line" the array will be filled with 0's. Commented Sep 2, 2013 at 12:19
  • It's not a homework, but I'm preparing for an exam. Commented Sep 2, 2013 at 12:20
  • People remove the important note while editing the question: I would like to do it without using LINQ. Commented Sep 2, 2013 at 12:26

9 Answers 9

2

An example. You can use Praveen's answer but this is just an alternative.

int[] numbers = { -1, 0, 1, 2, 3, 4, 5 };

public int getMinimum(int[] array)
{
    // Since you need larger than 0
    int minimum = 1;

    foreach (int elem in array)
    {
        minimum = Math.Min(minimum, elem);
    }

    return minimum;
}

So calling getMinimum(numbers) will return 1

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

1
int[] userInput = new int[1000];
int counter;

Console.WriteLine("Please input some numbers");

for (counter = 0; counter < userInput.Length; counter++)
{
    string line = Console.ReadLine();

    if (line == "" || line == "stop")
    {
        break;
    }
    else
    {
        int.TryParse(line, out userInput[counter]);
    }
}
int min = 0;
for (int i = 0; i < userInput.Length; i++)
{
    if (userInput[i] < min && userInput[i] > 0)
    {
        min = userInput[i];
    }
}
Console.WriteLine(min);

This will be find the smallest number in array.

Comments

0

Getting the max / min value among a set of values is a very popular (and eventually trivial) programming problem.

Your post is a specialized instance of the same problem. In your case you want to get the minimum positive value among a set of integers.

Your code is almost correct. Only replace the following line in the second for block:

 min = userInput[i];

4 Comments

What about if the first element is 0?
@I4V: The second loop searches for the first element > 0. The error in the original code is to assign min to that value instead of the other way round. After the correction, min is > 0 if a value > 0 exists in the array. The remaining loop is then correct.
As an optimization I would propose to limit the second and third loop to counter instead of userInput.Length (wich is always 1000). Also, the third loop could start where the second one stops.
Wow, three downvotes from people who can't read code... OK, OK, I'll stop the spam and move on :-)
0

try this:

   int min;
    int found_positive = 0; // 1 if there's positive element
    for(int i = 0; i < userInput.Length; i++)
    {
      if(userInput[i]>0){
        if(found_positive==1){
          if(userInput[i]<min) min=userInput[i];
        }else{
          found_positive=1;
          min = userInput[i];
        }
      }
    }

Comments

0
    int[] userInput = new int[1000];
    int counter;

    Console.WriteLine ("Please input some numbers");

    for (counter = 0; counter < userInput.Length; counter++) {
        string line = Console.ReadLine ();

        if (line == "" || line == "stop") {
            break;
        } else {
            int.TryParse (line, out userInput [counter]);
        }
    }
    var min = userinput.Length>0?userInput[0]:0;
    for(int i = 1; i < userInput.Length; i++)
    {
        if(userInput[i] < min && userInput[i] > 0)
        {
            min = userInput [i];
        }
    }

This much should suffice...

Comments

0

Do that with LINQ, in a single line:

int[] userInput = new int[1000];

var result = userInput.OrderBy(i=>i).SkipWhile(i=>i<=0).First()

3 Comments

Have you read this part: I would like to do it without using LINQ.
yeah, but only after posting my answer :)
BTW: Why do you need to sort the input? userInput.Where(x => x > 0).DefaultIfEmpty().Min()
0

You have to limit the list to all entries above zero and then look for the lowest minimum value which is closest to zero using the LINQ method Min(). See a non-LINQ version as a second example below.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please input some numbers. Use SPACE as separator");
            string line = Console.ReadLine();
            var userInput = new List<int>();

            foreach (string entry in line.Split(' '))
            {
                int number;
                if (!string.IsNullOrEmpty(entry) && int.TryParse(entry, out number))
                    userInput.Add(number);
            }

            const int lowest = 0;

            Console.WriteLine("The lowest number above {0} is: {1}", lowest, userInput.Where(n => n > lowest).Min());

            Console.WriteLine("Press any key to finish.");
            Console.ReadKey();
        }
    }
}

Non-LINQ example

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please input some numbers. Use SPACE as separator");
            string line = Console.ReadLine();
            var userInput = new List<int>();

            int min = int.MaxValue;

            if (!string.IsNullOrEmpty(line))
            {
                foreach (string entry in line.Split(' '))
                {
                    int number;
                    if (!string.IsNullOrEmpty(entry) && int.TryParse(entry, out number))
                        userInput.Add(number);
                }
            }

            const int lowest = 0;
            foreach(int number in userInput)
            {
                if (number > lowest)
                    min = Math.Min(number, min);
            }

            Console.WriteLine("The lowest number above {0} is: {1}", lowest, min);

            Console.WriteLine("Press any key to finish.");
            Console.ReadKey();
        }
    }
}

Comments

0

In your current solution you change the first instance that's above 0 to 0:

if(userInput[i] > 0)
{
    userInput[i] = min;
    break;
}

You need to change it to

min = userInput[i];

Although this for loop is completely unnecessary anyway (and adds complexity). You'd be better off setting min to the maximum possible int value using int.MaxValue so that in the next for loop

if(userInput[i] < min && userInput[i] > 0)
{
    min = userInput [i];
}

the first value will be less than (or at least equal to) min;

Comments

-1
array1.Min()

See this

With the Min method we find the minimum element or the minimum value after a transformation.

3 Comments

You have to select all values above 0 first and then use Min(). So it's array1.Where(n=>n>0).Min()
@Matthias: But the OP wants no LINQ
@TToni He would like to ;) so no must ;) *kidding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.