Skip to main content

Practical-01

Write a program to check the given number is Palindrome or not using User Defined Function (UDF).

Introduction

In this program, we will check if the given number is Palindrome or not. A number is Palindrome if it is equal to its reverse. For example, 121 is Palindrome because it is equal to its reverse 121. We will use user defined function to check if the number is Palindrome or not.

Algorithm

  1. Get the number from the user.
  2. Call the user defined function checkPalindrome() and pass the number as an argument.
  3. In the function, reverse the number and check if it is equal to the original number.
  4. If it is equal, then the number is Palindrome. Otherwise, it is not Palindrome.
  5. Return the result from the function.
  6. Check the result in the main function and print the answer.
  7. End.

Code

Practical-01.c

#include <stdio.h> // Preprocessor directive

void main() // This defines our main function
{
int num, result;
printf("Enter a number: "); // Prompt the user to enter a number
scanf("%d", &num); // Get the number

result = checkPalindrome(num); // Call the user defined function

// Check the result and print the answer
if(result == 1)
printf("%d is Palindrome\n", num);
else
printf("%d is not Palindrome\n", num);

// Return statement
}

// User defined function to check for Palindrome
int checkPalindrome(int num)
{
int temp, remainder, reverse = 0;

// Store the value of num in temp
temp = num;

// Reverse the number using while loop
while(temp!=0){
remainder = temp % 10;
reverse = reverse*10 + remainder;
temp = temp / 10;
}

// Check if reversed number is equal to original
// and return the result
if(num == reverse)
return 1;
else
return 0;
}

Output

Enter a number: 121
121 is Palindrome
Explanation

The program first asks the user to enter a number. Then it calls the user defined function checkPalindrome() to check if the number is Palindrome or not. The function reverses the number and checks if it is equal to the original number. If it is equal, then the number is Palindrome.

The function checkPalindrome() returns 1 if the number is Palindrome and 0 if it is not.

The main function checks the result and prints the answer.