Thursday, October 30, 2008

Learning Computer Programming - Page 5

Coming back to our program. Let's try to execute it manually, using our old rough pad. After statement 4, our rough pad looks like this:


After statement 5, our rough pad becomes:


Now to statement 7. It is a while statement. The condition is next_number < 10, which is true because next_number is now 0 (see our rough pad). Because the condition evaluates to true, execution enters the next code block, i. e. to statement 9. After statement 9 is executed, our rough pad looks like:


Then comes statement 10. After statement 10 is executed. The rough pad looks like:


Now, after statement 10 is executed, execution again continues from the while statement, i. e. statement 7.

In statement 7, the condition evaluates to true, because next_number is now 1, which is less than 10. So, execution enters into the next block, i. e., statement 9 is executed. After execution of statement 9, the rough pad looks like this:


Then, statement 10 is executed. Then execution goes to the while statement, i. e. statement 7.

If you carry on this process, after sometime, you will find that the condition will become false. The rough pad would be looking like this then:


At this point, the next code block, i. e. statements 8 through 11 will be skipped and execution will continue from statement 12. Statement 12, being blank, statement 13 will be executed, which will display sum_till_now, which contains the desired result.

Done! This explains the use of loop. If now you are asked to write a program to add up to 10000, or 1000000, you need only to change at one place, i. e. in the condition in the while statement.

Previous | Next

Page 1 | Page 2 | Page 3 | Page 4 | Page 5 | Page 6

No comments:

Post a Comment