Jump to content

converting an integer to an array of digits

- - - - -

  • Please log in to reply
5 replies to this topic

#1
khaled_attia

khaled_attia

    Newbie

  • Members
  • Pip
  • 2 posts
Hi guys,
I want to know if there is a way in C# to convert an integer
to an array of digits so that I can perform (Mathematical) operations
on each digit alone

ex:
I need the user to input an integer i.e 123 , 456
then the program creates two arrays of three element {1,2,3} , {4,5,6}
then add each digit in one array to its corresponding digit in the second array,
stores the results in a new array
thnx in advance

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
Your easiest way of doing this would be to simply accept a string of characters from the user and scan it one character at a time, parsing those characters to Ints as you store them in your array.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#3
khaled_attia

khaled_attia

    Newbie

  • Members
  • Pip
  • 2 posts
would you please provide an example , because it doesn't work for me

#4
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
Use Console.Read to read characters one by one. You can put this read method call in the conditional of a while loop, and set it to execute the loop only when it is not equal to -1, because Console.Read returns -1 when the input buffer is empty.

You should check the value of this character to make sure it is a digit. You can use Convert.ToChar(i), where i is an Int32, to convert the integer returned by Console.Read to a Character. Then, you can call Char.IsDigit© on that character to make sure it's a digit.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#5
Abbath1349

Abbath1349

    Newbie

  • Members
  • PipPip
  • 22 posts
write this function :)

public static int[] transformation(int x)

        {

            string s,numbers = x.ToString();

            char[] num = numbers.ToCharArray();

            int L=num.Lenght;

            int[] x1 = new int[L];

            for (int i = 0; i <L; i++)

            {

                s = num[i].ToString();

                x1[i] = Convert.ToInt32(s);

            }

            

            return x1;

        }



#6
TCristoforo

TCristoforo

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
Also, if you prefer to use an integer, you can use the mod(%) operator




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users