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

i want to find all palindrome from 1 to 100 using for loop

Page 1 of 1

1 Replies - 16232 Views - Last Post: 05 September 2008 - 11:01 PM Rate Topic: -----

#1 harsimran.grewal11  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • 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! :code:

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  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4361
  • View blog
  • Posts: 12,180
  • 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. :snap:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1