Search code examples
c#arraysdigits

separating number in array of digits C#


i am new in programming and for now only practicing with C#. So my problem is: i am trying to separate a number in a digits with array (example: number 12345 in to digits {1,2,3,4,5}). I make some code, here is it:

  int num = int.Parse(Console.ReadLine());
        int[] digits = new int[3];
        int separatedDigit = 0;


        for (int i = num; num != 0; i--)
        {
            digits[i] = num  % 10;
            num = num / 10;

        }

but it shows me error " Index was outside the bounds of the array." I suppose the problem is coming from that "for" part because it starts from position 3 and the array have only 2 (0, 1, 2). I don't know how to fix it, so can someone help me?


Solution

  • i starts out as equal to num, which in turn starts out as the number that you entered, which can be far greater than 3. For example, if I put in 123 as the input number, then the loop first tries to access digits[123] which is waaaaaay outside the bounds of that array.

    You're going to want to tweak your for loop to get i to start at a more reasonable number:

    for (int i = digits.Length - 1; num != 0; i--)
    {
        // ...
    

    Alternatively, you could start i at 0 and work your way up:

    for (int i = 0; num != 0; i++)
    {
        // ...