C Program To Find Sum of Natural Numbers Using Recursion

Write a recursive function to obtain the running sum of first 25 natural numbers.

1 + 2 + 3 + 4 + 5 + …. + 23 + 24 + 25 = 325

Related Read:
C Program to Calculate the Sum of Natural Numbers From 1 to N
C Program To Calculate the Sum of Natural Numbers From 1 to N using For Loop
Recursive Functions In C Programming Language

Video Tutorial: C Program To Find Sum of Natural Numbers Using Recursion


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

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


Source Code: C Program To Find Sum of Natural Numbers Using Recursion

#include<stdio.h>

int sum(int num)
{
    if(num)
        return(num + sum(num-1));
    else
        return 0;
}

int main()
{
    int count = 25;

    printf("Sum of 1st 25 natural numbers is %d\n", count, sum(count));

    return 0;
}

Output:
Sum of 1st 25 natural numbers is 325

Logic To Find Sum of Natural Numbers Using Recursion

25 is passed to a function sum, from main method. Inside function sum(), if the passed number is a non-zero then we add sum(num-1) to num. We keep doing it until num value is 0. Once num is 0, code inside else block gets executed and 0 is returned.

Source Code: Find Sum of Natural Numbers Using Recursion – Take input from user

#include<stdio.h>

int sum(int num)
{
    if(num)
        return(num + sum(num-1));
    else
        return 0;
}

int main()
{
    int count;

    printf("Enter a positive no\n");
    scanf("%d", &count);

    printf("Sum of 1st %d natural numbers is %d\n", count, sum(count));

    return 0;
}

Output 1:
Enter a positive no
5
Sum of 1st 5 natural numbers is 15

Output 2:
Enter a positive no
14
Sum of 1st 14 natural numbers is 105

Example:

Lets assume user has input num value as 5.
Recursive Call sum(num – 1).

numCalling FunctionReturned Value
5sum(5)
5sum(4)10
4sum(3)6
3sum(2)3
2sum(1)1
1sum(0)0
0return 0;

Value Returning – Control Shifting back.

num+sum(num-1)Return ValueResult
1 + sum(0)01 + 0 = 1
2 + sum(1)12 + 1 = 3
3 + sum(2)33 + 3 = 6
4 + sum(3)64 + 6 = 10
5 + sum(4)105 + 10 = 15

Finally, after completing the recursive calls and once num is equal to zero, sum() will return 15 to main().

i.e., 1 + 2 + 3 + 4 + 5 = 15.

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 Print Natural Numbers using Recursion

Lets write a C program to print/display natural numbers from 1 to user entered limit, using recursive function calls.

Related Read:
C Program to Print Natural Numbers from 1 to N using While loop
C Program to Print Natural Numbers from 1 to N using for loop
Recursive Functions In C Programming Language

Video Tutorial: C Program To Print Natural Numbers from 1 To N using Recursion


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

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


Source Code: C Program To Print Natural Numbers using Recursion

#include<stdio.h>

void display(int);

int main()
{
    int limit;

    printf("Enter the number of terms to be printed\n");
    scanf("%d", &limit);

    printf("\nNatural Numbers from 1 To %d are:", limit);
    display(limit);

    return 0;
}

void display(int num)
{
    if(num)
        display(num-1);
    else
        return;

    printf("\n%d\n", num);
}

Output:
Enter the number of terms to be printed
14

Natural Numbers from 1 To 14 are:
1

2

3

4

5

6

7

8

9

10

11

12

13

14

Logic To Print Natural Numbers using Recursion

We ask the user to input the limit or the number of terms of natural numbers to be printed. We store that value inside variable limit. We pass this value to a function called display().

Inside display() function
We check if number is not zero, in that case we call the same function display() recursively and pass (num-1) to it. In the else block we write the base condition, that is, return the control back to the calling function if num is 0.

This prints the natural numbers from 1 to user input limit.

Example:

If limit = 5. We copy the value of limit to num. So num = 5.

numCalling FunctionCalled Function
5main()display(5)
5display(5)display(4)
4display(4)display(3)
3display(3)display(2)
2display(2)display(1)
1display(1)display(0)
returns the control backdisplay(0)return;

Value Returning – Control Shifting back.

FunctionReturn Value
return;
display(0)1
display(1)2
display(2)3
display(3)4
display(4)5

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 Reverse a Number using Recursion

Lets write a C program to reverse a user input number, using recursive function.

