Back

Palindrome Program in C: Comprehensive Guide with Examples

11 Dec 2024
6 min read

A palindrome is a sequence of characters or digits that reads the same backwards as it does forward. This property can apply to both numbers and strings. For instance, the word "radar" or the number "121" are palindromes because when reversed, they remain identical. This concept is widely applicable in computer science for tasks like string manipulation, searching algorithms, and error-checking mechanisms.

The palindrome program in C is an essential topic for understanding basic programming concepts such as loops, conditionals, recursion, and string functions. In this article, we will walk you through various ways to implement palindrome-checking algorithms in C, from basic loops to recursive functions. You will learn through the process how palindromes work and how to efficiently write palindrome in C along the way.

Palindrome Number Algorithm

A palindrome number algorithm generally aims to determine whether the given number is the same when reversed. For instance, 121 is a palindrome; however, 123 is not. The general steps followed for the algorithm are:

  • Input the number: First, get a number from the user.
  • Reverse the number: Take apart the number into its separate digits, reverse the order, and rebuild it.
  • Comparison: Compare the reversed number with the original. If it is the same, the number is a palindrome; otherwise, it is not.

This algorithm uses mathematical operations, such as modulus (%) and division (/), to separate the digits and then reverse the number.

Palindrome Program in C Using For Loop

The use of a for-loop for the palindrome check represents one of the simplest and quickest of all palindromic techniques in C programming. This implies reversing the number and comparing it to the original one. The design of the logic using a for loop involves treating each digit of a number both divided by 10 during each iteration. The last digit is worn upon to reverse its counterpart.

  1. Input the number.
  2. Reverse the number: A for loop runs until the number becomes 0. In each iteration, the number's last digit is isolated and appended to the reversed number. The original number is then reduced by dividing it by 10, effectively removing the last digit.
  3. Comparison: After the loop, a comparison is made between the reversed number and the original number. If they are the same, print ‘Palindrome’; otherwise, print ‘Not a palindrome’.
#include <stdio.h>

int main() {
    int num, reversed = 0, remainder, original;

    // Get user input
    printf("Enter a number: ");
    scanf("%d", &num);

    original = num;  // Store the original number

    // Reverse the number using a for loop
    for (; num != 0; num /= 10) {
        remainder = num % 10;  // Get the last digit
        reversed = reversed * 10 + remainder;  // Build the reversed number
    }

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

    return 0;
}

Output:

Enter a number: 578
578 is not palindrome.
Process returned 0(0X0)  execution time : 4.979 s
press any key to continue

This method is also simple and helps in understanding the difference between while and for loops.

Palindrome Program in C Using While Loop

Another common approach to implement palindrome checks is using a while loop. This method is functionally identical to the for-loop method but uses a while loop to perform the reversal. A while loop is typically preferred when you don’t know beforehand how many iterations are necessary (which is true for number reversal). Here's the flow:

#include <stdio.h>

int main() {
    int num, reversed = 0, remainder, original;

    // Get user input
    printf("Enter a number: ");
    scanf("%d", &num);

    original = num;  // Store the original number

    // Reverse the number
    while (num != 0) {
        remainder = num % 10;  // Get the last digit
        reversed = reversed * 10 + remainder;  // Build the reversed number
        num /= 10;  // Remove the last digit
    }

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

    return 0;
}

Output:

Enter a number : 555
555 is a palindrome
Process returned 0 (0X0) execution time : 3.175 s
press any key to continue.

C Program to Check Palindrome Number Using Function

Using functions to check for palindromes is a way of making the code modular and reusable. From this function, you will apply your palindrome logic and call this function several times in your program, which is inherent in good programming practice.

Function Definition: A function created that takes value digits as input and returns true or false when asked for a palindrome.

Reversal Logic Inside the Function: The reversal logic (using a loop or recursion) resides within this function.

Main Program: The main() function collects user input, calls the palindrome-checking function, and displays the result.

#include <stdio.h>

// Function to check if a number is a palindrome
int isPalindrome(int num) {
    int reversed = 0, remainder, original = num;

    // Reverse the number
    while (num != 0) {
        remainder = num % 10;  // Get the last digit
        reversed = reversed * 10 + remainder;  // Build the reversed number
        num /= 10;  // Remove the last digit
    }

    // Check if the original number is equal to the reversed number
    return original == reversed;
}

int main() {
    int num;

    // Get user input
    printf("Enter a number: ");
    scanf("%d", &num);

    // Check if the number is a palindrome
    if (isPalindrome(num)) {
        printf("%d is a palindrome.\n", num);
    } else {
        printf("%d is not a palindrome.\n", num);
    }

    return 0;
}

