Home > Back-end >  Output of loop seems inaccurate
Output of loop seems inaccurate

Time:12-14

Just a basic question as I'm only a student who got curious. Shouldn't the output of:

for (int num = 0; num < 5; num  ) {
System.out.print(num   1);
}

be "13"?

The output shows "12345" instead.

CodePudding user response:

Your function is not actually summing, its asking for a print out of each sequential "num" with 1 added to it. If you wanted to actually sum, you'd change your code to the following:

int sum = 0;
for (int num = 0; num < 5; num  ) {
sum = sum   (num   1);
}
System.out.print(sum)

CodePudding user response:

By the rule it is doing the sum and then printing...

CodePudding user response:

Your for-loop is going until the num variable reaches 5. What you have done is have the code add 1 to num's value and then print that value and repeat. It adds one, prints 1, then adds one and prints 2, on and on until the for-loop's criteria is no longer met. This results in the "12345" that you were given.

  • Related