w3resource

C Exercises: Check whether a number is a palindrome or not

C For Loop: Exercise-38 with Solution

Write a C program to check whether a number is a palindrome or not.

Visual Presentation:

Check whether a number is a palindrome or not

Sample Solution:

C Code:

#include <stdio.h> // Include the standard input/output header file.

int main(){
    int num, r, sum = 0, t; // Declare variables for the original number, remainder, reversed number, and temporary variable.

    printf("Input a number: "); // Prompt the user to input a number.
    scanf("%d", &num); // Read the input from the user.

    for(t = num; num != 0; num = num / 10){ // Loop to reverse the digits of the number.
         r = num % 10; // Extract the last digit (remainder when divided by 10).
         sum = sum * 10 + r; // Build the reversed number by adding the extracted digit.
    }

    if(t == sum) // Check if the original number and the reversed number are equal.
         printf("%d is a palindrome number.\n", t); // Print a message if it is a palindrome.
    else
         printf("%d is not a palindrome number.\n", t); // Print a message if it is not a palindrome.
		  return 0;  // Indicate that the program has executed successfully.
}

Sample Output:

Input a number: 121                                                                                           
121 is a palindrome number.

Flowchart:

Flowchart : Check whether a number is a palindrome or not.

C Programming Code Editor:

Previous: Write a program in C to display the number in reverse order.
Next: Write a program in C to find the number and sum of all integer between 100 and 200 which are divisible by 9.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.