166k views
2 votes
What is the purpose of the following code in Java?

class Main {
public static void main(String[] args) {
int num = 1234567, reversed = 0;
for(; num != 0; num /= 10) {
int digit = num % 10;
reversed = reversed * 10 + digit;
}
System.out.println(Reversed Number: " + reversed);
}
}

a) To calculate the sum of all digits in the number 1234567.
b) To calculate the product of all digits in the number 1234567.
c) To reverse the digits of the number 1234567.
d) To print the number 1234567 as it is without any changes.

1 Answer

2 votes

Final answer:

The purpose of the given Java code is to reverse the digits of a number.

Step-by-step explanation:

The purpose of the given code in Java is to reverse the digits of the number 1234567.

The code uses a for loop to iterate through each digit of the number and extracts the digit using the modulo operator.

The extracted digit is then added to the reversed number by multiplying it by 10 and adding the extracted digit.

For example, if the number is 1234567, the first iteration of the loop will extract the last digit (7) and add it to the reversed number (0), resulting in a reversed number of 7.

In the second iteration, the next digit (6) will be extracted and added to the reversed number, resulting in a reversed number of 76.

This process continues until all the digits are reversed.

Finally, the reversed number is printed using the System.out.println statement.

User Lasitha Benaragama
by
7.4k points