I am new to programming and I am struggling in loops. Assume that I know nothing of programming and explain me by breaking down the problem I am posting here into pieces in simple language. Here's a code in Java and its output is 17:
int result = 0;
for (int i = 0; i<5; i ){
if (i==3){
result = 10;
}else{
result = i;
}
}
System.out.printIn(result);
Is here if statement is satisfied or else statement? Here,
i=0, result =0 =0
i=1, result =1 0 1 =1
i=2, result =2 1 2=3
i=3, result =10 3 10=13
i=4, result =4 13 4=17
My question is why does the loop proceed all the way upto i=4?
CodePudding user response:
If you want to break out of the loop use a break statement. Example see below code snippet if you want to break when value of i is 3.
int result = 0;
for (int i = 0; i<5; i ){
if (i==3) {
result = 10;
break;
} else{
result = i;
}
}
System.out.printIn(result);
CodePudding user response:
It looks like there is nothing breaking the loop other than the condition i<5 so that is why it is continuing to loop until i == 4.
A good way a at least for me to follow the behavior of loops when they get more complex is to create a unit test, put the loop in the test, create a breakpoint and use the debugger in your favorite IDE to run the test step by step and see how the variables changes values for each loop.
@Test
public void testLoop(){
int result = 0;
for (int i = 0; i<5; i ){
if (i==3){
result = 10;
}else{
result = i;
}
}
System.out.println(result);
}
CodePudding user response:
I think you want to break the loop when the result greater than 5. So please update your condition with result < 5 instead of i < 5.
Here is the basic functionality of For loop and It has basically 3 parts.
Initialisation i.e int i = 0; It is called once at the starting of the loop.
Condition i.e i < 5 (the value of i less than 5). It will proceed only if the condition is satisfied. It will call every time untill the condition is false and break the loop. Please note condition is called after the updation(point 3).
Updation i.e i (value of i increment by 1). It is called from the second loop on-words. As per code It increment the value of i by 1.
So as per your question loop will works untill the i reached at 5. and condition is breaked due to 5 < 4 is false and loop exit immediately.