Page 186 - Cs_withBlue_J_C11_Flipbook
P. 186
int s=0;
for(; n>0; n=n/10)
{
s=s+n%10;
}
return s;
}
void main()
{
Scanner sc= new Scanner(System.in);
int num,sum;
System.out.println("Enter a number ");
num=sc.nextInt();
sum=sod(num);
System.out.println("Sum of digits "+sum);
}
}
The output of the preceding program is as follows:
Enter a number
45
Sum of digits 9
8.5 MATHEMATICAL FUNCTIONS
There are many in-built methods in Java that help us to perform mathematical tasks quite easily. These in-built methods
are pre-defined functions that are already declared in some packages. To use the in-built functions, we must include
those packages in our program by using the following syntax:
import java.packagename.classname;
For example:
To include the util package which contains the Scanner class, we must use the following at the beginning of the program.
import java.util.*;
These built-in methods are also called Library or System methods. There are many types of library or system methods,
e.g., String methods, Mathematical methods, Graphics methods, etc. In this chapter, we shall deal with the different
types of Mathematical methods that are frequently used in coding.
To use Mathematical methods in programs, we need to use “Math” class which resides in “java.lang” package. But
since this lang package is included in the program automatically, we do not have to include it separately by writing the
import syntax.
To use it in the program, the syntax “Math. function name(arguments)” is used.
8.5.1 Different Mathematical Methods
1. Math.min()
This function finds the minimum number between two number arguments passed to it as parameters.
Example 1: double m=Math.min(23.9,24.32); Output: 23.9
184184 Touchpad Computer Science-XI

