+ 2

# as far as of my assumption this loop will be infinite then how i m getting the result. i would appreciate any help.

public class Program { public static void main(String[] args) { int result = 0; for(int i = 0;i<8;i--) { if(i==7){ result +=3; }else{ result +=i; } } System.out.println(result); } }

4 Answers

+ 1

looks like you guys haven't understood my question.my question is that that in the else statement it is programed that result is 'result + i' but i m decrementing the 'i' so it will be decremented infinitely and result+i will also run infinitely so how i m getting the result.

+ 17

shobhit
maybe u could set the For Loop to execute a specific number of times..
or
adjust the initial i-condition (i<8) to something like: (i<8 && i !<0), in other words,
i less than 8 AND i NOT less than zero.
plz let me know how your problem turns out..
i don't undetstand, but just couldn't resist trying
thanks

+ 17

shobhit
to me, it looks like result remains zero
after the first pass: i=0. result=0, !(i==7)
so (result+=i) evaluates tp 0..
the For loop could be set to run a specific numbet of times or maybe the conditipn

0

your code have no chance to be 7 rather it decreases down to neg Infinity, and holds true for the condition (i<8), and hence loops forever, simply incrementing the value of result by i. I tried to eliminate the infinite loop, try it as follows if I got your question correctly.
public class Program
{
public static void main(String[] args) {
int result = 0;
for(int i = 0;i<8;i++) {
if(i==7){
result +=3;
}else{
result +=i;
}
}
System.out.println(result);
}
}
result will become 0+1+2+3+4+5+6+3=24,
and the output is 24.