Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Java, consider the following program: public class PracticeExercises { public

ID: 3742012 • Letter: I

Question

In Java, consider the following program:

public class PracticeExercises {
public static void main(String[] args){   
int num = 10, sum = 0;   
for(int i=1; i<=num;i++){
sum += i;}
System.out.println("Sum = "+ sum);}
}

If you change the line "sum += i" the output changes from 55 to 10. Explain the differnce between "sum += i" versus "sum =+ i" and why one sets sum to 55 and the other sets sum to 10.

Explanation / Answer

sum += i; The above line adds i to the value of sum, every time through the loop. for all values of i(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), sum becomes 1+2+3+4+5+6+7+8+9+10 = 55 sum =+ i; => this is same as => sum = +i; The above line just assigns the value of i to variable sum through each iteration of the loop. for each iteration of i from (1-10) the value of sum is updated. Since 10 is the final value of i through the loop, sum is assigned a value of 10.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote