Number Operations

Problem statement
Write a c program to do the following
1. int sumdigits (int num) : This function should take a decimal number as input and return the sum of digits
of the number.
2. int reverse (int num) : This function should take a decimal number and return the reverse number.
3. int palindrome (int num) : This function should return 1 if the input decimal number is a palindrome and
0 otherwise.
4. void findcommondigits (int num1, int num2) : This function should print the digits that are
common in two decimal numbers num1 and num2.
a. [Helper function] int occursdigit (int digit, int num) : This function checks if digit (0<=digit<=9) is
a digit in the decimal number num1
Type the following C program to test the above functions



#include<stdio.h>
int sumdigit(int c);
int reverse(int c);
int palaindrome(int num);
void findcommondigits (int num1, int num2);
int occursdigit(int num,int digit);
int main ()
{
  int num1, num2, rev1, rev2, s1, s2;
  printf("entert number1  ");
  scanf ("%d", &num1) ;
  printf("enter number2  ");
  scanf ("%d", &num2) ;
  printf ("num1 = %d, num2 = %d\n",num1,num2) ;
  s1 = sumdigit(num1) ;
  s2 = sumdigit(num2) ;
  if (s1 > s2)
    {
      printf ("Sum of digits of %d (%d) is greater than that of %d (%d)\n", num1, s1, num2, s2) ;
    }
  else if(s2>s1)
    {
      printf ("Sum of digits of %d (%d) is greater than that of %d (%d)\n", num2, s2, num1, s1) ;
    }
  else
    {
      printf("sum of both numbers is same=%d",s1);
    }
  rev1 = reverse (num1) ;
  rev2 = reverse (num2) ;
  printf ("Reverse of %d is %d\n", num1, rev1) ;
  printf ("Reverse of %d is %d\n", num2, rev2) ;
  if (palaindrome (num1))
    printf ("%d is a palindrome.\n", num1) ;
  else
    printf("%d is not a palindrome \n",num1);
  if (palaindrome (num2))
    printf ("%d is a palindrome.\n", num2) ;
  else
    printf("%d is not a palindrome \n",num2);
  printf("the common digit in %d and %d is ",num1,num2);
  findcommondigits (num1,num2);
  return 0;
}
int sumdigit(int n)
{
  int tempsum=0;
  while(n>=1)
    {
      tempsum=tempsum+n%10;
      n=n/10;
    }
  return tempsum;
}
int reverse(int num)
{
  int rev_num = 0;
  while(num > 0)
    {
      rev_num = rev_num*10 + num%10;
      num = num/10;
    }
  return rev_num;
}
int palaindrome(int num)
{
  if( num==reverse(num))
    {
      return 1;
    }
  else
    return 0;
}
void findcommondigits (int num1, int num2)
{
  int temp,y;
  while(num1>=1)
    {
      temp=(num1)%10;
      y=occursdigit(num2,temp);
      if(y==1)
{
 printf("%d ",temp);
}
      num1=num1/10;
    }
  return ;
}
int occursdigit(int num,int digit)
{
  int temp;
  while(num>=1)
    {
      temp=num%10;
      if(temp==digit)
{
 return 1;
}
      num=num/10;
    }
  return 0;
}

No comments:

Post a Comment