Computer Applications
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;
}
Java
Java Iterative Stmts
ICSE 2023
65 Likes
Answer
9
2
Working
Step by step explanation of the code:
int n = 4279;
— Initializes the integern
with the value 4279.int d;
— Declares an integer variabled
without 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 whenn
is divided by 10 and stores it ind
. In the first iteration,d
will 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 ofn
by 100. In the first iteration,n
becomes 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;
—d
will now be 2 because the remainder of 42 divided by 10 is 2.System.out.println(d);
— It prints 2.n = n / 100;
—n
becomes 0 because 42 divided by 100 is 0. Sincen
is no longer greater than 0, the loop terminates.
Answered By
32 Likes
Related Questions
Give the output of the following Character class methods:
(a) Character.toUpperCase ('a')
(b) Character.isLetterOrDigit('#')
Rewrite the following code using the if-else statement:
int m = 400; double ch = (m>300) ? (m / 10.0) * 2 : (m / 20.0) - 2;
Give the output of the following String class methods:
(a) "COMMENCEMENT".lastIndexOf('M')
(b) "devote".compareTo("DEVOTE")
Consider the given array and answer the questions given below:
int x[ ] = {4, 7, 9, 66, 72, 0, 16};
(a) What is the length of the array?
(b) What is the value in x[4]?