Monday, October 27, 2008

Learning Computer Programming - Page 4

You must have observed that many steps in this program are similar and repetitive. Particularly, statements 7 to 14 are quite similar. It would be great if we could express it in some better way. Something like below.

1. #include <stdio.h>
2. int main()
3. {
4. int sum_till_now;
5.
6. sum_till_now = 1 + 2;
7. Repeat the step below till we have added 10:
8. sum_till_now = sum_till_now + 3;
9.
10. printf(¨The result is %d\n¨, sum_till_now);
11. }

See statement 7 above. We have expressed it in plain English, which the computer does not understand. What it understands is something perfectly formal, as below:

1. #include <stdio.h>
2. int main()
3. {
4. int sum_till_now = 0;
5. int next_number = 0;
6.
7. while (next_number < 10)
8. {
9. next_number = next_number + 1;
10. sum_till_now = sum_till_now + next_number;
11. }
12.
13. printf(¨The result is %d\n¨, sum_till_now);
14. }

Statements 7 introduces the while statement. Let's understand how a while statement works.

Whenever the while statement is executed, the condition in the statement is evaluated. If it is true, the code block (i. e. the set of statements in the curly braces) following the while statement is executed. After this, in stead of moving to the next statement, the execution again continues from the while statement.

If the condition in the while statement evaluates to false, the following code block is skipped, i. e. execution continues at the next statement after the code block.

Previous | Next

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

No comments:

Post a Comment