# right or wrong

• 09-24-2008, 02:36 PM
jot321
right or wrong
/*WRITE A PROGRAM TO ACCEPT A NUMBER AND FIND THE SUM AND PRODUCT OF DIGITS OF A NUMBER USING FUNCTION NAME DIGIT(int n ) WHICH RECEIVES THE VALUES FROM THE MAIN()*/

class digitsp
{
void main(int a)
{
double a1=a;
digitsp obj = new digitsp();
int pro=obj.digit(a);
System.out.println(pro);

double sum=obj.digit(a1);
System.out.println((int)sum);
}

int digit(int n)
{
int d,pro=1;
do
{
d=n%10;
n=n/10;
pro=pro*d;
}
while(n!=0);
return pro;

}

double digit(double n)
{
int d,sum=0;
do
{
d=(int)n%10;
n=(int)n/10;
sum=sum+d;
}
while(n!=0);
return sum;
}
}

/*HAVE I DONE IT IN RIGHT MANNER*/
• 09-24-2008, 02:56 PM
Norm
Part of the assignment woud be: Does it give you the correct results?
Another part: Are descriptive variable names used? Score: D-
ANother part: is the code documented so that anyone reading it can understand what the code is supposed to do.
You'd get an F for that.

Don't convert double input to int and then back to double. You'll lose precision.
Add "text" in println() to describe what output is.
• 09-24-2008, 03:59 PM
serjant
Yes,Norm is right,just also add public static void main(String[] args) to compile and run the application
• 09-24-2008, 04:16 PM
jot321
yes you are right that i must have used descriptive variable and proper printing statements

results are coming accurate
i want to know that is there any other of d doing this program(easier) or this is the easiest way

• 09-24-2008, 04:30 PM
Norm
Quote:

THE SUM AND PRODUCT OF DIGITS OF A NUMBER
Can you describe what this means?
What would be the answers for the number 5(a single digit number base 10)?
What would be the answer for 22?
• 09-25-2008, 04:38 AM
Eranga
First: When you post a question please use code tags. It's really helpful to others. If you don't know how to do it, read FAQ page.

Second: Try to describe your question as much as possible. Seems to me other members have lots of doubts what you are trying to do.

Actually I'm not clear what you are trying to do here too. Are you looking product/sum of a number? If so, the answer to the Norms' question,

Number 22 - Sum = 4 and Product = 4
Number 34 - Sum = 7 and Product = 12

is it? But in that case what is the output for single digit number?
• 09-25-2008, 10:30 AM
jot321
in case of single digit the answer will be same as the number
number-9
sum-9
product-9

Number 22 - Sum = 4 and Product = 4
Number 34 - Sum = 7 and Product = 12

THIS IS CORRECT

i want to know that is there any other way other than function overloading
• 09-25-2008, 11:45 AM
Eranga
Actually you no need to overload. And also for int number you never can't get double value. Simply get each digit and process.