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.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.