Hello, Another exercise. In this particular problem we are given a five digit integer and program have to determine if its a Palindrome. Author states that we have to separate each digit into its own variables using % and /. I came up with solution but i don't know if its acceptable. It produces correct result but it looks bad to me. Here's my code, can someone look over it and give me any suggestions what i should have done instead or how i can improve it. Also author only had five digit numbers as examples. Thanks.

//deitel chaper  palindrome
	
#include "stdafx.h"
#include <iostream>

using namespace std;

int main(){
	
	int iCouner, iNumOne = 0, iNumTwo = 0, iWhole,
		iRemainder, iNumThree =0, iNumFour = 0, 
		iNumFive = 0, iRev = 0;

		iWhole = 12321;

		for( iCouner = 10000; iCouner >= 1; iCouner /= 10){
		
			iRemainder = iWhole % iCouner;

			if ( ( iWhole / 10 ) > 0 ) {
				iWhole /= iCouner; 
			}

			//each variable to contain just a whole number
			
			if ( iRev == 0 )
				iNumOne = iWhole;
			else if ( iRev == 1 )
				iNumTwo = iWhole;
			else if ( iRev == 2)
				iNumThree = iWhole;
			else if ( iRev == 3 )
				iNumFour = iWhole;
			else
				iNumFive = iWhole;

			
			iWhole = iRemainder; 
			++iRev;
			
		}
		if ( iNumOne == iNumFive && iNumTwo == iNumFour )
			cout << "its a palindrome" << endl;
		else
			cout << "Its not a pslindrome" << endl;


	return 0;
}

Your solution is fine, though if you fine yourself naming variables 1, 2, 3, etc., you really want an array instead:

#include <iostream>

using namespace std;

int main()
{
    int iCouner, iNum[5], iRev = 0;
    int iWhole = 12321;

    for (iCouner = 10000; iCouner >= 1; iCouner /= 10) {
        int iRemainder = iWhole % iCouner;

        if ((iWhole / 10) > 0)
            iWhole /= iCouner; 

        iNum[++iRev] = iWhole;
        iWhole = iRemainder; 
    }

    if (iNum[0] == iNum[4] && iNum[1] == iNum[3])
        cout << "its a palindrome" << endl;
    else
        cout << "Its not a pslindrome" << endl;

    return 0;
}

Notice how the logic of dealing with individual digits is vastly simplified by using an array. That's really the only big thing I'd mention. Everything else is minor nitpicks.

Right in later chapter he introduces the arrays and how they work so we are only limited to loops, if, switch. Thank you for the reply

would this do it?

if(iWhole/10000==iWhole%10&&(iWhole/1000)%10==(iWhole/10)%10){is_pal=true;}
else{is_pal=false;}

Edited 5 Years Ago by frogboy77: n/a

I think it achieves to see if the number is Palindrome but you violate the requirement of not separating each digit into its own variable.

This article has been dead for over six months. Start a new discussion instead.