Sunday, May 29, 2011

Chapter[2]: Data Types, Input and Output

In this chapter we will be writing a few short programs. You must write all the programs here and run it successfully. Do little experiments with these, change a little of this and that in the code and observe how the output changes.

Our first program here is a performs simple addition of two numbers. Think about how we add two numbers on paper. We use some space on the paper to write (or store) the numbers that we will add. But how do we get a paper-like thing in our program? The computer memory does it for our programs. Every programming language supports variables that can be assigned values. These variables are stored in computer memory. Therefore, variables are just names for a space in the memory. To set the value stored in a variable, we have to write a the code like variablename = some value. Lets use the code below to help explain it further.


#include<stdio.h>

int main() 
{
    int a;
    int b;
    int sum;


    a = 50;
    b = 60;


    sum = a + b;


    printf("Sum is %d", sum);


    return 0;
}
Program 2.1 

Run the program now. You should see Sum is 110 on the screen.

In this program, a, b and sum are three variables each storing different values. The first step is to declare these names as variables of a data type. All these variables are of type integer, and hence they are declared as int. Thus, the line int a; tells the compiler that we are interested in using a as a variable that will be used to store integer values. Like int, there are many other data types supported by C. We will get to know them with use. There is a shorter version of declaring variables of the same type. Instead of typing three int declarations for a, b and sum, we could have written int a, b, sum;, which has the same effect as the former. Note how semicolon terminates variable declaration.


In the next two lines, we have two statements. 


a = 50;
b = 60;


Here we have assigned a value of 50 to a, and 60 to b. Unless we change the value ourselves, the compiler will always find these values for these variables in our program.

Saturday, May 28, 2011

Chapter[1]: The First Program

Welcome to the world of programming!

Lets start with the simplest of programs in C, the hello world program. Its actually a kind of a tradition to start off with when learning a new programming language. You won't be an exception either.

I will use codeblocks to run all the codes in this book. You are free to use any other program you are comfortable with. Usually the basic steps are quite similar.

So how do you install Codeblocks? You can also download the software as instructed in Chapter[0]. I am assuming you are on Windows PC and have the codeblocks installer file. Double click the installer and follow screenshots below.

Fig 1.1

Fig 1.2

Fig 1.3

Fig. 1.4
Fig. 1.5
Click 'No' here (Fig 1.5).
Fig 1.6

'Finish' finishes the installation. To start codeblocks, click on the Start menu, choose Programs and find an entry named 'Codeblocks'. If you are in Ubuntu, you will find it in Applications > Programming menu.

Fig 1.7
If you don't want to see the 'Tip of the day' windows every time you start codeblocks, remove the check from the check-box labelled 'Show tips at startup'.

As the first step of beginning to code, you should create a file where you will save your code. To create a new file, click on the File menu > New File > Empty file. You should reach the following screen (Fig 1.8).

Fig 1.8
We are almost done. To keep your programs organized, create a folder on your hard-drive. Save all your codes in this folder during the practice. To save the empty file you just created, click on File > Save. From Save as type choose C/C++ as shown below.

Fig 1.9
So you just saved your file as hello.c. Check if hello.c is the name of the selected tab in the editor window. Save all your C programs with a .c extension.

Fig 1.10
Now we are ready to write some code. Type in the code below on the editor. Save the file when finished.

Fig 1.11
Don't let this scare you! I will explain everything shortly. For now, just carry out all the steps mentioned here. From the Build menu, click on Compile Current File.

Fig 1.12
If you have written the code from the book as-is, you should see the message 0 errors, 0 warnings. This  means that you have used the syntax of the language right. The message should appear as shown below.

Fig 1.13
You may now run the program you have written. From the Build menu, click on Run (Fig 1.14). This will execute your code and produce an output similar to Fig 1.15.

Fig 1.14

Fig 1.15
Notice the Hello World you have printed on the screen. That is exactly what your code does. The next line says Process returned 0 (0x0). We shall ignore this message for now. Execution time 0.031s means that your program took 0.031 seconds to run. Finally, the message Press any key to continue actually explains itself. Pressing any key will close the window and take you back to the editor.

If you have successfully run the program to print Hellow World on the screen, I must say you have done a very nice job indeed. Take your pride!

