Reputation: 11
//Program to print the summation of a five-digit or less than 5 digit number entered using recursion.
#include <stdio.h>
#include <conio.h>
int summation(long int num) //summation function.
{
int sum = 0, rem;
if (num < 10)
return num;
else
{
for (int i = 0; i <= 4; i++)
{
rem = num % 10;
sum = sum + rem;
summation(num / 10);
}
return sum;
} //End else.
} //End summation.
int main()
{
long int data;
int ans;
int summation(long int num);
clrscr();
printf("Enter a number");
scanf("%ld", &data); //Taking the input of data.
ans = summation(data); //Calling the funcion.
printf("%d", ans); //Printing the output.
getch();
return 0;
} //End main.
In this program, when I called the function by passing the argument as num/10
then it gave a wrong answer. Instead, if I wrote num =num/10
and called the function by passing num
as an argument I got the right answer. Why is this happening? Are both statements the same thing?
Upvotes: 1
Views: 87
Reputation: 189307
You are mixing recursion and loops. Use either, but not both. (Of course, the assignment says to use recursion, so do that.)
Loop solution (pseudocode):
int summation(number) {
for (digit in number)
sum += digit;
return sum;
}
Recursion (pseudocode):
int summation(number) {
if (number < 10) return number;
else {
dv = number%10;
return dv + summation(number // 10);
}
}
Notice how the latter calls itself, and also how that call return
s the value from the new call to the caller, building a chain between them.
Upvotes: 1
Reputation:
#include<stdio.h>
int summation(int);
int main(){
int val,sum;
scanf("%d",&val);
sum=summation(val<0?-val:val);//We need the absolute value
printf("%d",sum);
return 0;
}
//Get the sum recurcively
int summation(int v){
if(v==0)
return 0;
return (v%10)+summation(v/10);//v%10 is the reminder which is the last digit
}
Upvotes: 0