Search code examples
c#arraysdigits

Why can't I correctly assign variables to an Array?


So I'm writing a program that inputs a number (binary) then assigns each digit of that input into an array.

static void Main(string[] args)
{
    Console.Write("Please enter a binary number: ");
    String input = Console.ReadLine();
    int inputLength = input.Length;
    int nInput = Convert.ToInt32(input);
    int[] digits;
    digits = new int[inputLength];

    int remain = 10;
    int divider = 1;
    for (int i = 0; i > inputLength; i++)
    {
        digits[i] = (nInput % remain) / divider;
        remain = remain * 10;
        divider = divider * 10;
    }
    Console.WriteLine("Demo number  " + digits[0]);
}

However, it seems like all my arrays have a value of 0, whenever I run the code. Why is that?

So if my input is 11010, digit[0] should be 0. digit[1] should be 1. digit[2] should be 0. digit[3] should be 1. digit[4] should be 1.


Solution

  • The Loop is not executing since its condition always false; So you are getting its default value, change the condition as i < inputLength;

    If you do so and give the input as "123"

    The output on the console will be : Demo number 3; And the array Will be

    digit[0]=3
    digit[1]=2
    digit[2]=1
    

    Few suggestions to improve your code:

    • use int.TryParse(); instead for Convert.ToInt32(); for avoid throwing conversion exceptions. you can see a comparison here
    • Since the numbers are in an array you can reverse them using Array.Reverse()

    That is ..

            String input =Console.ReadLine();
            int nInput;
            int inputLength = input.Length;
            if (int.TryParse(input, out nInput))
            {
                int[] digits = new int[inputLength];
                Array.Reverse(digits);
                Console.WriteLine("Reversed Number is:{0}",String.Join( "",digits));
            }
            else { Console.WriteLine("Wrong input"); }