Core Java Practical
Core Java Practical
Sample Output:
yaml
SOURCE CODE
Enter a string: Hello World 123!
Letters: 10
Spaces: 2
Numbers: 3
Other characters: 1
Implement a Java function that calculates the sum of digits for a given
char array consisting of the digits '0' to '9'. The function should return the
digit sum as a long value.
java
SOURCE code
public class DigitSumCalculator {
return sum;
}
Explanation:
1. Function Definition:
o The function calculateDigitSum() takes a char[] (char array) as
input.
o It uses a loop to iterate through each character in the array.
o For each character, it checks if the character is between '0'
and '9' using simple character comparison.
o If the character is a valid digit, it converts it to its numeric
value by subtracting '0' from the character (which gives the
corresponding numeric value of the digit).
o The result is accumulated in the sum variable, which is of type
long to handle large sums.
2. In the main() method:
o An example char[] array is created with the digits '1' to '9' and
'0'.
o The calculateDigitSum() function is called with the array, and the
result is printed.
Sample Output:
python
Copy code
The sum of the digits is: 45
// Iterate through the array to find the smallest and largest elements
for (int i = 1; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
if (array[i] > largest) {
largest = array[i];
}
}
// Call the function to find and print the smallest and largest elements
findMinMax(array);
}
}
Explanation:
1. findMinMax Function:
o This function accepts an integer array as an argument.
o We initialize smallest and largest with the first element of the
array.
o The program loops through the array from the second element
onward. For each element:
If the element is smaller than the current smallest, we
update smallest.
If the element is larger than the current largest, we
update largest.
o After completing the loop, the smallest and largest elements
are printed.
2. In the main() method:
o An example array {3, 56, 7, 89, 12, 5, -2, 18} is used.
o The findMinMax function is called to find and display the
smallest and largest elements.
Sample Output:
yaml
Copy code
Smallest element: -2
Largest element: 89
Explanation of Output:
The smallest element in the array {3, 56, 7, 89, 12, 5, -2, 18} is -2.
The largest element is 89.
This program will work with any integer array and correctly find the
smallest and largest values. Let me know if you'd like further
modifications!