Thursday, 22 December 2016

C++ Code to make a number palindrome

Statement:If the number is not Palindrome your program should make it Palindrome.
Code:
//If the number is not Palindrome your program should make it Palindrome 
#include<iostream>
using namespace std;
void main()
{
       cout << "\t\t\tPlindrome Number\n\n";
       int num, rev, tmp, tmp2, i, j, rev1;
       rev = 0; i = 0; j = 1; rev1 = 0;
       cout << "Enter A Nmuber : ";
       cin >> num;
       tmp = num;
       while (tmp != 0) //to calculate reverse
       {
              tmp2 = tmp % 10; //number remainder 10 will assign to tmp2
              rev = rev * 10 + tmp2; //reverse of number is equal to rev*10+number%10
              tmp = tmp / 10; //updating the value of number
       }
       if (rev == num) //if reverse is equal to number
       {
              cout <<endl<< num << " Is Pandlirome.";
       }
       else //if reverse is not equal to number
       {

              cout <<endl<< num << " Is Not Palindrome.";

              //**************************WORKING TO MAKE A NUMBER PALINDROME*****************************

              rev1 = rev; //rev1 is a temporary number to stre revers of given number
              while (rev1 != 0) // revers is not equal to zero
              {
                     rev1 = rev1 / 10; // revers updatin value by dividing reverse 10                                             | For Example : if revrese is 321 so by dividing 321/10=32...32/10==3... 3/10==0 
                     i++; //it will add value in i variable how much times revese divided by ten to calculate number of zeros     |So loop will execute 3 times and i=3;
              }
              while (i >= 2) //while i varivale in which number of 0s stored is greator then 2
              {
                     j = j * 10; //j is a variable which will multiply 1 i times to 10 ;;;; j==1 already  | For example for i==3 , 1=1*10==j=10;;;10==10*10=100;;;;j=100;;;
                     i--; // i will update its value to make j a 10s times variable number                | i value will decreease
              }
              rev = rev%j; // reverse remainder j will remove the first number of reverse and update it   | it will divede as 321%100; {rev==10 and j==10} rev=221; so it will print :12321:
              cout << "\n";
              cout <<endl<< num << rev << " Is Palindrome."; //it will print number and reverse which first charater is not include
       }


       cout << "\n\n";
       system("pause");

}

Mohammad Tayyab

Author & Editor

Imagination is more important than knowledge.

0 comments:

Post a Comment