179k views
2 votes
What does the following loop do? val = 0 total = 0 while (val < 10): val = val + 1 total = total + val print(total)

Prints the numbers backwards from 10 to 1.

Prints the sum of the numbers from 1 to 10.

Finds the average of the numbers between 1 and 10.

Prints the numbers from 1 to 10.

1 Answer

4 votes

Program in Python

val = 0

total = 0

while (val < 10):

val = val + 1

total = total + val

print(total)

Answer:

Prints the sum of the numbers from 1 to 10.

Step-by-step explanation:

Given

The above lines of code

Required

What does the loop do?

To know what the loop does, we need to analyze the program line by line

The next two lines initialize val and total to 0 respectively

val = 0

total = 0

The following iteration is repeated while val is less than 10

while (val < 10):

This increases val by 1

val = val + 1

This adds val to total

total = total + val

This prints the value of total

print(total)

Note that the loop will be repeated 10 times and in each loop, val is incremented by 1.

The values of val is 1 to 10.

The summation of these value is then saved in total and printed afterwards.

Hence, the loop adds numbers from 1 to 10

User Jakob Hohlfeld
by
5.6k points