working algorithm using c-arrays