Wednesday, May 12, 2010

A little more useful code

Now let us make our program a little bit more useful. Let us calculate the area of a square. Suppose the length of the side of this square is 5. Then we would write a program as below.
int main()
{
    return 5*5;
}
The * sign indicates multiplication. The program will return 25. However we will have to do something special to see the return value. Depending upon the OS and the implementation you are using, you may see the returned value directly (as in VC++) or may have to type echo $? (in Linux).
In any case, you have written your first program that does something useful! But there is a limitation (there are many limitations, but we will currently dwell over only one of them). If you now wish to calculate the area of a square with a side of length 6 instead of five, you will have to change the number five at two places. What’s the big deal? You might ask. But think if I had asked you to write a program that outputs the sum of the area and the volume of a square and a cube of a particular side length, (x*x + (x*x*x)), count how many x’s you would have to modify. To avoid such problems, we use constants or variables as the case might be. Just as in algebra we use named constructs such as x and y and then replace their values only when needed, we use constants and variables to do that in C and C++.
int main()
{
    const int side = 5;
    return side*side;
}
We are now using a named construct known as “side”. We assign a particular value to this named construct. During one execution of the program, the value of “side” does not change. Hence we define it as:
Const int side = 5;
Now if I asked you to calculate the area of another square with side equal to 6, all you have to do is replace one “5” with a “6” and you will get the required answer.
With this limited knowledge of the C world, you can now solve a lot of your primary school mathematics problems. Take this for example:
“Your uncle owns a rectangular piece of land with length=10m and width=7m. He wishes to construct a paved path at the boundary of this land (inside) with a width of 1m. His contractor informed him that it will cost him Rs 100 per square meter. How much money would your uncle require to get the pavement done?” Easy isn’t it?
int main()
{
    const int len1 = 10;
    const int width1 = 7;
    const int len2 = 8;
    const int width2 = 5;
    const int rate = 100;
    return rate*((len1*width1)-(len2*width2));
}

No comments: