Monday, October 27, 2008

Learning Computer Programming - Page 3

Now, let´s teach this to a computer, i. e. write a computer program for this, using the C language. The program is given below. Note that the line numbers are given just for our reference. They are not part of the program.

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

Let's understand the logic.

We shall not dig into the syntax, or grammar of C, and just try to understand the logic.

A program is executed step by step, from top to bottom.

Statement number 4 is similar to your drawing a box named sum_till_now in rough pad. Computer uses its internal memory as its rough pad. sum_till_now is called a variable. Similar to a box in your rough pad, a variable can hold a value.

See statement 6. It is called an assignment statement. ¨=¨ is called the assignment operator. When an assignment statement is executed, whatever is in the right side of ¨=¨ is evaluated and put into the variable in the left side. That means, after executing statement 6, the value of sum_till_now becomes 3.

Statement 6 can be read as ¨1 + 2 is assigned to sum_till_now.¨ Never confuse ¨=¨ with the equality operator as in common mathematics. Both are different.

Statement 7 is also an assignment statement. Evaluating the right side (i. e. sum_till_now + 3) results in 6 (remember that sum_till_now is now holding 3). So, 6 is assigned to the left side, i. e. sum_till_now.

Hence, after execution of statement 7, sum_till_now holds 6.

Carrying on, after execution of statement 14, sum_till_now holds 55, which is the desired output.

Done. But the program seems long. What if the problem were to add from 1 till 10000!

Previous | Next

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

No comments:

Post a Comment