Output:

Enter any number: 778778
778778 is not a palindrome
Process returned 0 (0X0)  execution time : 65.290 s
press any key to continue

This approach not only solves the problem but also promotes the reuse of the palindrome-checking logic.

String Palindrome Program in C Using strrev()

For string palindromes, one of the simplest ways is to employ the built-in strrev() function that reverses a string. Thus, you can do the following:

This method simplifies the process by utilising C’s standard string handling functions. However, note that strrev() is not a standard C function and may not work in all compilers (it is mostly available in Turbo C and some non-standard C compilers).

#include <stdio.h>
#include <string.h>

// Function to check if a string is a palindrome
int isPalindrome(char str[]) {
    int len = strlen(str);
    char reversed[100];
    
    // Reverse the string manually
    for (int i = 0; i < len; i++) {
        reversed[i] = str[len - 1 - i];
    }
    reversed[len] = '\0';  // Null-terminate the reversed string

    // Compare the original string with the reversed string
    if (strcmp(str, reversed) == 0) {
        return 1; // Palindrome
}
    return 0; // Not a palindrome
}

int main() {
    char str[100];

    // Get user input
    printf("Enter a string: ");
    scanf("%s", str);

    // Check if the string is a palindrome
    if (isPalindrome(str)) {
        printf("\"%s\" is a palindrome.\n", str);
    } else {
        printf("\"%s\" is not a palindrome.\n", str);
    }

    return 0;
}

Output:

Enter a string : boy
"boy" is not palindrome

Palindrome String Program in C Using Recursion

Recursion has a more elegant and clear approach to solving palindrome problems. In this concept, you define a recursive function that compares characters from either end of the string against the middle. Here is how it works:

#include <stdio.h>
#include <string.h>

// Recursive function to check palindrome
int isPalindrome(char str[], int start, int end) {
    // Base case: If we have checked all the characters
    if (start >= end) {
        return 1;  // Palindrome
    }

    // Check if the characters at start and end are the same
    if (str[start] != str[end]) {
        return 0;  // Not a palindrome
    }

    // Recursive call by moving inwards
    return isPalindrome(str, start + 1, end - 1);
}

int main() {
    char str[100];

    // Get user input
    printf("Enter a string: ");
    scanf("%s", str);

    // Call the recursive function and check palindrome
    if (isPalindrome(str, 0, strlen(str) - 1)) {
        printf("\"%s\" is a palindrome.\n", str);
    } else {
        printf("\"%s\" is not a palindrome.\n", str);
    }

    return 0;
}

Output:

Enter a string: MoM
"MoM" is a palindrome.

However, to use this method, you would require to have a good understanding of recursion while it may look more complex, it’s quite concise for checking palindromes without using loops.

Conclusion

Once the palindrome program is mastered in C, different concepts will follow quite easily, and one gets introduced to loops, functions, string manipulation, and recursion. We have seen various approaches to solving the palindrome problem: for loop, while loop, function, and recursion. With time, you will easily relate this programming coding with various complex problems and develop into a logical and efficient programmer.

By understanding the core concepts and implementing them in C, you are now equipped to tackle other string manipulation and algorithmic challenges in programming.

Frequently Asked Questions

1. What is a palindrome?

A palindrome is that which reads the same either backward or forward. This deals with sequences that can be words (e.g., madam, noon) or numbers (e.g., 121). For a sequence of symbols to become a palindrome, it must have symmetry.

2. Why are palindrome programs important in C?

A palindrome program in c is a good way to build up basic programming skills like loops, recursion, functions, and strings logical thinking, and problem-solving skills. This makes palindrome programs a constant practice exercise for beginners and intermediate programmers.

3. Can palindrome programs be used in real-world applications?

Yes, palindrome checks are crucial in various real-world applications. In cryptography, for example, palindromes are used for error detection and encoding schemes. They are also important in data validation and parsing tasks in software development.

4. What are some key functions for palindrome programs in C?

Some of the functions that the programmer mostly utilizes when it comes to checking for palindrome strings include strrev() to reverse a string and strcmp() to compare two strings. When checking if the number is a palindrome or not, the loops and mathematical operations such as modulus (%) and division (/) are highly useful.

5. What’s the difference between iterative and recursive approaches?

Iterative Method: Use loops (for, while) to repeatedly execute a particular instruction or a block of instructions; this is more memory-efficient and easier for beginners to comprehend.

Recursive approach: Involves the function calling itself to solve smaller instances of the same problem. While elegant, recursion may not be suitable for large inputs due to stack overflow risks.

Read More Articles

Chat with us
Chat with us
Talk to career expert