Give the output of the following program segment:
int n = 4279; int d;
while(n > 0)
{ d = n % 10;
System.out.println(d);
n = n / 100;
}
Single Choice
Views 72
Answer:
Output
9
2
Explanation
Step by step explanation of the code:
int n = 4279;— Initializes the integernwith the value 4279.int d;— Declares an integer variabledwithout initializing it. It will be used to store the individual digits.
Now, let's go through the loop:
The while loop continues as long as n is greater than 0:
d = n % 10;— This line calculates the remainder whennis divided by 10 and stores it ind. In the first iteration,dwill be 9 because the remainder of 4279 divided by 10 is 9.System.out.println(d);— This line prints the value ofd. In the first iteration, it will print 9.n = n / 100;— This line performs integer division ofnby 100. In the first iteration,nbecomes 42. (Remember, it is integer division so only quotient is taken and fractional part is discarded.)
The loop continues, and in the second iteration:
d = n % 10;—dwill now be 2 because the remainder of 42 divided by 10 is 2.System.out.println(d);— It prints 2.n = n / 100;—nbecomes 0 because 42 divided by 100 is 0. Sincenis no longer greater than 0, the loop terminates.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.