C Program to Check Palindrome Number.

In this C programming tutorial, we will learn how to check if the given number is a palindrome number or not. Before moving to the code section let us understand what is Palindrome number?

Palindrome Number.

A palindrome number is a number that reads the same backward as forward. In other words, the digits of a palindrome number remain unchanged when read from left to right and from right to left. 

Example: 121, 454, and 12321 are palindrome numbers.

Algorithm to Check Palindrome Number.

Step 1: Input the number from the user.
Step 2: Create a copy of the original number to compare later.
Step 3: Initialize variables to store the reverse of the number and the remainder.
Step 4: Use a loop to reverse the digits of the number:
  • a) Extract the last digit of the number using the modulus (%) operator.
  • b) Add the last digit to the reversed number after moving the previous digits one place left using multiplication (*= 10).
  • c) Remove the last digit from the original number using integer division ( /= 10).
  • d) Repeat the above steps until the original number becomes 0.
Step 5: Compare the reversed number with the copy of the original number.
Step 6: If the reversed number is equal to the original number, it is a palindrome. Otherwise, it is not.

Program to Check Palindrome Number.

// c code implementation to check palindrome number
#include <stdio.h>

int main() {
    int num, originalNum, reversedNum = 0, remainder;

    printf("Enter an integer: ");
    scanf("%d", &num);

    originalNum = num;

    // Reverse the number
    while (num != 0) {
        remainder = num % 10;         
        reversedNum = reversedNum * 10 + remainder;   
        num /= 10;                    
    }

    // Compare with the original number
    if (reversedNum == originalNum) {
        printf("%d is a palindrome number.\n", originalNum);
    } else {
        printf("%d is not a palindrome number.\n", originalNum);
    }

    return 0;
}
Output:
Enter an integer: 12321
12321 is a palindrome number.

Time Complexity: O(n) where n is the number of digits present in the given number.
Space Complexity: O(1) no extra space is required to solve this problem.

Similar articles:

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS