226k views
1 vote
What is the output of the following program?

int sum = 0; int k = 1; int val = 1; for (k = 0; k <= 8; k++) { sum += val; val++; }
System.out.println(sum);

User Nick Foden
by
6.1k points

1 Answer

7 votes

Answer:

Output of the program is following

sum=45

Step-by-step explanation:

The execution of the program in the "for" loop will be following

For k=0

=> val=1 and sum=0+1=1

For k=1

=> val=2 and sum=1+2=3

For k=2

=> val=3 and sum=3+3=6

For k=3

=> val=4 and sum=6+4=10

For k=4

=> val 5 and sum=10+5=15

For k=5

=> val=6 and sum=15+6=21

For k=6

=> val =7 and sum=21+7=28

For k=7

=> val=8 and sum=28+8=36

For k=8

val=9 and sum=36+9=45

So all the iterations of for loop are completed and the output is 45.

I hope it will help you!

User Swix
by
6.8k points