-5

I have an assingment and I'm a bit lost. In an array of 10 (or less) numbers which the user enters (I have this part done), I need to find the second smallest number. My friend sent me this code, but I'm having a hard time understanding it and writing it in c#:

Solved it!!! :

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int vnesena;
            int? min1 = null;
            int? min2 = null;
            for(int i=1; i<11; i=i+1)
            {
                Console.WriteLine("Vpiši " + i +"." + " število: ");
                vnesena = Convert.ToInt32(Console.ReadLine());

                if (vnesena == 0)
                {
                    break;

                }
                if (min1 == null || vnesena < min1)
                {
                    min2 = min1;
                    min1 = vnesena;
                }
                else if (vnesena != min1 && (min2==null || vnesena<min2))
                {
                    min2 = vnesena;
                }



            }


            if (min1 == null || min2 == null)
            {
                Console.WriteLine("Opozorilo o napaki");
            }
            else
            {
                Console.WriteLine("Izhod: " + min2);
            }


            Console.ReadKey();


        }
    }
}
Rene Vucko
  • 33
  • 1
  • 10

3 Answers3

3

That code is too complicated, so try something like this.

int[] numbers = new int[10];
for (int i = 0; i < 10; i++)
{
    numbers[i] = int.Parse(Console.ReadLine());
}
Array.Sort(numbers);
Console.WriteLine("Second smallest number: " + numbers[1]);

If the code isn't too obvious, let me explain:

  1. Declare an array of 10 integers
  2. Loop 10 ten times and each time, ask for user input & place input as an integer to the array
  3. Sort the array so each number is in the number order (smallest first, biggest last).
  4. The first integer is smallest (input at index 0, so numbers[0]) and the second smallest is obviously numbers[1].

Of course, for this piece of code to work, you have to use this code in console program.

As you didn't mention if you are allowed to use built in sorting functions etc, I assume that Array.Sort() is valid.

EDIT: You updated your topic so I'll change my code to match criterias.

int[] numbers = new int[10];
bool tooShortInput = false;
for (int i = 0; i < 10; i++)
{
    int input = int.Parse(Console.ReadLine());
    if (input != 0)
    {
        numbers[i] = input;
    }
    else
    {
        if (i == 2)
        {
            Console.WriteLine("You only entered two numbers!");
            tooShortInput = true;
            break;
        }
        else
        {
            for (int j = 0; j < 10; j++)
            {
                if (numbers[j] == 0)
                {
                    numbers[j] = 2147483647;
                }
            }
            break;
        }
    }
}
// Sort the array    
int temp = 0;

for (int write = 0; write < numbers.Length; write++) {
    for (int sort = 0; sort < numbers.Length - 1; sort++) {
        if (numbers[sort] > numbers[sort + 1]) {
        temp = numbers[sort + 1];
        numbers[sort + 1] = numbers[sort];
        numbers[sort] = temp;
        }
    }
}

if (!tooShortInput) 
{
    Console.WriteLine("Second smallest number: " + numbers[1]);
}

If you don't understand the updated code, let me know, I will explain.

NOTE: This is fastly coded and tested with android phone so obviously this code isn't 5 star quality, not even close, but it qualifies :-).

Regards, TuukkaX.

Yytsi
  • 424
  • 1
  • 5
  • 14
  • 1
    @ReneVucko Updated my code. Doesn't use built in sorting functions and works perfectly. The code is very poor to say the least, but it works. Sorting mechanism in the code is called 'bubble sort'. – Yytsi Nov 12 '15 at 19:03
2

To paraphrase the code given:

  1. Set 2 variables to nothing. (This is so that there can be checks done later. int? could be used if you want to use null for one idea here.
  2. Start loop through values.
  3. Get next value.
  4. If the minimum isn't set or the new value is lower than the minimum, replace the second lowest with the former lowest and lowest with the new value that was entered.
  5. Otherwise, check if the new value isn't the same as the minimum and if the minimum isn't set or the entered value is lower than the second lowest then replace the second lowest with this new value.
  6. Once the loop is done, if either minimum value isn't filled in then output there isn't such a value otherwise output the second lowest value.

Imagine if you had to do this manually. You'd likely keep track of the lowest value and second lowest value as you went through the array and the program is merely automating this process. What is the problem?


This is a rough translation of what your friend gave you that isn't that hard to translate to my mind.

        int enteredValue;
        int? smallest = null, secondSmallest = null;

        for (int i = 0; i < 10; i = i + 1)
        {
            Console.WriteLine("Vpiši " + i+1 + " število: ");
            enteredValue = Convert.ToInt32(Console.ReadLine());
            if (smallest==null || enteredValue<smallest) {
                  secondSmallest=smallest;
                  smallest = enteredValue;
            } else if (enteredValue!=smallest && enteredValue<secondSmallest) {
                  secondSmallest= enteredValue;
            }
        }
JB King
  • 11,860
  • 4
  • 38
  • 49
  • Side note: Explanations of proper algorithms can be found by https://www.bing.com/search?q=c%23+select+kth+min like [How to find the kth largest element in an unsorted array of length n in O(n)?](http://stackoverflow.com/questions/251781/how-to-find-the-kth-largest-element-in-an-unsorted-array-of-length-n-in-on) – Alexei Levenkov Nov 12 '15 at 17:44
  • 1
    How close to being spoonfed of an answer are you expecting here? Is there some part you want elaborated? I've even translated the friend's algorithm. If you want more I'd suggest hiring private tutors to do the work for you as this is getting pretty close to that, IMO. – JB King Nov 12 '15 at 18:22
  • if (min1 = null || vnesena < min1) operand || cannot be applied to operands of null – Rene Vucko Nov 12 '15 at 18:31
0

Why use a loop and not take advantage of the Array.Sort method?

        int[] numbers = new int[4] { 4, 2, 6, 8 };

        Array.Sort(numbers);

        int secondSmallestNumber = numbers[1];
Tony P
  • 46
  • 3