Example: If user input number is 12345, recursive function should return 54321 i.e., the reversed number.

Related Read:
C Program To Reverse a Number
Recursive Functions In C Programming Language

Video Tutorial: C Program To Reverse a Number using Recursion


[youtube https://www.youtube.com/watch?v=yQt27d-OBfk]

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


Source Code: C Program To Reverse a Number using Recursion

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

int reverse(int num)
{
    if(num)
        return( (num%10) * pow(10, (int)log10(num)) + reverse(num/10) );
    else
        return 0;
}

int main()
{
    int num, isNegative = 1, result = 0;

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

    isNegative = (num < 0);

    if(isNegative)
        num *= -1;

    result = reverse(num);

    if(isNegative)
        result *= -1;


    printf("Reverse of %d is %d\n", num, result);

    return 0;
}

Output 1:
Enter a number to reverse
12345
Reverse of 12345 is 54321

Output 2:
Enter a number to reverse
-12345
Reverse of -12345 is -54321

Logic To Reverse a Number using Recursion

We ask the user to input a number, and store it inside variable num. If num is negative, then we store 1(true) inside variable isNegative or store 0(false) inside variable isNegative if num is positive.

If isNegative is 1, then we change the value of num to positive and send it as argument to reverse() function.

Inside reverse() function
If num is 0, it returns 0. Else we recursively call reverse() function as follows:

(num%10) * pow(10, (int)log10(num)) + reverse(num/10)

num % 10 gives the last digit in the number.
log10(num) gives the length of the number or the number of digits present in the number. The count starts from 0. Ex: if num = 12345, then log10(num) would give 4.

num/10 reduces the number by 1 digit from right.

pow(10, (int)log10(num)) is used to properly place the reminder value in its decimal place.

Lets assume that user has input 1234 as value of num.

i.e., num = 1234;

Recursive Function Calls – Stacking of calls

numnum % 10num%10*log10(num)num/10
1234reverse(1234)
123444 * 103 = 4000reverse(123)
12333 * 102 = 300reverse(12)
1222 * 101 = 20reverse(1)
111 * 100 = 1reverse(0)

Value Returning – Control Shifting back.

Return ToresultresolveReturn Value
reverse(0)0
reverse(1)1* 100+reverse(0)1 * 1 + 01
reverse(12)2*101+reverse(1)2 * 10 + 121
reverse(123)3*102+reverse(12)3 * 100 + 21321
reverse(1234)4*103+reverse(123)4 * 1000 + 3214321

Note: Whenever there is a call to a function, the function instance(and memory associated with it) gets stored in the memory stack. Once the function returns value to calling function, the control shifts back to the calling function and the memory instance gets popped or deleted out of the memory stack immediately after returning the value.

Source Code: C Program To Reverse a Number using Recursion and Ternary Operator

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

int reverse(int num)
{
return( (num>0) ?
        ((num%10) * pow(10, (int)log10(num)) + reverse(num/10)) :
         0);
}

int main()
{
    int num, isNegative = 1, result;

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

    isNegative = (num < 0);

    if(isNegative)
        num *= -1;

    result = reverse(num);

    if(isNegative)
    {
        num *= -1;
        result *= -1;
    }


    printf("Reverse of %d is %d\n", num, result);

    return 0;
}

Output 1:
Enter a number to reverse
123
Reverse of 123 is 321

Output 2:
Enter a number to reverse
-123
Reverse of -123 is -321

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

Source Code: C Program To Reverse a Number using Recursion without using log10() function

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

int reverse(int num, int len)
{
    if(num)
        return( (num%10) * pow(10, len-1) + reverse(num/10, len-1) );
    else
        return 0;
}

int main()
{
    int num, count = 0, temp;

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

    temp = num;

    while(temp)
    {
        count++;
        temp = temp / 10;
    }

    printf("Reverse of %d is %d\n", num, reverse(num, count));

    return 0;
}

Output 1:
Enter a number to reverse
123456
Reverse of 123456 is 654321

Output 2:
Enter a number to reverse
-123456
Reverse of -123456 is -654321

Logic To Reverse a Number using Recursion without using log10() function

Inside main method itself we calculate the number of digits present in the user entered number and then pass that information to the function reverse() along with the user entered number.

reverse(num, count);

Inside reverse() function
Inside reverse() function, we get the reminder by modulo dividing num by 10. We place this remainder in it’s decimal place by multiplying it with

pow(10, len-1)

where len is the length or the number of digits present in the number.

Next we recursively call reverse() function and pass the value of (num/10) and (len-1).

Finally we combine all these results using below formula and return the value to the calling function recursively, until num is equal to 0:

(num%10) * pow(10, len-1) + reverse(num/10, len-1)

Look at above tables to know the calling function and return values.

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 Calculate Sum of Digits Using Recursion

A 5-digit positive integer is entered through the keyboard, write a recursive and a non-recursive function to calculate sum of digits of the 5-digit number.

Analyze The Problem Statement

1. User enters a 5-digit number.
2. We need to write 2 functions to calculate sum of digits of user entered number.
3. One function should use recursive logic and the other should calculate sum of digits without using recursion.

Related Read:
Recursive Functions In C Programming Language
Calculate Sum of Digits: C Program

Video Tutorial: C Program To Calculate Sum of Digits Using Recursion


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

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


Source Code: C Program To Calculate Sum of Digits Using Recursion

#include<stdio.h>

int add(int);
int add_rec(int);

int main()
{
    int num;

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

    printf("Sum of Digits(without using recursion): %d\n", add(num));
    printf("Sum of Digits(using recursion): %d\n", add_rec(num));

    return 0;
}

int add(int num)
{
    int sum = 0;

    while(num)
    {
        sum = sum + (num % 10);
        num = num / 10;
    }

    return(sum);
}

int add_rec(int num)
{
    if(num)
        return( (num % 10) + add_rec(num / 10) );
    else
        return 0;
}

Output 1:
Enter a 5-digit positive integer number
12345
Sum of Digits(without using recursion): 15
Sum of Digits(using recursion): 15

Output 2:
Enter a 5-digit positive integer number
15937
Sum of Digits(without using recursion): 25
Sum of Digits(using recursion): 25

Logic To Calculate Sum of Digits without using Recursion

1. Using (num % 10), we fetch the last digit of the user entered number and add it to the previous value of sum.
2. Next we reduce the uer entered number by 1 digit(from the right end) by dividing the number by 10 i.e., num / 10.
3. We put above two steps/logic into while loop. We iterate through the while loop until num is positive. Once num value is 0, control exits the while loop.
4. Outside while loop we return the value present in variable sum – which will have the sum of all the individual digits of the user entered number.
If num = 12345;

numnum%10sumnum/10
12345551234
123449123
12331212
122141
11150

If you observe above table, when num becomes 0, sum has 15 in it. So 15 is the sum of all the individual digits of the user entered number 12345.

i.e., 1 + 2 + 3 + 4 + 5 = 15.

Full logic with separate video explaining this concept is present at Calculate Sum of Digits: C Program. Kindly watch it without fail.

Logic To Calculate Sum of Digits using Recursion

If num is positive we execute below line of code

return( (num % 10) + add_rec(num / 10) );

If num is 0, then we return zero.

Recursive Function Calls – Stacking of calls

Call Fromnum % 10add_rec(num / 10)
add_rec(12345)5add_rec(1234)
add_rec(1234)4add_rec(123)
add_rec(123)3add_rec(12)
add_rec(12)2add_rec(1)
add_rec(1)1add_rec(0)

Value Returning – Control Shifting back.

Return To(num % 10) + resultReturn value
add_rec(0)return(0)0
add_rec(1)1 + add_rec(0)1 + 0 = 1
add_rec(12)2 + add_rec(1)2 + 1 = 3
add_rec(123)3 + add_rec(12)3 + 3 = 6
add_rec(1234)4 + add_rec(123)4 + 6 = 10
add_rec(12345)5 + add_rec(1234)5 + 10 = 15

So at the end 15 is returned back to main() method and the result is printed on the console window.

Note: Whenever there is a call to a function, the function instance(and memory associated with it) gets stored in the memory stack. Once the function returns value to calling function, the control shifts back to the calling function and the memory instance gets popped out of the memory stack immediately after returning the value.

Ternary or Conditional Operator And Recursion

int add_rec(int num)  
{  
    return( ( num > 0 ) ? ( (num % 10) + add_rec(num / 10) ) :  0 );

}  

You can even write the recursive logic to find sum of digits of a number using above ternary or conditional operator.

Source Code: C Program To Calculate Sum of Digits Using Recursion And Ternary Operator

#include<stdio.h>

int add(int);
int add_rec(int);

int main()
{
    int num;

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

    printf("Sum of Digits(without using recursion): %d\n", add(num));
    printf("Sum of Digits(using recursion): %d\n", add_rec(num));

    return 0;
}

int add(int num)
{
    int sum = 0;

    while(num)
    {
        sum = sum + (num % 10);
        num = num / 10;
    }

    return(sum);
}

int add_rec(int num)
{
    return( ( num > 0 ) ? ( (num % 10) + add_rec(num / 10) ) :  0 );
}

Output 1:
Enter a 5-digit positive integer number
12345
Sum of Digits(without using recursion): 15
Sum of Digits(using recursion): 15

Output 2:
Enter a 5-digit positive integer number
98654
Sum of Digits(without using recursion): 32
Sum of Digits(using recursion): 32

You can know more about Ternary or Conditional Operators in this 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

Recursive Functions In C Programming Language

Lets learn recursive functions in C programming language, with examples and illustrations of memory and function instances in the stack.

Stake is a Data Structure and we’ll be discussing it once we start teaching Data Structures using C topics. For now consider it as a memory stack and some organized structure to hold data, which follows LIFO rule. i.e., Last In, First Out

That is, the last instance which enters the stack is the one which leaves the stack first.

Related Read:
Function / Methods In C Programming Language

Recursive Function: A function calling itself, within it’s own function definition is called Recursive Function.

Types of Recursive Functions

There are 4 types of recursive functions:
1. Direct Recursive function.
2. In-direct Recursive function.
3. Tail Recursive function.
4. Non-tail Recursive function.

We’ll discuss each one in separate video tutorials.

In this video tutorial lets learn the very basic of how to write and use recursive functions and how to keep track of function instances and return data.

Requirements To Learn Recursion

1. You need to know basics of C programming language. If you’re a total beginner, then we do not advice you to start with recursive functions. Just go to this page C Programming: Beginner To Advance To Expert and start watching the C program video tutorials one by one, and in no time you’ll be an advance user and you can learn/understand Recursive functions.

2. If you know the basics, then grab a piece of paper and get a pen. Write down the program on the paper, and also write the function call instances and track the variable values. Write everything we’re explaining in this video tutorial. If you get any doubts, write it down too. Watch the video once again and check if your doubts are cleared. If its still not cleared, follow the next step.

3. Turn on your computer and your favorite C editor, and type the program. Don’t copy paste it. Write the code yourself. Better if you write it without looking at the source code we’ve posted below. Once you execute and get the results, edit/modify the source code and check for different results. Check if you can edit the program and clarify your doubts. If you still don’t understand, then use the comment section below and ask your doubts.

4. Even if you understood the concept well, please visit the comment section below and try to help other students understand it. By teaching, you learn more.

Video Tutorial: Recursive Functions In C Programming Language


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

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


Source Code: Recursive Functions In C Programming Language: Example

#include<stdio.h>

void natural(int);

int main()
{
    int num = 1;

    natural(num);

    return 0;
}

void natural(int num)
{
    if(num <= 3)
    {
        natural(num+1);
        printf("%d  ", num);
    }

    return;
}

Output:
3 2 1

Logic To Print natural numbers from 1 to 3 using Recursion

We call natural() function and pass num to it. Initial value of num is set to 1. Inside natural() function/method we check if the value of num is less than or equal to 3. If true, we call the method natural() and pass num+1 to it. Once num is greater than 3, return statement executes and the control transfers to the calling function and the remaining code in that function gets executed. In our program we have printf statement after the recursive function call. So our program prints the value of num and then transfers the control to the calling function.

SlnonumFunction Call
11main()
21nature(1+1)
32nature(2+1)
43nature(3+1)
54nature(4+1)

Each time the recursive call is executed, an instance of the function and memory associated with it is pushed or added to the stack. And for each time the return statement is executed, the function and the memory associated with it is popped or deleted from the stack.

Stack is a Data Structure used to store data in some organized way. For now just know that its a memory stack in your RAM. It’s like a basket which holds the data in particular order. The data is stored one upon another. So the one which gets inserted or pushed at the last is the one which gets popped out first. This concept is called LIFO. Which means, Last In, First Out.

5
4
3
2
1

So we have 5 numbers inside the stack. If we want to add 6 to it, it’ll sit at the top of 5. In above stack, if you want to pop out, the first number you can pop out is the last number present in the stack, which is 5. You can only pop out the items one by one in this order, from above stack: 5, 4, 3, 2, 1.

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