Merge while loop and if-else-if functionality