Tuesday, July 14, 2009

I'm having trouble in running the user defined function in C programming?

I can printf for 0 to 9 but not %26gt; 9


#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;math.h%26gt;





int main(void)


{ int input, sum=0, product=1;


void spdigit(int, int*, int*);





printf("If number = ");


scanf("%d", %26amp;input);





spdigit(input, %26amp;sum, %26amp;product);


printf("SDIGIT = %d\n", sum);


printf("PDIGIT = %d\n", product);





return 0;


}





void spdigit(int input3f, int *sumf, int *productf)


{ int noofdigits, counter=0, i;





do


{counter++;


noofdigits = input3f/10;


} while ( noofdigits != 0 );





int remainder1[counter], remainder2[counter];





remainder1[0] = input3f%10;


remainder2[0] = remainder1[0];





for ( i=1; i%26lt;counter; i++ )


{ remainder1[i] = input3f%(10*i);


remainder2[i] = remainder1[i]; }





*sumf+=remainder1[0];


*productf*=remainder1[0];





for ( i=1; i%26lt;counter; i++ )


{ remainder2[i]-= remainder1[i-1];


remainder2[i]/= 10*i;


*sumf+=remainder2[i];


*productf*=remainder2[i]; }


}

I'm having trouble in running the user defined function in C programming?
The corrected %26amp; tested (for several times) code is--------------------------------------...

















#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;math.h%26gt;





void spdigit(int input3f, int *sumf, int *productf)


{


int noofdigits,b=1,counter=0, i=input3f;


int *rem1;


do


{


counter++;


noofdigits = i/10;


i=i/10;


}


while ( noofdigits != 0 );


i=0;


rem1=(int *)malloc(sizeof(int)*counter);


*(rem1+0) = input3f%10;


b=input3f;


for (i=1; i%26lt;counter; i++ )


{


b=b/10;


*(rem1+i)=b%10;


printf("\n%d",*(rem1+1));


}


*sumf+=*(rem1+0);


*productf*=*(rem1+0);


for ( i=1; i%26lt;counter; i++ )


{


*sumf+=*(rem1+i);


*productf*=*(rem1+i);


}


}

















Corrections are:-%26gt;


1. you can use malloc for dynamic memory allocation.


2. It is not necessary to use remainder2


instead I have used variable b whose value is inpower of 10 %26amp; which divides the total value each time by 10 so that eliminiting last digit. All Digits are stored in array pointed by rem1.











Thank you.





Mandar Gurav


Walchand College of Engineering,


Sangli,


Maharashtra,


India.
Reply:All of your printf function calls look good, so my guess is that the problem is in the spdigit function. Use a debugger to make sure that spdigit is doing what you want/expect/need it to do.





You could try this to test your printf for multi-digit output if you really want to:





int x = 1234;


printf("%d\n", x);
Reply:Your do while loop is faulty


No comments:

Post a Comment