+ 1

Could some one please explain clearly how to convert numbers to array using the below method

Convering from int to int array do {  arr[i] = number % 10;  number /= 10;  i++;  } while (number != 0); 

31st Jul 2019, 10:03 AM
Saitek
Saitek - avatar
3 Answers
+ 1
that code takes every digit from your number and puts it into an array. assuming i equals 0 at the begining and the array has enough space... in the begining i is equal to 0 so the value gained from "number % 10" is stored at the begining of the array. "number % 10" returns the last digit of an number. (the % is the modulo-operator and returns actually the remainder of an division, but % 10 is the same as the last digit of an number). the expresion number % 10 doesn't change the number ao we need to remove the last digit we just stored to the array, this is done by simply dividing the number by 10. to prevent storing the next value again at index 0 in the array we increase i by 1. the process then gets repeated until the number is 0 meaning there is nothing left to extract. the do-while is probably used so the array isn't empty when number is equal to 0... hope this helped! happy coding!! 😄
31st Jul 2019, 1:19 PM
Anton Böhler
Anton Böhler - avatar
+ 1
Thanks
5th Aug 2019, 10:09 AM
Saitek
Saitek - avatar
0
It divides the number by 10, and the '%' symbols means that you are taking the rest of the division. Then it reduces the number to its first cipher by dividing it by 10 as an integer. For example, considering 24: arr[0]=4(that is the rest of 24/10) number=2(which is 24/10, but as an integer) i++ Then, on the second part of the loop: arr[1]=2 number=0 i++
31st Jul 2019, 1:16 PM
Davide Mornatta
Davide Mornatta - avatar