Write C++ program to reverse a number using while & for loop


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


Reverse a Number using while loop

  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int num, rev = 0;
  9.  
  10. //Reading a number from user
  11. cout<<"Enter any number:";
  12. cin>>num;
  13.  
  14. //finding reverse number using while loop
  15. while (num > 0) {
  16. rev = rev * 10;
  17. rev = rev + num % 10;
  18. num = num / 10;
  19. }
  20.  
  21. cout<<"Reversed number is: "<<rev;
  22.  
  23. return 0;
  24. }
  25.  

Reverse a Number using for loop

  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int num, rev = 0;
  9.  
  10. //Reading a number from user
  11. cout<<"Enter any number:";
  12. cin>>num;
  13.  
  14. //finding reverse number using for loop
  15. for (rev = 0; num > 0; num = num / 10) {
  16. rev = rev * 10;
  17. rev = rev + num % 10;
  18. }
  19.  
  20. cout<<"Reversed number is: "<<rev;
  21.  
  22. return 0;
  23. }
  24.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts