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

Text Stacking: CSS & JavaScript

Develop and demonstrate, using Javascript, a xHTML document that contains three short paragraphs of text, stacked on top of each other, with only enough of each showing so that the mouse cursor can be placed over some part of them. When the cursor is placed over the exposed part of any paragraph, it should rise to the top to become completely visible.

Video Explaining the program:



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


HTML coding:

Info:
Div tag is a block-level element.

In HTML code we have used unique ids for the div tags: one, two, three. The same ids have been used in CSS(to assign style information) as well as in the Javascript(for functionality) file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
<html>
 <head>
  <title>Text Stacked On Top Of EachOther: CSS & JavaScript</title>
  <link rel="stylesheet" href="style.css" type="text/css">
  <script type="text/javascript" src="stacked.js"></script>
 </head>
 <body>
 
<div id="one" onmouseover="moveIt('one')">
Microsoft Dominates!<br />
Windows 7 is getting popular!
</div>
 
<div id="two" onmouseover="moveIt('two')">
Apple may Dominate!<br />
iTV may takeoff in the market!
</div>
 
<div id="three" onmouseover="moveIt('three')">
Google Rocks!!<br />
We all know that!!!! :-) 
</div>
 
 </body>
</html>

Cascading StyleSheet(CSS) coding:
In CSS, we assign Verdana as the font for the entire body, with font size as 24 points(pt).
Next, using the id(present in the HTML code below) we assign styling information to each div tags.
Positioning is absolute.
We have varied 20 pixels from top and 20 pixels from left for each div, so that the text overlaps on each other leaving 20 pixels(from top as well as from left) of space for mouse over.
We have also changed the background-color and foreground-color of the text inside div tags, so that each div stands out from the other.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 
body {
font-family: verdana;
font-size: 24pt;
}
 
#one {
position: absolute;
top: 200px;
left: 300px;
 
background-color: black;
color: white;
}
 
#two {
position: absolute;
top: 220px;
left: 320px;
 
background-color: cyan;
color: black;
}
 
#three {
position: absolute;
top: 240px;
left: 340px;
 
background-color: pink;
color: yellow;
}

JavaScript coding:
In Javascript, we declare a variable called topLayer and assign it the value three(which is a id name).
Next inside the function moveIt we declare another variable called oldTop, in which we store the style information of topLayer variable(which contains id “three”).
Similarly, in variable newTop we store the style information of the toTop(which we receive as parameter to moveIt function).

We can also combine those two lines of code as shown below:

1
2
3
 
    var oldTop   =   document.getElementById(topLayer).style.zIndex = "0";
    var newTop =   document.getElementById(toTop).style.zIndex = "10";

Note: Higher the value of z-index(in CSS) or zIndex(in javascript), nearer it looks to the user viewing it.

In javascript, while writing style property name, make use of capital latter immediately after the hyphen and eleminate the actual hyphen.

Example:
In CSS: background-color
In JS : backgroundColor

In CSS: z-index
In JS : zIndex

In CSS: font-weight
In JS : fontWeight

In CSS: border-style
In JS : borderStyle

etc, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
var topLayer = "three";
 
function moveIt(toTop) {
 
    var oldTop   =   document.getElementById(topLayer).style;
    var newTop =   document.getElementById(toTop).style;
 
    oldTop.zIndex   = "0";
    newTop.zIndex = "10";
 
    topLayer = document.getElementById(toTop).id;
 
 
}

At the end of the function we reset the value of topLayer variable with the id name which invoked the function.
Note:
Make sure to save all these (.html, .css and .js : HTML, CSS and Javascript) files in the same folder or else change the path in the header as appropriate.