# it's a program to find reverse of a number using for loop

Page 1 of 1

## 1 Replies - 19966 Views - Last Post: 05 September 2008 - 11:01 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=62865&amp;s=764246f6fe6982df9fb9ffc4ad25baf7&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 harsimran.grewal11

Reputation: 1
• Posts: 1
• Joined: 05-September 08

# it's a program to find reverse of a number using for loop

Posted 05 September 2008 - 10:30 PM

```#include<iostream.h>
int main()
{
int num;
int rev=0,rem;
cout<<endl<<"enter a number";
for(cin>>num;num>0;num/=10)
{
rem=num%10;
rev=rev*10+rem;
}
cout<<endl<<"reverse is"<<rev;
return(0);
}

```

*edit: Please use code tags in the future, thanks!

This post has been edited by Martyr2: 05 September 2008 - 10:57 PM

Is This A Good Question/Topic? 1

## Replies To: it's a program to find reverse of a number using for loop

### #2 Martyr2

• Programming Theoretician

Reputation: 4860
• Posts: 13,176
• Joined: 18-April 07

## Re: it's a program to find reverse of a number using for loop

Posted 05 September 2008 - 11:01 PM

Well as you might be aware of, the only palindromes in the first 100 numbers are those which are double numbers... 11, 22, 33 etc. You might want to try 1-1000 or more.

I have taken your code, refactored out the palindrome functionality into its own function. Then from a for loop we loop through a range of numbers and give it to the function to test. If it returns true, then it is a palindrome so print it to screen.

```#include<iostream>
using namespace std;

// Declaration of our new isPalindrome function
bool isPalindrome(int number);

int main()
{

// For loop which loops from 1 - 100 looking for palindromes
// Then prints them on screen when found
// As you can imagine only palindromes in the first 100
// are those which are double numbers... 11, 22, 33 etc
for (int i = 1; i <= 100; i++) {
if (isPalindrome(i)) {
cout << i << " is a palidrome" << endl;
}
}
return(0);
}

// We refactored your palindrome algorithm and modified it a little
// It checks numbers greater than a single digit and checks the
// reverse against the original number passed in.

bool isPalindrome(int number) {
if (number > 9) {
int rev=0,rem;
for(int num = number;num>0;num/=10)
{
rem=num%10;
rev=rev*10+rem;
}

if (rev == number) { return true; }
}
return false;
}

```

Read through the in code comments to see how I have done this refactoring and the changes I did to the method. Hope it makes a bit more sense to you and does what you like it to do.

Enjoy!

"At DIC we be refactoring and reversing code ninjas...we also like to drive a 'racecar' when we get a chance.