Wednesday, May 19, 2010

Accepting Input

Excited at your success of solving the problem your uncle talks to the contractor about your program. The contractor sees the value of having such a program at his disposal and contacts you for the same. However, since all the clients have different size of land, and also want different sized pavements, you wish to provide user configurable length and width parameters.
This brings us to the input part of the stdio.h header file. Getting user input is similar to showing the output.
#include "stdio.h"
int main()
{
 int length;
 scanf(“%d”, &length);
 return length;
}
Running the above program will result in the computer waiting for your input. It expects an integer and be sure to type in an integer only. It will store the value you enter in the variable “length”. Since the variable is being written to (its value is being changed) we cannot just pass the variable name, but have to append an & in front of the variable. Always remember to put the & in front of the variable when using the scanf function. Here is the stub of the program you will need to complete your assignment at the contractor’s place:
#include "stdio.h"
int main()
{
 int len1, len2, width1, width2;
 int area, rate;
 printf(“Enter outside length “);
 scanf(“%d”, &len1);
 printf(“Enter outside width “);
 scanf(“%d”, &width);
 …
 area = (len1*width1)-(len2*width2);
 scanf(“%d”, &rate);
 printf(“Cost of paving = Rs.%d\n”, area*rate);
}
[Exercise] The paving company has a dedicated computer to do this calculation. They do not wish to run the program again and again after each calculation. Encompass your program with something that will cause the first question to appear soon after the cost of the first pavement is done displaying.
[Exercise] Some customers may want to check with various rates. Modify your program such that the program will remember the previous inputs. Finally the program will ask for user input in the following fashion:
Enter outside length [enter 0 for 1200] _
Previously the user had entered 1200. This time she could just enter 0 to assume the same value as previous.
This problem also teaches a lesson in usability of systems. Lack of ease of inputs is a major reason that many banks, ATMs and vending machines have long queues.
Side note: We never entered the units. This is because arithmetically units don’t matter. However when interacting with the user, it is always best to make the units clear. You may also want to write a conversion program or modify the existing one to support both US units as well as metric units.

Producing output

Now that your uncle has got his answer, he is really excited. He contacts his contractor and asks if there are any other type of pavements. Of course, there are and they cost Rs.150, Rs.170 and Rs.200 per sq. mt. respectively. Your uncle again asks you to calculate the cost. This time you have to make changes to the rate one at a time and see the return value. You start wondering if there is any way to see all the output in one shot. You will write four different formula using various rates and you want their results displayed one after another.
You have come up with a requirement with which most C and C++ books start – a hello world program that starts with printing some output on the screen. I hope you appreciate how much you could already accomplish without ever having to print anything on the screen. But now, the time has come to show the stereotypical hello world program.
#include "stdio.h"
int main()
{
 printf(“Hello World!”);
return 0;
}
Printf is a function that outputs a formatted string to the screen. For the printf function to work, we need to include a file that comes with most C implementations. Hence we write #include . The # in this statement is a pre-processor directive. It calls upon the compiler to take some actions before the real compilation begins. In this case, it copies a file stdio.h to the text of the program. Stdio stands for standard input and output. .h indicates a header file, though the extension could really be anything.
The printf function outputs a formatted string, but also has some “magic” characters which are output differently. One of them is “\” known as the escape character or escape sequence. The character after the \ gives it a special meaning. \t stands for tab, \n stands for a new line \r for carriage return, \b for backspace, \% for percentage sign and \\ for backslash (more info). Another such character is the % sign. It has substitution power. The characters following the % will determine the type of substitution. For example, the quoted string inside printf for outputting the area will be “Area=%d”
The %d will be replaced by value of some integer variable which should follow the quoted string as in:
printf(“Area=%d”, area);
Similarly, %f stands for floating point numbers, %c for a single character, %s for a string, %l for long integers and %e for double floating point number. A complete list is here.
Now that we know how to print an output we can solve the problem of calculating cost for the paving of the area of your uncle’s garden:
#include "stdio.h"
int main()
{
 const int len1 = 10;
 const int len2 = 7;
 const int width1 = 8;
 const int width2 = 5;
 int rate = 100;
 int area = (len1 * width1) – ( len2 * width2);
 printf(“Cost @Rs.100 = %d\n”, rate * area);
 rate = 150;
 printf(“Cost @Rs.150 = %d\n”, rate * area);
 rate = 170;
 printf(“Cost @Rs.150 = %d\n”, rate * area);
 rate = 200;
 printf(“Cost @Rs.200 = %d\n”, rate * area);
 return 0;
}
Note that rate is not declared const since its value changes during the execution of the program. Area is also not defined but could have been since it is calculated only from other constants.
[Exercise] Modify the above program to support floating point lengths and widths. A float is defined as “float” instead of “int”.

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));
}

My Hello World

As I have mentioned in my previous post, I have not liked the way most C or C++ books begin. They start with a program that prints hello world and attempts to create enough enthusiasm among the readers to lure them to continue reading the fat book. This approach puts undue stress on experiencing the output without really speaking anything about computers or the C/C++ programming language. Moreover, the first program that the beginners write is so difficult and tricky that few will understand its true genius even after completing the entire book.

If I teach C, I want to start off differently. I want to include the least number of constructs in the first program. My first program will be an infinite while loop. It will look like this.

void main()
{
    while(1);
}

Now that is a beauty. I would tell that all C/C++ programs had one (and only one) main function. The main is the entry point into the program. The CPU will start executing the program from this point. The first word of the program represents what kind of output this program will produce. It is known as a return value. “void” means nothing. So we are declaring that this program will not produce any output. Some implementations of the C language may require that the main function produce some output. For such implementations we would replace the “void” with “int” (for integer value) and add one more statement just after the while(1); - return 0;

The round brackets after main have a special purpose. We will talk about those later. There are curly brackets after this. They define the scope. Think of a closed box with its name stamped on its cover and the kind of value (integer / void) that comes out of it, stamped before the name. Then, the name will be “main” the kind of value is the int or void written before main. The periphery of the box then, are the curly brackets.

Whatever is inside the curly brackets will be executed by the CPU, one statement at a time. In the simplistic demo program, we have a single statement that says while(1); The word while is different from the word main. "while” is a keyword. There are only a few number of keywords in C/C++ and they have a specific meaning. The “while” keyword is a looping construct. It asks the CPU to execute whatever comes after “while” for as many times as required until the condition inside the () becomes false. Of course, it may never become false at all in which case the CPU will keep executing the instructions ad infinitum.

True and False are tricky in conditional checks in C. Anything that evaluates to 0 is considered false and all non-zero values are considered true. Hence, the condition inside the round bracket will always evaluate to true (since it is non-zero) and the loop will continue forever. But there is nothing inside the loop. The loop boundary could have been defined by the same scope defining {} as for “main”. Instead, in their place, we have a semicolon (;). Hence no statements are to be executed inside the loop. All the CPU does is keep checking the condition, over and over again. Really, the computer is a dumb box.

Your first program does not produce any output. It causes the computer to hang! The condition inside the while loop () can be a more complex one. It could be a comparison such as 5>2, which would always evaluate to true or another such as 1!=1, which stands for one not equal to one which always evaluate to false. The C language supports many operators and we will explain then as and when we use them.