Finding the length and sum of integers of any number - The use of global variable in C

Variables are very important in almost every cases. Normally we use local variables but it is sometimes necessary to use global variables. We can not skip that matter with local variables. One of such kind of a problem is finding the sum of integers of any number. I have tried many times to use local variable here but failed. If you can please suggest me. But the program code is given here which I have written.


It is to be said that I had no interest on such kind of programs. But once our honourable teacher, MR. Aminul Islam told me to do this program (finding the sum of integers of any number) and then I became keen to do it. However the source code is bellow.

#include<stdio.h>
int s=0;
main()
{
v2();
}

v2()
{
    int a,b,c;
    printf("Enter number:\n");
    scanf("%d",&a);
    b = sum(a);
    c = length(a);
    printf("\nNumber: %d\nLength of it is: %d\nSum of the integers:%d\n\n",a,c,b);

}

sum(int n)
{
    int nn=0,nnn=0;
    nn = n/10;
    nnn = n - nn*10 ;
    s = s + nnn;
    if(nn>0)
        sum(nn);
return s;


}

length(int n)
{
    int l=1;
    while(n>9){ l++; n/=10; }
  return l;
}


I hope it will help you along with me.

Happy programming. 

Related Posts
Previous
« Prev Post