In case you haven't been able to run it successfully, try again, restarting the whole sequence of steps if necessary. If you are still stuck, take help from someone experienced. You have to get it right by now, otherwise you will gain nothing by moving forward with this book.

Let us now understand what we have actually written. The #include<stdio.h> in the first line will be explained shortly. This is followed by an empty line just for the sake of clarity. Empty lines serve no purpose in the code other than providing some comfort to our eyes. The third line is int main().  This is called the main function of the program, named such for the fact that all C programs begin execution by starting from the main function. A program may have only one main function. The code for the main function is enclosed within curly braces ( {} ), and a return 0; is placed right before the closing brace ( } ). This will be explained in a later chapter where I will discuss functions in C. For now, just use the following code skeleton to build your program on. 

int main() 
{
    your code goes here
    return 0;
}

The next line of our code says printf("Hello World"); In C, this is called a statement. printf() is a function that we will use whenever we need to print some text on the screen. We need to put the text within double quotes ( "" ) inside the printf() function. The text in our code is Hello World. The printf() function uses the file stdio.h to carry out the steps in writing the text on the screen. Files like stdio.h are called header files in C, and have the extension .h. The functions for performing standard input/output operations are defined in the stdio.h header file. We really do not have to know how these functions work internally. But to use these functions we have to write #include<stdio.h> in the beginning of our code as we did in our hello world program. There are many other useful header files available in C, each providing a different set of functions. We will use a few of them in our programs when necessary.

Statements in C, such as printf("Hello World");, are terminated with a  semicolon ( ; ) . C executes each statement sequentially, from top to bottom. return 0; is also a statement, hence it has a semicolon at the end. A common mistake by beginners is to forget to put a semicolon after each statement, and thereby earn a compile error. Try to compile your code by removing a semicolon from one of the statements. Prepare for a compile error.

A very important part of writing code is indentation. Notice carefully the code I have written here. The lines #include<stdio.h>, int main(), { and } all start at the leftmost column of the editor, along the same vertical line. However, printf() and return 0; are actually aligned four spaces to the right of the lines above. This method of keeping a fixed amount of space for codes within the curly braces ( {}, or blocks ) is called indentation. Like an empty line, keeping these spaces are not necessary for the execution of the code. In fact, they are ignored by the C compiler. Nevertheless, maintaining proper indentation of your code is a must. Good habits are hard to grow, but you should grow the habit of always indenting your code. A code without indentation can upset your colleague, irate your boss or even slim your chances in an interview! I hope you will realize the significance of indenting your code. The standard practice of indentation is to keep four spaces to the left. You can set the Tab key of your keyboard to put four spaces for indentation in the editor. To do this, from the Settings menu, click on Editor. In Tab Options, put a check on Tab indents and set TAB size in spaces to 4 (Fig 1.16).

Fig 1.16
Now, here comes the first exercise for you! Write a program that prints I love my country, Bangladesh! on the screen.

You must write the complete code for the program anew, compile it, and finally run it. Remember to save your file before compiling.

Friday, May 6, 2011

Chapter[0] : Before You Start

Computers are, both by name and purpose, a form of calculators. We have used our computers to listen to music, watch videos, play games, prepare documents etc. However, computers basically do not understand anything but zeros (0) and ones (1). So when you, an user, are running an application such as a music player on your PC, your machine actually does the work for playing the music by performing some simple calculations in the background. Like a music player, there are many other software available, and they serve a variety of purposes. Due to the abundance and flexibility of these software, computers are now widely used for almost everything. To create a software like these, we have to write programs which instruct the computer to behave just the way we want!

There was a time when programs had to be written as sequence of 0s and 1s, as the computers can not understand any other form of language other than its own. It was called the Machine language, and had only 0 and 1 as it alphabets. As you might expect, memorizing sequences of 0s and 1s was probably the hardest way of programming. As such, Assembly language was introduced, which provided programmers a set of English instructions that they could write in their programs to instruct the computer. For example, the ADD instruction performs addition, MUL did multiplication, and so on. But computers, as we have already said, will only understand 0s and 1s, not ADD or MUL or any other form of instruction for that matter. Therefore, the job of the Assembler was to convert these English instructions to machine language (0s and 1s). With time, our demands have increased, and the need for more functionality kept growing. More functionality requires more lines of code. Assembly language wasn't appropriate for writing big programs that consisted a large code-base. The need for an easier and more improved system have led to the development of newer languages such as Fortran, Basic, Pascal and C. These classical languages were followed by the more recent Visual Basic, Java, C-sharp (C#), Perl, PHP, Python and Ruby. And there are more to come. What makes these programming languages different is the difference between the compilers for each. It is the compiler that converts the more advanced set of instructions that we write to the machine language that the computer understands. That way, we do not have to worry about whether the computer will understand what we have written.

Writing a program involves three primary steps. First of all, the programmer must have a clear knowledge of what he wants to accomplish. Next, an algorithm is developed. This involves digging out appropriate logic and laying them out in proper order. Once the designing phase is complete, the algorithm we have devised is put into code using a known programming language.

In this book, we will try to learn some fundamental concepts of programming, and write our codes in C. This book assumes that you are comfortable using a computer and completely unfamiliar with programming. I have chosen C for the examples given throughout this book as C is very popular and powerful as a programming language, in spite of being quite old. C programs are very helpful for understanding the fundamentals of programming. Moreover, in all the popular programming contests, C stands out being the most widely used amongst the few programming languages supported. However, we are not going to learn everything about C in this book, but take in only what is required to understand the fundamental concepts of programming. Once you finish reading this book, you may start reading books dedicated to teach the C language, or any other programming language for that matter (for example C++, Java or Python). Check the Appendix where I have mentioned names of some useful books in this regard.

You will need three things to actually understand the contents of this book; a computer (preferably with an internet connection ), a C compiler and sufficient time. To get the most of out this book, read it slow, probably taking two to three months. Do not haste to the end just to realize you have learned nothing. Reading alone is not sufficient to learn programming. You have to stretch those fingers out and spend more time coding every single example in the book. When asked a question, you should think about it and try to find an answer. If you are taking too long to think, do not worry. It is indeed a very good practice. A programmer must grow the habit of thinking about a problem at a long stretch, even if its a span of a few days. You can not start reading the next chapter unless you have completely understood the previous one. Also, if any of the chapters seem very easy to you, do not skip it. Read it through, code all the programs in the chapter, and only then move on. There is a big difference between general studies and the way we should learn programming. Learning to program involves studying the material and practice it alongside. Keep in mind that this book will not make you a programmer. It will only start your journey towards a complete programmer.

Okay, now that you have a computer, we have to find a C compiler for you. There are many compilers for C, available for all the platforms in use today. If you are using Mac or Linux, gcc the best option for you. Usually, most of the Linux distributions have gcc per-installed. If you don't find it in your machine, you must install the package. In Windows, you can use Codeblocks (http://www.codeblocks.org/). Its a free and open source IDE that also runs on Mac and Linux machines. You can always use a general purpose text editor to write your code and compile it to get the executable. But most of the IDEs will do it for you. They have a text editor and a compiler built-in, along with many other tools. Using an IDE is the easiest way to learn to code.

You may download Codeblocks from their website http://www.codeblocks.org. Go the the Downloads page, and click on Binaries. You will bee provided two download options:  codeblocks-10.05-setup.exe and codeblocks-10.05mingw-setup.exe .  Download the latter (74.0 MB). Once downloaded, you can install in much the same way you would install any other application or game. Ubuntu users can download the software using Ubuntu Software Center (Applications > Ubuntu Software Center).

To develop you programming skills, you will need a lot of practice. There are quite a few web sites where you will find a list of problems that you can solve by writing programs. All these sites will allow you to submit solutions coded in C. What's more interesting is that some of these sites also arrange programming contests on a regular basis. Participating in these contests will not only hone your programming skills, but will also put you in a community of some really great programmers all over the world. However, to perform well in these contests, you should also have good analytical skills to solve mathematical problems. You can learn more about programming contests at the end of this book.

The number under each program in this book denotes the chapter and index of the program in that chapter. For example, program 2.5 refers to the fifth program of chapter two.

This isn't really a story book that you can just read trough and think you are done. To actually learn the materials of the book, you need to type in every single program whenever you come across it in the book, and check the output. When in problems, don't skip it. Try to find out where things could have possibly gone wrong. And don't take too long to realize that its actually fun!

I hope you will enjoy reading all the chapters with patience and typing in all the programs on your machine. Best wishes.