This blog is under construction
Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Sunday, 21 July 2013

C program to find the frequency characters in a string using recursion

Write a C program to find the frequency characters in a string using recursion.


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

  /* calculates the frequency of characters in the given string */
  void calcFrequency(char *str, int *freq) {
        int index;
        if (*str != '\0') {
                index = *str - 'a';
                freq[index]++;
                calcFrequency(str + 1, freq);
        }
        return;
  }

  int main() {
        char str[256];
        int i, frequency[26];

        /* get the input string from the user */
        printf("Enter your input string(only lowercase):");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* fill frequency with 0s */
        memset(frequency, 0, sizeof(frequency));

        /* finds the frequency of characters in the given string */
        calcFrequency(str, frequency);
        printf("Frequency of characters:\n");

        /* prints the result */
        for (i = 0; i < 26; i++) {
                if (frequency[i]) {
                        printf("%c => %d\n", i + 'a', frequency[i]);
                }
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string(only lowercase):helloworld
  Frequency of characters:
  d => 1
  e => 1
  h => 1
  l => 3
  o => 2
  r => 1
  w => 1


C program to print subset of a set using recursion

Write a C program to print subset of a set using recursion.


  #include <stdio.h>
  #include <stdlib.h>
  #include <math.h>

  /* find subsets of a given set */
  void findSubsets(int *value, int n, int i) {
        int j;

        if (i < 0)
                return;

        printf("{");
        /*
         * To form subsets, we need to consider binary values
         * with "n" bits.  If n is 3, then the possible 
         * number of subsets is 2^3 = 8.  And we need to consider
         * binary values with 3 bits.(000, 001, 010, 011, 100,
         * 101, 110, 111)ie. decimal values 0 to 7.  Then form
         * the subsets using the above manipulated binary value.
         * If any of the bit(in binary value) is set, then note
         * the bit index.  Use the same index value to fetch the
         * value from the input array.  Suppose, 001 is the value.
         * Here, 0th bit is set.  So, the element at index 0
         * from input array needs to cosidered for subset outputs.
         */
        for (j = 0; j < n; j++) {
                /* 
                 * checking jth bit is set in i.  If
                 * it is set, then fetch the element at
                 * jth index in value array
                 */
                if (i & (1 << j)) {
                        printf("%d ", value[j]);
                }
        }
        printf("}\n");

        /* recursive call */
        findSubsets(value, n, i - 1);

        return;
  }

  int main() {
        int i, j, count, n, *value;

        /* get the number of inputs from user */
        printf("Enter the number of elements:");
        scanf("%d", &n);

        /* allocate memory to store the elements */
        value = (int *)malloc(sizeof(int) * n);

        /* get the elements from the user */
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ",i);
                scanf("%d", &value[i]);
        }

        /* 2^n - indicates the possible no of subsets */
        count = pow(2, n);

        /* finds the subsets of the given set */
        findSubsets(value, n, count - 1);

        return 0;
  }


Note:
gcc subset.c -lm => linked math library since we have used a math function pow().

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements:3
  Data[0]: 1
  Data[1]: 2
  Data[2]: 3
  {1 2 3 }
  {2 3 }
  {1 3 }
  {3 }
  {1 2 }
  {2 }
  {1 }
  {}


C program to perform bubble sort using recursion

Write a C program to perform bubble sort using recursion.


  #include <stdio.h>
  #include <stdlib.h>

  /* sorts the given numbers in ascending order */
  void bubbleSort(int *data, int n) {
        int i, temp;

        if (n > 0) {
                for (i = 1; i < n; i++) {
                        if (data[i - 1] > data[i]) {
                                temp = data[i];
                                data[i] = data[i - 1];
                                data[i - 1] = temp;
                        }
                }

                bubbleSort(data, n - 1);
        }

        return;
  }

  int main() {
        int i, n, *data;

        /* get the number of inputs from the user */
        printf("Enter the number of inputs:");
        scanf("%d", &n);

        /* dynamically allocate memory to store i/p values */
        data = (int *) malloc(sizeof(int) * n);

        /* get the input data from the user */
        for (i = 0; i < n; i++) {
                printf("data[%d]: ", i);
                scanf("%d", &data[i]);
        }

        /* sorts the given numbers */
        bubbleSort(data, n);

        /* print the sorted numbers */
        printf("Data After Bubble Sort:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", data[i]);
        }
        printf("\n");

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of inputs:5
  data[0]: 500
  data[1]: 100
  data[2]: 300
  data[3]: 200
  data[4]: 400

  Data After Bubble Sort:
  100 200 300 400 500 


C program to extract digits of a number using recursion

Write a C program to extract digits of a number using recursion.


  #include <stdio.h>

  /* extract digits of the given numer */
  void extractDigits(int num, int *count, int *digits) {
        if (num) {
                digits[*count] = num % 10;
                *count = *count + 1;

                /* recursive call */
                extractDigits(num / 10, count, digits);
        }
        return;
  }

  int main() {
        int i, num, count = 0, digits[32];

        /* get the input value from the user */
        printf("Enter your input value:");
        scanf("%d", &num);

        /* if the user input is 0 */
        if (!num) {
                printf("Digit 1 is 0\n");
                return 0;
        }

        /* extracts digits of the given number */
        extractDigits(num, &count, digits);

        /* print the digits of the given number */
        for (i = count - 1; i >= 0; i--) {
                printf("Digit %d is %d\n", (count - i), digits[i]);
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:123456
  Digit 1 is 1
  Digit 2 is 2
  Digit 3 is 3
  Digit 4 is 4
  Digit 5 is 5
  Digit 6 is 6


C program to calculate ncr using recursion

Write a C program to calculate nCr using recursion.


  #include <stdio.h>

  /* finds factorial of the given number */
  int fact(int num) {
        int ret;

        /* 0! is 1 */
        if (!num) {
                return 1;
        }

        /* recursively call */
        ret = num * fact(num - 1);
        return ret;
  }

  int main() {
        int n, r;
        float nCr;

        /* get the input value n from the user */
        printf("Enter your input for n:");
        scanf("%d", &n);

        /* get the input value r from the user */
        printf("Enter your input for r:");
        scanf("%d", &r);

        /* calculates nCr */
        nCr = (1.0 * fact(n)) / (fact(r) * fact(n - r));

        /* printing the result */
        printf("Result: %f\n", nCr);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input for n:12
  Enter your input for r:6
  Result: 924.000000


C program to check whether the given string is palindrome or not using recursion

Write a C program to check whether the given string is palindrome or not using recursion.


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

  /* checks whether the given string is palindrome or not */
  int isPalindrome(char *str, char *rev) {
        int ret;

        /* parsed whole string.. so palindrome */
        if (*str == '\0') {
                return 1;
        } else if (*str != *rev) {
                /* any character mismatch - not a palindrome */
                return 0;
        }

        /* recursive call */
        ret = isPalindrome(str + 1, rev - 1);
        return ret;
  }

  int main() {
        char str[256], ret;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* checks whether i/p string is palindrome or not */
        ret = isPalindrome(str, str + (strlen(str) - 1));

        /* printing the result */
        if (ret) {
                printf("%s is a palindrome\n", str);
        } else {
                printf("%s is not a palindrome\n", str);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string: madam
  madam is a palindrome


C program to check prime number or not using recursion

Write a C program to check prime number or not using recursion.


  #include <stdio.h>

  /* checking whether the given number is prime or not */
  void checkPrime(int num, int div) {
        /*
         * if div equals to num/2, then no number from
         * 2 to n/2 perfectly divides the given input
         */
        if (div == (num / 2)) {
                printf("%d is prime\n", num);
                return;
        }

        if ((div != 1) && (num == 1 || num % div == 0)) {
                printf("%d is not a prime number\n", num);
                return;
        }

        /* recursive call */
        checkPrime(num, ++div);
        return;
  }

  int main() {
        int num, div = 1;

        /* get the input value from the user */
        printf("Enter your input value:");
        scanf("%d", &num);

        /* checks whether the given input is prime or not */
        checkPrime(num, div);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:123
  123 is not a prime number
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:151
  151 is prime


C program to calculate power of a number using recursion

Write a C program to calculate power of a number using recursion.


  #include <stdio.h>

  /* calculates power of a number using recursion */
  void calcPower(int num, int power, int *res, int *count) {
        if (*count < power) {
                *res = *res * num;
                *count = *count + 1;

                /* recursive call */
                calcPower(num, power, res, count);
        }
        return;
  }

  int main() {
        int num, power, res = 1, count = 0;

        /* get the input value and its power from user */
        printf("Enter your input value:");
        scanf("%d", &num);
        printf("Enter your power value:");
        scanf("%d", &power);

        /* any value power 0 is 1 and 0 to the power any value is 0 */
        if (!num || !power) {
                printf("%d^%d is %d\n", num, power, num ? 1: 0);
                return 0;
        }

        /* calculates power of a number using recursion */
        calcPower(num, power, &res, &count);

        printf("%d^%d => %d\n", num, power, res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:5
  Enter your power value:3
  5^3 => 125


C program to generate fibonacci series using recursion

Write a C program to generate Fibonacci series using recursion.


  #include <stdio.h>

  /* prints first n fibonacci numbers */
  void fibonacci(int *num1, int *num2, int *count, int n) {
        int temp;
        if (*count < n) {
                printf("%d ", *num1);
                temp = *num1 + *num2;
                *num1 = *num2;
                *num2 = temp;
                *count = *count + 1;
                /* recursive call */
                fibonacci(num1, num2, count, n);
        }
        return;
  }

  int main() {
        int num1 = 0, num2 = 1, n, count = 0;

        /* get the number of fibonacci numbers needed */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* prints first n fibonacci numbers */
        printf("Fibonacci Series:\n");
        fibonacci(&num1, &num2, &count, n);
        printf("\n");

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:10
  Fibonacci Series:
  0 1 1 2 3 5 8 13 21 34


C program to convert decimal to binary using recursion

Write a C program to convert decimal to binary using recursion.


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

  /* finds the reverse of the given input */
  void strrev(char *binary, char *output, int *len) {
        if (*len >= 0) {
                *output = *(binary + *len);
                *len = *len - 1;
                strrev(binary, output + 1, len);
        } else {
                *output = '\0';
        }
        return;
  }

  /*
   * converts decimal to binary.  But, the binary output
   * will be in reverse order.  We need to reverse the binary
   * output to get the exact binary value.
   */
  void decimalToBinary(int num, char *binary) {
        if (num) {
                *binary = (num % 2) + '0';
                decimalToBinary(num / 2, binary + 1);
        } else {
                *binary = '\0';
        }
        return;
  }

  int main() {
        int num, len;
        char binary[256], output[256];

        /* get the input decimal value from the user */
        printf("Enter your input value:");
        scanf("%d", &num);

        if (!num) {
                printf("Binary Value: 0\n");
                return 0;
        }

        /* decimal to binary conversion */
        decimalToBinary(num, binary);
        len = strlen(binary) - 1;
        strrev(binary, output, &len);

        /* print the result */
        printf("Binary Value: %s\n", output);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:65535
  Binary Value: 1111111111111111


C program to convert binary to decimal using recursion

Write a C program to convert binary to decimal using recursion.


  #include <stdio.h>
  #include <string.h>
  #include <math.h>
  /* convert binary to decimal using recursion */
  void binaryToDecimal(char *binary, int *decimal, int *len) {
        static int num, i = 0;
        if (*len > 0) {
                /* parsing string from last character to start */
                *len = *len - 1;
                num = *(binary + *len) - '0';
                *decimal = *decimal + (num * pow(2, i++));
                binaryToDecimal(binary, decimal, len);
        }
        return;
  }

  int main() {
        char binary[256];
        int decimal = 0, len;

        /* get the input value from the user */
        printf("Enter your binary input:");
        fgets(binary, 256, stdin);
        binary[strlen(binary) - 1]= '\0';

        /* find the length of the given binary input */
        len = strlen(binary);

        /*
         * converts binary to decimal and it
         * stores the result in decimal
         */
        binaryToDecimal(binary, &decimal, &len);

        /* prints the resultant decimal value */
        printf("Decimal Value: %d\n", decimal);
        return 0;
  }


Note:
gcc binToDeci.c -lm => linked math library since we have used math function pow().

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your binary input:1111111111111111
  Decimal Value: 65535


C program to find the sum of first n natural numbers using recursion

Write a C program to find the sum of first N natural numbers using recursion.


  #include <stdio.h>

  /* find the sum of first n natural numbers */
  void findSum(int num, int *res) {
        if (num) {
                *res = *res + num;

                /* recursive call */
                findSum(num - 1, res);
        }
        return;
  }

  int main() {
        int input, sum = 0;

        /* get the input value from the user */
        printf("Enter your input value:");
        scanf("%d", &input);

        /* find the sum of first n natural numbers */
        findSum(input, &sum);

        /* print the result */
        printf("Sum of first %d natural numbers is %d\n", input, sum);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:10
  Sum of first 10 natural numbers is 55


C Program to find the sum of digits of a number using recursion

Write a C Program to find the sum of digits of a number using recursion.


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

  /* sum of digits of the given number */
  void sumOfDigits(int num, int *sum) {
        /* finds sum of digits */
        if (num) {
                *sum = *sum + num % 10;

                /* recursive call */
                sumOfDigits(num / 10, sum);
        }
        return;
  }

  int main() {
        int num, sum = 0;

        /* get the input value from the user */
        printf("Enter your input value:");
        scanf("%d", &num);

        /* sum of digits of the given input */
        sumOfDigits(num, &sum);

        /* print the sum of digits of the given input */
        printf("Sum of digits of %d is %d\n", num, sum);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:123456
  Sum of digits of 123456 is 21


C program to convert lowercase to uppercase using recursion

Write a C program to convert lowercase to uppercase using recursion.


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

  /* converts lowercase to uppercase using recursion */
  void lowerToUpper(char *str) {
        if (*str != '\0') {
                /* lower to upper */
                if (*str >= 'a' && *str <= 'z') {
                        *str = *str - 'a' + 'A';
                }

                /* recursive call */
                lowerToUpper(str + 1);
        }
        return;
  }

  int main() {
        char str[256];

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* converts lowercase to uppercase */
        lowerToUpper(str);
        printf("Uppercase To Lowercase: %s\n", str);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:hello world
  Uppercase To Lowercase: HELLO WORLD


C program to convert uppercase to lowercase using recursion

Write a C program to convert uppercase to lowercase using recursion.


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

  /* converts uppercase to lowercase using recursion */
  void upperToLower(char *str) {
        if (*str != '\0') {
                /* upper to lower */
                if (*str >= 'A' && *str <= 'Z') {
                        *str = *str - 'A' + 'a';
                }

                /* recursive call */
                upperToLower(str + 1);
        }
        return;
  }

  int main() {
        char str[256];

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* converts uppercase to lowercase */
        upperToLower(str);
        printf("Uppercase To Lowercase: %s\n", str);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:HELLO WORLD
  Uppercase To Lowercase: hello world


C program to print lowercase characters in a string using recursion

Write a C program to print lowercase characters in a string using recursion.


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

  /* print lowercase character in give character using recursion */
  void printLower(char *str) {
        if (*str != '\0') {
                /* prints lowercase characters alone */
                if (*str >= 'a' && *str <= 'z') {
                        printf("%c", *str);
                }

                printLower(str + 1);
        }
        return;
  }

  int main() {
        char str[256];

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* prints lowercase character in the given input */
        printf("Lower case characters in given string:");
        printLower(str);
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:HeLlO WoRlD
  Lower case characters in given string: elol


C program to print uppercase characters in a string using recursion

Write a C program to print uppercase characters in a string using recursion.


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

  /* print uppercase character in give character using recursion */
  void printUpper(char *str) {
        if (*str != '\0') {
                /* prints uppercase characters alone */
                if (*str >= 'A' && *str <= 'Z') {
                        printf("%c", *str);
                }

                printUpper(str + 1);
        }
        return;
  }

  int main() {
        char str[256];

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* prints uppercase character in the given input */
        printf("Upper case characters in given string:");
        printUpper(str);
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:HeLlO WoRlD
  Upper case characters in given string:HLOWRD


C program to copy string using recursion

Write a C program to copy one string to another using recursion.


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

  /* copies the source string to destination */
  void strcopy(char *src, char *dest) {
        if (*src != '\0') {
                *dest = *src;
                strcopy(src + 1, dest + 1);
        } else {
                /* terminating with null character */
                *dest = *src;
        }

        return;
  }

  int main() {
        char src[256], dest[256];

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(src, 256, stdin);
        src[strlen(src) - 1] = '\0';

        /* copies input string to given destination */
        strcopy(src, dest);

        /* print the results */
        printf("Source: %s\n", src);
        printf("Destination: %s\n", dest);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:copy me
  Source: copy me
  Destination: copy me


C program to find the length of a string using recursion

Write a C program to find the length of a string using recursion.


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

  /* finds length of the given string using recursion */
  int stringLength(char *str, int len) {

        if (*str != '\n') {
                len++;
                len = stringLength(str + 1, len);
        }
        return len;
  }

  int main() {
        char str[256], len = 0;

        /* get the input string from the user */
        printf("Enter your input string:");
        /* fgets appends \n with user input */
        fgets(str, 256, stdin);

        /* finds the length of the given input string */
        len = stringLength(str, len);

        /* print the result */
        printf("Length of the given input string is %d\n", len);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Calculate my length
  Length of the given input string is 19