A 5-digit positive integer is entered through the keyboard ,write a recursive and non-recursive function sum of the 5-digit number.
A 5-digit positive integer is entered through the keyboard ,write a recursive and non-recursive function sum of the 5-digit number.
1. Non-Recursive
copy:-
#include<stdio.h>
int main()
{
unsigned int n;
int y = 0 ;
printf("\nEnter the value: ");
scanf("%u",&n);
while(n!=0)
{
y = y +(n%10);
n = n/10;
}
printf("\nSUM = %d",y);
return 0;
}
int main()
{
unsigned int n;
int y = 0 ;
printf("\nEnter the value: ");
scanf("%u",&n);
while(n!=0)
{
y = y +(n%10);
n = n/10;
}
printf("\nSUM = %d",y);
return 0;
}
2. Recursive
#include<stdio.h>
int y;
int main()
{
unsigned int n;
int s;
printf("\nEnter the value: ");
scanf("%u",&n);
s = sum(n);
printf("\nSUM = %d",s);
return 0;
}
int sum(unsigned int x)
{
if(x==0)
{
return y;
}
else
{
y = (x%10) + sum(x/10);/*recursion occurred here*/
return y;
}
}
int y;
int main()
{
unsigned int n;
int s;
printf("\nEnter the value: ");
scanf("%u",&n);
s = sum(n);
printf("\nSUM = %d",s);
return 0;
}
int sum(unsigned int x)
{
if(x==0)
{
return y;
}
else
{
y = (x%10) + sum(x/10);/*recursion occurred here*/
return y;
}
}
Comments
Post a Comment