Check If Input Number is Palindrome in C

There are some numbers in mathematics when even reversed remain the same. Well as for observing these numbers with human eyes we don’t need to exert too much stress on our brains. However, to find the same thing using a computer program is quite a challenge for newbie programmers. Such numbers when even reversed remain the same are known as Palindrome numbers. And in today’s article, we’ll try to find Palindrome numbers using programs. So let’s find out how to Check If the Input Number is Palindrome or not in C.

 

What’s The Approach?

 

  • The simplest approach we will apply is to reverse the given input number and check if it is equal to the original number.

 

  • Let’s consider input number n. Therefore if the reverse of n is similar to n we’ll print true otherwise we’ll print false.

 

  • We will create a separate function to return the reverse of input n.

 

  • Create a reverse variable rev_num, we will multiply it by 10 & perform a modulo operation with 10.

 

  • The above instructions will keep executing till the value of num is greater than 0. So after that, we’ll divide num with 10. This way we’ll get the trailing digit of input n becoming the leading digit in our reverse variable.

 

Also Read: How to install C/C++ Compiler in Mac OS M1 Big Sur

 

C Program To Check If Input Number is Palindrome

 

Input:

N=2002

Output:

Is 2002 a Palindrome number? -> true

 

// C program to check a number
// is Palindrome or not.

#include <stdio.h>

/* Iterative function to reverse digits of num*/
int reverseDigits(int num)
{
    int rev_num = 0;
    while (num > 0) {
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}

/* Function to check if n is Palindrome*/
int isPalindrome(int n)
{

    // get the reverse of n
    int rev_n = reverseDigits(n);

    // Check if rev_n and n are same or not.
    if (rev_n == n)
        return 1;
    else
        return 0;
}

/*Driver program to test isPalindrome*/
int main()
{

  int n = 2002;
    printf("Is %d a Palindrome number? -> %s\n", n,
        isPalindrome(n) == 1 ? "true" : "false");
    return 0;
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *