Thursday, November 25, 2010

A Program Layout

A Program Layout

In the previous article, we met the following program:
main()
{
printf("Welcome to C Programming");
}

C does not require the program to be laid out as in the example. An equivalent program is
#include <stdio.h>
main()
{
printf("Welcome to C Programming"); }

or
#include <stdio.h>
main() {
printf("Welcome to C Programming"); }

All that matters is that the order of the words and punctuation is maintained. For this small program, it probably does not matter which version we use. However, as program size increases, it becomes imperative that the layout of the program highlights the logical structure of the program.

This improves its readability and makes it easier to understand. Indentation and clearly indicating which { matches which } can help in this regard. We will see the value of this principle as our programs become more substantial.
Writing output with printf

Suppose we want to write a program to print the lines (from The Gitanjali by Rabindranath Tagore):

Where the mind is without fear

And the head is held high



Our initial attempt might be:
#include <stdio.h>
main() {
printf("Where the mind is without fear");
printf("And the head is held high");
}

However, when run, this program would print:

Where the mind is without fearAnd the head is held high

Note that the two strings are joined together (we say the strings are concatenated). This happens because printf does not place output on a new line, unless this is specified explicitly. Put another way, printf does not automatically supply a newline character after printing its argument(s). A newline character would cause subsequent output to begin at the left margin of the next line.

In the example, a newline character is not supplied after fear is printed so that And the head... is printed on the same line as fear and immediately after it.
The newline character, \n

To get the desired effect, we must tell printf to supply a newline character after printing ...without fear. We do this by using the character sequence \n (backslash n) as in the following:

#include <stdio.h>
main()
{
printf("Well-Come in the field of C Programming\n");
printf("Where the mind is without fear\n");
printf("And the head is held high\n");
}


The first \n says to terminate the current output line; subsequent output will start at the left margin of the next line. Thus, And the... will be printed on a new line. The second  and third \n has the effect of terminating the second line. If it were not present, the output will still come out right, but only because this is the last line of output. A program prints all pending output just before it ends.

Monday, November 22, 2010

Data & Variables

Data and Variables

All computer programs, except the most trivial, are written to operate on data. For example:

• the data for an action game might be keys pressed or the position of the cursor when the mouse is clicked;
• the data for a word processing program are the keys pressed while you are typing a letter;
• the data for an accounting program would include, among other things, expenses and income;
• the data for a program that teaches Spanish could be an English word that you type in response to a question.

For a program to be run, it must be stored in the computer’s memory. When data is supplied to a program, that data is also stored in memory. Thus we think of memory as a place for holding programs and data. One of the nice things about programming in a high-level language (like C or Java) is that you don’t have to worry about which memory locations are used to store your data. But how do we refer to an item of data, given that there may be many data items in memory?
Think of memory as a set of boxes (or storage locations). Each box can hold one item of data, for example, one number. We can give a name to a box, and we will be able to refer to that box by the given name. In our example, we will need two boxes, one to hold the side of the square and one to hold the area. We will call these boxes s and a, respectively.

If we wish, we can change the value in a box at any time; since the values can vary, s and a are called variable names, or simply variables. Thus a variable is a name associated with a particular memory location or, if you wish, it is a label for the memory location. We can speak of giving a variable a value, or setting a variable to a specific value, such as 1, for instance. Important points to remember are:
• a box can hold only one value at a time; if we put in a new value, the old one is lost;
• we must not assume that a box contains any value unless we specifically store a value in the box. In particular, we must not assume that the box contains 0.

Variables are a common feature of computer programs. It is very difficult to imagine what programming would be like without them. In everyday life, we often use variables. For example, we speak of an ‘address’. Here, ‘address’ is a variable whose value depends on the person under consideration. Other common variables are telephone number, name of school, subject, size of population, type of car, television model, etc. (What are some possible values of these variables?)
Now that we know a little bit about variables, we are ready to develop the algorithm for calculating the area of a square.

Develop the Algorithm

Using the notion of an algorithm and the concept of a variable, we develop the following algorithm for calculating the area of a square, given one side:

Algorithm for calculating area of square, given one side

(1) Ask the user for the length of a side
(2) Store the value in the box s
(3) Calculate the area of the square (s times s)
(4) Store the area in the box a
(5) Print the value in box a, appropriately labelled
(6) Stop

When an algorithm is developed, it must be checked to make sure that it is doing its intended job correctly. We can test an algorithm by ‘playing computer,' that is, we execute the instructions by hand, using appropriate data values. This process is called dry running or desk checking the algorithm. It is used to pinpoint any errors in logic before the computer program is actually written. We should never start to write programming code unless we are confident that the algorithm is correct. Here, the algorithm is fairly simple, so it is easy to check that it is indeed correct.


Thursday, November 18, 2010

Problem Analysing and Designing Algorithm

In this  article The computer programming process we described the following stages in the development of a computer program:
  •  Define the problem.
  •  Analyze the problem.
  •  Develop an algorithm (a method) for solving the problem.
  •  Write the computer program which implements the algorithm.
  •  Test and debug (find the errors in) the program.
  •  Document the program. (Explain how the program works and how to use it).
  •  Maintain the program.

We now take a more detailed look at each of these stages. In this article, we describe the first three.

Define the problem

Suppose we want to help a child work out the areas of squares. This defines a problem to be solved. However, a brief analysis reveals that the definition is not complete or specific enough to proceed with developing a program. Talking with the child might reveal that she needs a program which requests her to enter the length of a side of the square; the program then prints the area of the square.

Analyze the problem

We further analyze the problem to:
(a) ensure that we have the clearest possible understanding of it;
(b) determine general requirements such as the main inputs to the program and the main outputs from the program. For more complex programs, we would, for instance, also need to decide on the kinds of files which may be needed. (Think of a file as a place in the computer used for storing things like documents, pictures, programs, even songs and movies.)
If there are several ways to solve the problem, we should consider the alternatives and choose the best or most appropriate one.
In this example, the input to the program is the length of one side of the square and the output is the area of the square. We only need to know how to calculate the area. If the side is s, then the area, a, is calculated by:
a = s x s

Write an algorithm to solve the problem

An algorithm is a set of instructions which, if faithfully followed, will produce a solution to a given problem or perform some specified task. When an instruction is followed, we say it is executed. We can speak of an algorithm for finding a word in a dictionary, for changing a punctured tyre or for playing a video game.
For any problem, there will normally be more than one algorithm to solve it. Each algorithm will have its own advantages and disadvantages. When we are searching for a word in the dictionary, one method would be to start at the beginning and look at each word in turn. A second method would be to start at the end and search backwards. Here, an advantage of the first method is that it would find a word faster if it were at the beginning, while the second method would be faster if the word were towards the end.
Another method for searching for the word would be one which used the fact that the words in a dictionary are in alphabetical order—this is the method we all use when looking up a word in a dictionary. In any situation, a programmer would usually have a choice of algorithms, and it is one of her more important jobs to decide which algorithm is the best, and why this is so.
In our example, we must write the instructions in our algorithm in such a way that they can be easily converted into a form which the computer can follow. Computer instructions fall into three main categories:
(1) Input instructions, used for supplying data from the ‘outside world’ to a program; this is usually done via the keyboard or a file.
(2) Processing instructions, used for manipulating data inside the computer. These instructions allow us to add, subtract, multiply and divide; they also allow us to compare two values, and act according to the result of the comparison. Also, we can move data from one location in the computer’s memory to another location.
(3) Output instructions, used for getting information out of the computer to the outside world.

Before we can write the algorithm for solving this problem, we need to explain a little bit about variables. We do this in our next article

Sunday, November 14, 2010

Reserve Words in C


A list of all the reserved words in C has been given below. The set of reserved words above is used to build up the basic instructions of C; you can not use them in programs as a variable name or identifier.
Please note that this list is somewhat misleading. Many more words are out of bounds. This is because most of the facilities which C offers are in libraries that are included in programs. Once a library has been included in a program, its functions are defined and you cannot use their names yourself.
C requires all of these reserved words to be in lower case. (This does mean that, typed in upper case, the reserved words could be used as variable names, but this is not recommended.)
(A "d" by the word implies that it is used as part of a declaration.)
 
 
 
auto d                       if
    break                        int d
    case                         long d
    char d                       register d
    continue                     return
    default                      short d
    do                           sizeof
    double d                     static d
    else                         struct
    entry                        switch
    extern d                     typedef d
    float d                      union d
    for                          unsigned d
    goto                         while

    also in modern implementations:

    enum d
    void d
    const d
    signed d
    volatile d