java - Entering numbers in program using while loop -
i beginner in java, can please explain me how total 11.
question - user ready enter in these numbers 1 one until program stops: 4 7 5 8 9 3 4 1 5 3 5
what displayed total?
int number; int total = 0; system.out.print("enter number"); number = input.nextint(); while (number != 1) { if (number < 5) total = total + number; system.out.print("enter number"); number = input.nextint(); } system.out.println(total);
i'll explain step step.
step - 1:
you've declared 2 integer variables. 1 holding input, , holding total value after calculation. integer total
initialized 0. following part of code doing this:
int number; int total = 0;
step - 2:
now you're providing input values. input values entering while loop. while loop continue execute unless input value 1. first input 4, 4!=1, so, enters loop.
system.out.print("enter number"); number = input.nextint(); while (number != 1) {
step - 3:
now, inside loop, you're checking whether input value less 5 or not. if it's less 5, total
value incremented total + number
. else, total
remains unchanged. regardless of if condition, system continue prompt provide number
inputs long it's not 1. following code this:
if (number < 5) total = total + number; system.out.print("enter number"); number = input.nextint(); }
in case, input sequence 4 7 5 8 9 3 4 1 5 3 5.
for first input 4, 4 < 5, true
, total = 0 + 4 = 4
. next input 7, 7 < 5 false
, total
remains 4, same goes inputs 5 through 9. when input 3, 3 < 5 true
, total = 4 + 3 = 7
. input 4, 4 < 5 true
again, total = 7 + 4 = 11
as we've seen, above while loop terminate, input 1. next input 1, loop terminate, can't input more number, , final total value remains 11.
step - 4:
outside loop, you're printing value of total
, display 11.
system.out.println(total);
p.s.
if understood solution, next task exact same thing using for loop
.
Comments
Post a Comment