I'm trying to add every digit of the number 12345
to an array such that it appears like that [5,4,3,2,1]
but it prints nothing. I need to know what is the reason for that?
var number: Int = 12345
var x: Int = number 1
var array: [Int] = []
while number >= 0 && number < x {
let j: Int = 10
let decimal = number % j
array.append(decimal)
}
print(array)
CodePudding user response:
The issue there is that your while loop will never end because you never mutate number
and said greater or EQUAL to zero. You need to mutate number
and change your while loop to only greater than zero condition. You code can be simplified as:
var number = 12345
var array: [Int] = []
while number > 0 {
array.append(number % 10)
number /= 10
}
CodePudding user response:
As @matt said in a comment, your program is running an infinite loop because you never change number
, so your while statement continues to run with a true statement.
I would convert the number to a String
, then append its digits to your array. Here is the code that you should use:
let number: Int = 12345
var array: [Int] = []
for char in String(number).reversed() {
array.append(Int(String(char))!)
}
print(array)