C Program To Find Sum of Squares of Digits using Recursion

Write a C program to find sum of squares of digits of a positive integer number input by the user, using recursive function.

Example:

If user inputs num value as 123. Then we fetch the individual digits present in 123 i.e., 3, 2 and 1, square it and add it to get the final result.

i.e., (3 x 3) + (2 x 2) + (1 x 1) = 14.

So, sum of squares of digits of 123 is 14.

Video Tutorial: C Program To Find Sum of Squares of Digits using Recursion


[youtube https://www.youtube.com/watch?v=7YaJ2pIkzKc]

YouTube Link: https://www.youtube.com/watch?v=7YaJ2pIkzKc [Watch the Video In Full Screen.]

Source Code: C Program To Find Sum of Squares of Digits using Recursion

#include<stdio.h>

int square(int num)
{
    if(num == 0)
        return 0;
    else
        return( (num%10) * (num%10) + square(num/10) );
}

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

Output:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Source Code: C Program To Find Sum of Squares of Digits using Recursion and pow() method

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

int square(int num)
{
    if(num == 0)
        return 0;
    else
        return( pow((num%10), 2) + square(num/10) );
}

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

Output:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Here we are making use of pow() method present inside math.h library file. pow() takes base value as first argument and exponent value as its second argument.

Source Code: C Program To Find Sum of Squares of Digits using Recursion, Ternary/Conditional Operator and pow() method

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

int square(int);

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

int square(int num)
{
    return( (num == 0) ? 0 : ( pow((num % 10), 2) + square(num/10) ));
}

Output 1:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Output 2:
Enter a positive integer number:
2103
Sum of squares of digits of 2103 is 14.

Output 3:
Enter a positive integer number:
456
Sum of squares of digits of 456 is 77.

Output 4:
Enter a positive integer number:
2020
Sum of squares of digits of 2020 is 8.

Output 5:
Enter a positive integer number:
2021
Sum of squares of digits of 2021 is 9.

To know more about Ternary or Conditional Operator visit:
Ternary Operator / Conditional Operator In C.

Dry Run: Example

Lets assume that user has input num value as 123.

num(num%10)2num/10(num%10)2+square(num/10)
123(3)2129+square(12)
12(2)214+square(1)
1(1)201+square(0)

Value Returning – Control Shifting back.

Return ValueToResult
return 0;square(0)1+0=1
1square(1)4+1=5
5square(12)9+5=14

So, sum of squares of digits of 123 is 14.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Convert Decimal To Binary Number using Recursion

A positive integer is entered through the keyboard, write a function to find the Binary equivalent of this number:

(1) Without using recursion.
(2) Using recursion.

Analyze The Problem Statement

We need to convert the user input Decimal number to its equivalent Binary number using iterative logic as well as recursive logic.

In this video tutorial, we’ll write 2 functions. One for iterative logic and another for recursive logic.

Expected Input/Output

Enter a Decimal number
14

Iterative Logic
Binary Equivalent of 14 is 1110.

Recursive Logic
Binary Equivalent of 14 is 11110.

Note: Binary number system can be derived by base 2 to the power of whole numbers.

Binary Number System

Explanation:

If user enters num = 14

We keep on dividing and modulo dividing the number by 2.

14 / 2 = 7, reminder 0.
07 / 2 = 3, reminder 1.
03 / 2 = 1, reminder 1.
01 / 2 = 0

So Binary equivalent of 14 is 1110.

Video Tutorial: C Program To Convert Decimal To Binary Number using Recursion


[youtube https://www.youtube.com/watch?v=hBaesKngoMY]

YouTube Link: https://www.youtube.com/watch?v=hBaesKngoMY [Watch the Video In Full Screen.]

Source Code: C Program To Convert Decimal To Binary Number using Recursion

#include<stdio.h>

int binary_rec(int);
int binary(int);

int main()
{
    int num;

    printf("Enter a Decimal number\n");
    scanf("%d", &num);

    printf("Binary Equivalent (Iterative) of %d is %d\n", num, binary(num));
    printf("Binary Equivalent (Recursive) of %d is %d\n", num, binary_rec(num));

    return 0;
}

int binary_rec(int num)
{
    if(num == 0)
        return 0;
    else
        return((num % 2) + 10 * binary_rec(num/2));
}

int binary(int num)
{
    int rem, bin = 0, place = 1;
    while(num)
    {
        rem   = num % 2;
        num   = num / 2;
        bin   = bin + (rem * place);
        place = place * 10;
    }
    return(bin);
}

Output 1:
Enter a Decimal number
14

Iterative Logic
Binary Equivalent of 14 is 1110

Recursive Logic
Binary Equivalent of 14 is 1110

Output 2:
Enter a Decimal number
41

Iterative Logic
Binary Equivalent of 41 is 101001

Recursive Logic
Binary Equivalent of 41 is 101001

Logic To Convert Decimal Number To Binary Number using Recursion

For iterative logic, please check the video tutorial C Program To Convert Decimal Number To Binary Number, using While Loop.

Recursive Function Logic
Assume that user inputs num value as 14.

numnum % 2(num % 2) + 10 * binary_rec(num/2)
1414 % 2(0) + 10 * binary_rec(7)
77 % 2(1) + 10 * binary_rec(3)
33 % 2(1) + 10 * binary_rec(1)
11 % 2(1) + 10 * binary_rec(0)

Value Returning – Control Shifting back.

Return ValueToResult
return 0;(1) + 10 * binary_rec(0)(1) + 10 * 0 = 1
1(1) + 10 * binary_rec(1)(1) + 10 * 1 = 11
11(1) + 10 * binary_rec(3)(1) + 10 * 11 = 111
111(0) + 10 * binary_rec(7)(0) + 10 * 111 = 1110

Binary Equivalent of Decimal Number 14 is 1110.

Source Code: C Program To Convert Decimal To Binary Number using Recursion and Ternary or Conditional Operator

#include<stdio.h>

int binary_rec(int);
int binary(int);

int main()
{
    int num;

    printf("Enter a Decimal number\n");
    scanf("%d", &num);

    printf("\nIterative Logic\n");
    printf("Binary Equivalent of %d is %d\n\n", num, binary(num));

    printf("\nRecursive Logic\n");
    printf("Binary Equivalent of %d is %d\n\n", num, binary_rec(num));

    return 0;
}

int binary_rec(int num)
{
    return( (num == 0) ? 0 : (num % 2) + 10 * binary_rec(num / 2));
}

int binary(int num)
{
    int rem, bin = 0, place = 1;

    while(num != 0)
    {
        rem   = num % 2;
        num   = num / 2;
        bin   = bin + (rem * place);
        place = place * 10;
    }
    return(bin);
}

Output 1:
Enter a Decimal number
14

Iterative Logic
Binary Equivalent of 14 is 1110

Recursive Logic
Binary Equivalent of 14 is 1110

Output 2:
Enter a Decimal number
41

Iterative Logic
Binary Equivalent of 41 is 101001

Recursive Logic
Binary Equivalent of 41 is 101001

To know more about Ternary or Conditional Operator visit:
Ternary Operator / Conditional Operator In C

Source Code: C Program To Convert Decimal To Binary Number using Recursion

Another Method

#include<stdio.h>

void binary_rec(int);
int binary(int);

int main()
{
    int num;

    printf("Enter a Decimal number\n");
    scanf("%d", &num);

    printf("\nIterative Logic\n");
    printf("Binary Equivalent of %d is %d\n\n", num, binary(num));

    printf("\nRecursive Logic\n");
    printf("Binary Equivalent of %d is ", num);
    binary_rec(num);
    
    printf("\n");

    return 0;
}

void binary_rec(int num)
{
    if(num == 1)
        printf("1");
    else
    {
        binary_rec(num/2);
        printf("%d", num%2);
    }
}

int binary(int num)
{
    int rem, bin = 0, place = 1;

    while(num != 0)
    {
        rem   = num % 2;
        num   = num / 2;
        bin   = bin + (rem * place);
        place = place * 10;
    }
    return(bin);
}

Output:
Enter a Decimal number
14

Iterative Logic
Binary Equivalent of 14 is 1110

Recursive Logic
Binary Equivalent of 14 is 1110

Here we simply divide the number by 2 and keep passing it as new value of num to binary_rec() function, and we print num%2 once num = 1 and it returns the value 1.

Number Systems

number systems

1. Binary Number System uses base 2 and digits 01.
2. Octal Number System uses base 8 and digits 01234567.
3. Decimal Number System uses base 10 and digits 0123456789.
4. Hexadecimal Number System uses base 16 and digits 0123456789ABCDEF.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Prime Factors of a Number using Recursion

A positive integer is entered through the keyboard, write a C program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

Analyze The Problem Statement

According to problem statement we need to find prime factors of user input positive integer number using iterative logic first, and then modify it and write a recursive logic to obtain the same result.

In our video tutorial we’ll write both iterative as well as recursive logic. This way you can compare the two – both the similarities and differences in the code.

For Example: Prime factors of 24 are 2, 2, 2 and 3.

prime factors of 24

Related Read:
C Program To Find Prime Factors of a Number

Note:
Both 24 and 35 are not prime numbers, but the factors(2, 3, 5 and 7) we display are prime numbers and multiplying all the prime factors should give the original number.

Video Tutorial: C Program To Find Prime Factors of a Number using Recursion


[youtube https://www.youtube.com/watch?v=cssyXvqaQI4]

YouTube Link: https://www.youtube.com/watch?v=cssyXvqaQI4 [Watch the Video In Full Screen.]


Source Code: C Program To Find Prime Factors of a Number using Recursion

#include<stdio.h>

void pfactors_rec(int, int);
void pfactors(int);

int main()
{
    int num;

    printf("Enter a positive integer number\n");
    scanf("%d", &num);

    printf("\nPrime Factors of %d without using recursion\n", num);
    pfactors(num);

    printf("\nPrime Factors of %d using recursion\n", num);
    pfactors_rec(num, 2);

    return 0;
}

void pfactors_rec(int num, int count)
{
    if(num < 1)
        return;
    else if(num % count == 0)
    {
      printf("%d\n", count);
      pfactors_rec(num / count, count);
    }
    else
    {
      pfactors_rec(num, count+1);
    }
}

void pfactors(int num)
{
    int count;

    for(count = 2; (num > 1); count++)
    {
        while(num % count == 0)
        {
            printf("%d\n", count);
            num = num / count;
        }
    }
    printf("\n");
}

Output 1:
Enter a positive integer number
24

Prime Factors of 24 without using recursion
2
2
2
3

Prime Factors of 24 using recursion
2
2
2
3

Output 2:
Enter a positive integer number
35

Prime Factors of 35 without using recursion
5
7

Prime Factors of 35 using recursion
5
7

Output 3:
Enter a positive integer number
510

Prime Factors of 510 without using recursion
2
3
5
17

Prime Factors of 510 using recursion
2
3
5
17

Output 4:
Enter a positive integer number
24024

Prime Factors of 24024 without using recursion
2
2
2
3
7
11
13

Prime Factors of 24024 using recursion
2
2
2
3
7
11
13

Output 5:
Enter a positive integer number
315

Prime Factors of 315 without using recursion
3
3
5
7

Prime Factors of 315 using recursion
3
3
5
7

Logic To Find Prime Factors of a Number using Recursion

We pass the user input number and 2 to the recursive function pfactors_rec(). We pass 2 as count value because 2 is the first prime number. So we initialize 2 to count and we change the value of count inside pfactors_rec() function.

Inside pfactors_rec() function
We first write the base condition(i.e., a condition to exit or return from the infinite recursive calls – freeing up the memory stack). We check if num value is less than 1, in that case we return the control back to the calling function.

Inside else if condition we check if the user input number is perfectly divided by 2(initial value of variable count). If true, then we print the value 2 and then divide the number by 2. We keep doing this recursively until num is not perfectly divided by 2.

prime factors of 24

If 2 can’t perfectly divide the number then, else condition code is executed, where we increment the value of count by 1.

Since inside else if we keep dividing the number by value of count until it perfectly divides the number, the multiples of value of count can not divide the number going further. So only prime numbers can(probably) perfectly divide the value present inside variable num. This is the reason we need not write function to find next prime number and then assign it to count.

Example with output

numcountnum%countfunction callPrint
242truepfactor_rec
(24/2, 2)
2
122truepfactor_rec
(12/2, 2)
2
62truepfactor_rec
(6/2, 2)
2
32falsepfactor_rec
(3, 2+1)
33truepfactor_rec
(3/3, 3)
3

Since num = 1, base condition gets executed and all the function instances of pfactors_rec() and associated memory gets popped out of the stack and finally the prime factors of the user input number will be left out on the console window.

Logic To Find Prime Factors of a Number using Iterative Logic

Complete logic, code and explanation with example is given at C Program To Find Prime Factors of a Number

Important Note:

If user input number is perfectly divisible by 5, then we iteratively or recursively or repeatedly divide the number by 5, until the number is no longer perfectly divisible by the number 5. That way, going forward, no other numbers which are multiples of 5 can perfectly divide the number.

For Example: If user input number is 24, and you continously divide the number 24 by 2 until 2 doesn’t perfectly divide the number, then no other multiples of 2 can perfectly divide the number.

Step 1:

num = 24, count = 2;

24 % 2 == 0 (True)
24 / 2 = 12;

Step 2:

num = 12, count = 2;

12 % 2 == 0 (True)
12 / 2 = 6;

Step 3:

num = 6, count = 2;

6 % 2 == 0 (True)
6 / 2 = 3;

Step 3:

Now num is reduced to 3, so no other numbers which are multiples of number 2 can perfectly divide the number(which happens to be 3 in this case).

Check steps 1, 2 and 3 for any number. Ultimately, only prime numbers can perfectly divide any number. Take a pen and paper and give it a try.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find GCD of Two Numbers using Recursion: Euclid’s Algorithm

Lets write a C program to find GCD(Greatest Common Divisor) or HCF(Highest Common Factor) of two positive integer numbers input by the user using Euclid’s Algorithm and by using Recursive function call logic.

Related Read:
C Program To Find GCD and LCM of Two Numbers using Euclidean algorithm
Recursive Functions In C Programming Language

Euclid’s Algorithm Logic

If user inputs 2 numbers n1 and n2, reduce the bigger number by modulo dividing it by the smaller number. For example, if n1 is greater than n2, then reduce the value of n1 by replacing it with n1%n2.

Assume that we’ve a function gcd() which returns gcd of 2 numbers passed to it. Ex: gcd(n1, n2);

According to Euclid’s Algorithm, we’ll get the same gcd if we reduce the bigger number by modulo dividing it by smaller number.

If n1 > n2 we need to pass gcd(n1%n2, n2);
If n2 > n1, we need to pass gcd(n1, n2%n1);

We need to recursively execute above 2 lines of logic until either n1 is 0 or until n2 is 0. If n1 is 0, then value present in n2 is the gcd of (n1,n2). If n2 is 0, then value present in n1 is the gcd of (n1,n2).

Video Tutorial: C Program To Find GCD of Two Numbers using Recursion: Euclid’s Algorithm


[youtube https://www.youtube.com/watch?v=k6zrTKpSg20]

YouTube Link: https://www.youtube.com/watch?v=k6zrTKpSg20 [Watch the Video In Full Screen.]


Source Code: C Program To Find GCD of Two Numbers using Recursion: Euclid’s Algorithm

#include<stdio.h>

int gcd(int, int);

int main()
{
    int num1, num2;

    printf("Enter 2 positive integer numbers\n");
    scanf("%d%d", &num1, &num2);

    printf("\nGCD of %d and %d is %d.\n", num1, num2, gcd(num1, num2));

    return 0;
}

int gcd(int n1, int n2)
{
    if(n1 == 0) return n2;
    if(n2 == 0) return n1;

    if(n1 > n2)
        return gcd(n1%n2, n2);
    else
        return gcd(n1, n2%n1);
}

Output 1:
Enter 2 positive integer numbers
1980
1617

GCD of 1980 and 1617 is 33.

Output 2:
Enter 2 positive integer numbers
15
20

GCD of 15 and 20 is 5.

Example:

Lets assume that user has entered n1 = 1980 and n2 = 1617

n1n2Biggest NoEvaluateFunction Call
198016171980gcd(1980 % 1617, 1617)gcd(363, 1617)
36316171617gcd(363, 1617 % 363)gcd(363, 165)
363165363gcd(363 % 165, 165)gcd(33, 165)
33165165gcd(33, 165 % 33)gcd(33, 0)

In above table gcd(33, 0) gets called, since n2 = 0, our program returns value of n1 as gcd, which is 33.

So GCD of 1980 and 1617 is 33.

Source Code: C Program To Find GCD of Two Numbers using Recursion and Ternary or Conditional Operator: Euclid’s Algorithm

#include<stdio.h>

int gcd(int, int);

int main()
{
    int num1, num2;

    printf("Enter 2 positive integer numbers\n");
    scanf("%d%d", &num1, &num2);

    printf("GCD of %d and %d is %d.\n", num1, num2, gcd(num1, num2));

    return 0;
}

int gcd(int n1, int n2)
{
    if(n1 == 0) return n2;
    if(n2 == 0) return n1;

    return( (n1 > n2) ? gcd(n1%n2, n2) : gcd(n1, n2%n1) );
}

Output 1:
Enter 2 positive integer numbers
1980
1617

GCD of 1980 and 1617 is 33.

Know more about ternary operator or conditional operator, watch a separate video tutorial: Ternary Operator / Conditional Operator In C.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Factorial of a Number using Recursion

Lets write a C program to find Factorial of a user input number using Recursion.

Factorial Definition: Factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n.

Important Note: By convention, Factorial of 0 is 1. i.e., 0! = 1.

Example: 5! = 5 x 4 x 3 x 2 x 1 which is equal to 120. i.e., 5! = 120.

Formula To Calculate Factorial of any positive integer number
We can calculate factorial of any number using this relationship:

num! = num * (num – 1)!

where num is a positive integer number.

Related Read:
C Program To Find Factorial of a Number
Recursive Functions In C Programming Language

Video Tutorial: C Program To Find Factorial of a Number using Recursion


[youtube https://www.youtube.com/watch?v=efcK6uNZzKw]

YouTube Link: https://www.youtube.com/watch?v=efcK6uNZzKw [Watch the Video In Full Screen.]


Source Code: C Program To Find Factorial of a Number using Recursion

#include<stdio.h>

int fact(int);

int main()
{
    int num;

    printf("Enter a positive number to find its Factorial\n");
    scanf("%d", &num);

    printf("\nFactorial of %d is %d.\n", num, fact(num));

    return 0;
}

int fact(int num)
{
    if(num)
        return(num * fact(num - 1));
    else
        return 1;
}

Output 1:
Enter a positive number to find its Factorial
7

Factorial of 7 is 5040.

Output 2:
Enter a positive number to find its Factorial
8

Factorial of 8 is 40320.

Logic To Find Factorial of a Number using Recursion

We ask the user to enter a positive integer number and we pass this number to a function called fact().

Inside fact() function
Inside fact() function, we check if the number is non-zero, if true, we execute the code inside if block orelse(if num is zero), then the code inside else block gets executed.

Inside if block, we add the factorial of (num-1) to the value of num.

num * fact(num – 1)

and return the result to the calling function.

Inside else block, we simply return 1. Because factorial of 0 is 1. So when num is 0, we return 1.

Example:

numnum * fact(num-1)
55 * fact(4)
44 * fact(3)
33 * fact(2)
22 * fact(1)
11 * fact(0)

Value Returning – Control Shifting back.

FunctionReturn Value Result
1 * fact(0)return 1;1 * 1 = 1
2 * fact(1)12 * 1 = 2
3 * fact(2)23 * 2 = 6
4 * fact(3)64 * 6 = 24
5 * fact(4)245 * 24 = 120

Finally 120 will be returned to main() method where we call the fact() method.

Source Code: C Program To Find Factorial of a Number using Recursion and Ternary or Conditional Operator

#include<stdio.h>

int fact(int);

int main()
{
    int num;

    printf("Enter a positive number to find its Factorial\n");
    scanf("%d", &num);

    printf("\nFactorial of %d is %d.\n", num, fact(num));

    return 0;
}

int fact(int num)
{
    return( (num > 0) ? (num * fact(num - 1)) : 1 );
}

Output 1:
Enter a positive number to find its Factorial
5

Factorial of 5 is 120.

Output 2:
Enter a positive number to find its Factorial
6

Factorial of 6 is 720.

Know more about ternary operator or conditional operator, watch a separate video tutorial: Ternary Operator / Conditional Operator In C.

Memory Stack

Whenever there is a recursive function call, function instance and the memory associated with that function instance gets pushed into the stack. When any function instance returns a value, that function instance and memory associated with that function instance gets popped out or removed or gets deleted from the memory stack.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert