Search code examples
javavariablestrace

Java Variable Trace Form


For an assignment I am supposed to complete a table tracing the values of myNum and mySum as well as any output based off of the following code segment:

int myNum = 11;
int mySum = 0;

while (myNum >= 0) 
{
myNum--;
mySum += myNum * 5;
}

System.out.println ("myNum: " + myNum);
System.out.println ("mySum: " + mySum);

I'm fairly new to Java and I'm having some trouble understanding what this segment will produce. Can anyone help clarify?


Solution

  • Here's a commented version:

    int myNum = 11; // myNum is 11
    int mySum = 0; // mySum is 0
    
    while (myNum >= 0) // repeat the next block (between {}) while myNum is positive or 0
    {
        myNum--; // decrease myNum by 1
        mySum += myNum * 5; // add 5 times myNum to mySum
    }
    
    System.out.println ("myNum: " + myNum); // output "myNum: " followed by myNum value
    System.out.println ("mySum: " + mySum); // same as above by with mySum