Skip to content

Instantly share code, notes, and snippets.

@Lablnet Lablnet/reverse_number.cpp
Last active Mar 27, 2019

Embed
What would you like to do?
C++ program to reverse the input number by for, while and do while loop
//By Muhammad Umer Farooq
#include <iostream>
namespace ReverseNumber
{
int rem = 0; int rev = 0;
int for_loop(int n)
{
for (n; n != 0; n /= 10) { // for (n; n > 0; n /= 10), for (;n != 0; n /= 10)
rem = n % 10;
rev = rev * 10 + rem;
}
return rev;
}
int while_loop(int n)
{
rem = rev = 0;
while (n != 0) { //while (n > 0)
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
return rev;
}
int do_while_loop(int n)
{
rem = rev = 0;
do {
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
} while(n != 0); // while (n > 0);
return rev;
}
}
int main()
{
int n;
std::cout << "Enter number to reverse \t";
std::cin >> n;
std::cout << "For loop: " << ReverseNumber::for_loop(n) << std::endl;
std::cout << "While loop: " << ReverseNumber::while_loop(n) << std::endl;
std::cout << "Do While loop: " << ReverseNumber::do_while_loop(n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.