Semplifing the code logic by replacing "while" with "if-else" block