Q8 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.

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.

Program: 129

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.

How to use recursion and non recursion function to get sum of a positive integer digit.

 

#include<stdio.h>
int rec_func(int num);
int non_rec_func(int num);

void main()
{
    int num, rec, non_rec;
    printf("Enter an integer: ");
    scanf("%d", &num);

    rec = rec_func(num);
    non_rec = non_rec_func(num);

    printf("\n Calculate sum using recursion: %d",rec);
    printf("\n Calculate sum without recursion: %d",non_rec);
}

int rec_func(int num)
{
    if (num==0)
    {
        return 0;
    }

    return (num%10+rec_func(num/10));
}

int non_rec_func(int num)
{
    int res, count=0;
    while(num!=0)
    {
        res=num%10;
        count += res;   //count=count+res;
        num = num/10;
    }
    return count;
}

Output:

Enter an integer: 12345
 Calculate sum using recursion: 15
 Calculate sum without recursion: 15

Lokesh Kumar: Being EASTER SCIENCE's founder, Lokesh Kumar wants to share his knowledge and ideas. His motive is "We assist you to choose the best", He believes in different thinking.
Related Post
Leave a Comment

This website uses cookies.