Been brushing up my C,C++ for my new venture in Graduate Studies for this fall.I am doing basic programs in which I am trying this one right now.
A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:
(1) Without using recursion
(2) Using recursion
I am entering five digit number as a character array and I am trying to add them.
(I found it clumsy to construct conventional method using %,/ operators to implement in functions.)
I am trying hands on various functions of string handling to add the digits but no success.Another thing my recursive function 'sumr' is not giving any output on terminal and 'sumd' is giving output as 20 however may be the digit entered.
I am using Netbeans.Here is the code snippet that I have created.
A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:
(1) Without using recursion
(2) Using recursion
I am entering five digit number as a character array and I am trying to add them.
(I found it clumsy to construct conventional method using %,/ operators to implement in functions.)
I am trying hands on various functions of string handling to add the digits but no success.Another thing my recursive function 'sumr' is not giving any output on terminal and 'sumd' is giving output as 20 however may be the digit entered.
I am using Netbeans.Here is the code snippet that I have created.
Code:
#include <stdio.h>
#include<ctype.h>
#include<stdlib.h>
main()
{
char n[5];
int sum,csum;
printf("Enter 5 digit number\n");
gets(n);
int sumd(char *);
int sumr(char *);
sum=sumd(&n[0]);
printf("\nThe sum of the digits without recursion is %d\n",sum);
csum=sumr(&n[0]);
printf("\nThe sum of digits with recursion is %d\n",csum);
return 0;
}
int sumd(char *p)
{
int j,sum=0;
for(j=0;j<5;j++)
{
sum=sum+(isdigit(*p));
p++;
}
return sum;
}
int sumr(char *q)
{
int gsum;
gsum=(isdigit(*q))+sumr(q++);
return gsum;
}
Comment