Monday, November 17, 2014

Hanoi, Palindrome, Prime , Perfect or Not



C Program to print Tower of Hanoi using recursion

 #include
 #include 
void toh(int num, char x, char y, char z);
int main()
{
   int num;
   printf("\nEnter number of plates:");
   scanf("%d", &num);
   toh(num - 1, 'A', 'B', 'C');
   return (0);
}
 void TOH(int num, char x, char y, char z)
{
   if (num > 0)
   {
      toh(num - 1, x, z, y);
      printf("\n%c -> %c", x, y);
      toh(num - 1, z, y, x);
   }
}

Check Whether Given Number is Palindrome or Not

#include
#include
 int main()
{
   int num, i, count = 0;
   char str1[10], str2[10];
   printf("nEnter a number:");
   scanf("%d", &num);
   sprintf(str1, "%d", num);
   strcpy(str2, str1);
   strrev(str2);
   count = strcmp(str1, str2);
   if (count == 0)
      printf("%d is a prime number", num);
   else
      printf("%d is not a prime number", num);

   return 0;
}

Check Whether Number is Prime or not

#include
#include
int main()
{
   int num, i, count = 0;
   printf("Enter a number:");
   scanf("%d", &num);
   for (i = 2; i <= num / 2; i++)
     {
      if (num % i == 0)
      {
         count++;
         break;
      }
   }

   if (count == 0)
      printf("%d is a prime number", num);
   else
      printf("%d is not a prime number", num);

   return 0;
}

Check for Armstrong Number in C

#include
#include
int main()
{
   int num, temp, sum = 0, rem;
   printf("\nEnter number for checking Armstrong : ");
   scanf("%d", &num);
   temp = num;
   while (num != 0)
   {
      rem = num % 10;
      sum = sum + (rem * rem * rem);
      num = num / 10;
   }
    if (temp == sum)
      printf("%d is Amstrong Number", temp);
   else
      printf("%d is Amstrong Number", temp);
    return (0);
}

Output


Enter Number For Checking Armstrong : 153
153 is Amstrong Number

Program to Check Whether Number is Perfect or Not

#include
#include
int main()
{
   int num, i = 1, sum = 0;
   printf("Enter a number: ");
   scanf("%d", &num);
   while (i < num)
   {
      if (num % i == 0)
      {
         sum = sum + i;
      }
      i++;
   }
    if (sum == num)
      printf("%d is a Perfect Number", i);
   else
      printf("%d is Non Perfect Number", i);
    return 0;
}

No comments:

Post a Comment