... but your solution does not do what the OP wants:
Only print directory names (yours also prints file names).
Do not read all the names into an array at once -- just operate on each name, one at a time (yours stuffs all names into an array, then it loops through the array).