Because it does not sum my cycle for

0

Hello, I am all studying a Java course but I can not understand why the result of Sum is 0

public class TestClass{
 public static void main (String args []){
  int sum = 0;
   for (int i = 0, j = 10; sum > 20; ++i, --j)
   {
     sum = sum+ i + j; //1
   }
   System.out.println("Sum = " + sum);
 }
}
    
asked by Rastalovely 10.04.2018 в 17:59
source

3 answers

2

To understand the behavior of your code, you must first review a little more thoroughly the operation of the for :

Within the flow controls provided by Java, we find the for , which is characterized by loops created in our code, that is, giving us the ability to execute the same lines of code every few times we want (or rather that the stop condition allows us).

Here is a way to use it, perhaps the most "simple" or at least the one that will serve as a reference:

We can delve into 3 important elements:

  • Declaration / initialization block: runs at the beginning of the for and unique times. It is usual to declare and initialize control variables.
  • Control block: Run every time you want to enter a loop and if the condition is true execute what is inside the for; otherwise skip the entire block. It is usual to buy the control variable.
  • Execution block at the end of the iteration: once the iteration is finished, each time the code that is placed there is executed, it is usual to increase or decrease a control variable.
  • In your particular case, no entry is made to the for, because the condition is initially false.

    Greetings

        
    answered by 10.04.2018 / 21:50
    source
    1

    The ending condition of the for loop is incorrect.

    It should be sum < 20

    Greetings

        
    answered by 10.04.2018 в 18:06
    1

    Check the condition of your for cycle. As you have it now, it will not be repeated because sum is 0 and the iteration will be as long as sum is greater than 20.

        
    answered by 10.04.2018 в 18:06