Sunday, 3 January 2016

A basic Introduction

Welcome to the world of C. The first high Level Programming Language that is still popular in development even after 40 years of its first release.

Before we start anything on this topic, I would like to assume the following,

  1. You know about computer programs.
  2. You know about different form of languages.
  3. You know the basics of using a computer like using notepad to write something on it.
  4. Copy, Paste and save notepad contents.
  5. You know how to deal with the command prompt/shell.
However, if you don't know about computer programs, you can read the information in this post, Computer Programs. This post gives you an insight why a computer program exists and what is its basic functionality.

If you are a beginner and yet to know about forms of programming language and where C resides in the world of Programming, the following two articles are just right for you,

If you do not have any idea of Unix Shell/ Windows Powershell or Mac OS Command Line, I recommend you complete this crash course on Command Line, Command Line Crash Course.

At this point, I assume that you are aware of Computer Programming, High Level languages and Command Line.

Please don't prove my assumptions wrong. Because, they are the strong base you will be requiring throughout all the subsequent articles.

Now, I want to be very frank on my writing rules,
  • While writing any article, I assume that you are in front of me and you may have asked me ta question and I will answer that question for you. Questions are generally marked bold while my answers to them are in plain text. That may be weird way of writing. But that's the best way I can explain things in minute details.
    For example, look at this article on data, Data. Once you go through it, you will definitely understand what I mean.
  • Sometimes articles are too long. No way, you have to bear with them.
  • Most of the articles will be having real code examples and the output.
  • Although you will see the output in the article, I recommend you to write them on a notepad, save it, compile and run it to see the results yourself rather than relying on me.
  • Practice makes a man perfect. So, practice every day. If you are stuck with anything, comments are welcome. I will try to reply on your comment as soon as possible.
  • Wherever necessary, there will  be a section named Source Code Distribution. This section will details about the source code discussed in the article. You can download the source code and can verify the same with your program. But it is not recommended to directly download and use it for your purposes. That will actually defeat the purpose of learning.

I think after reading all these, some people will surely go back and check some other website. If you are still reading this, 'Welcome reader, I thank you to be here' and we'll start our discussion on C in the next article.

Motivation for learning C

People sometimes ask,

  • Is it worth learning C as it is an old language ?
  • What can you do using C ?
  • Can I do anything in C ? 
In short, yes you can do anything with C, even to see the most beautiful image on your desktop, you are using C. If you are also editing the image in a high end image processor like Photoshop, you are surely using C.

So, instead of writing an introductory article, I am going to show you the way how C helps in computing.

I will be going through a scenario of a building, a building with 10 floors.

I have a 10 storey building.

  • The ground floor is a single portion.
  • The first floor is another portion.
  • The second/third/fourth floor combined together contributes to a single portion.
  • The fifth/sixth floor combined together contributes to a single portion.
  • The seventh/eighth combined together contributes to a single portion.
  • The topmost floor is another single portion.

Now, I want to destroy a portion of the building.

  • If I destroy the topmost floor, probably the remaining 9 stays unaffected except for some garbage cleaning stuffs to perform.
  • If I destroy the Seventh/Eighth floor, the lower 7 sustains beautifully. But the top three floors are destroyed in a single go.
  • If I destroy the fifth/sixth floor, the remaining sustains beautifully. But it destroys all the floors from 5 - 9.
  • If I destroy the portion containing second/third/fourth floor, it will destroy everything from 2-9. Well the building is small enough and it lost most of the floors but still it is having the ground and first floor.
  • If I destroy first floor, everything is lost from 1-9 and it is almost gone but still there is a portion left in the building and its not completely gone.
  • If I destroy ground floor, the whole building is destroyed in a single go.
Do you agree ?
Better you do. Because, you don't have any option to fight gravity.

Now, you understand the consequence on destroying the portions of the building.

Now let's get the real value on each portions and you will understand where C, C++, Java, C#, Android, iOS etc are working.

  • The ground floor is C.
  • The first floor is C++.
  • The second/third/fourth floor is a Java, C#, Objective C, .NET Platform which are written mostly in C/C++.
  • The fifth/sixth floor is combination of OS Kernel and other stuffs which are mostly implemented in C/C++ and the mentioned platforms like Java, .NET, Objective C etc.
  • The fifth/sixth floor is Spring, Hibernate, nSpring, Sharepoint etc.
  • The seventh/eighth floor is Web Development/Standard Desktop Application Development.
  • The topmost floor is where you see different applications like Internet Explorer, Google Chrome, Mozilla Firefox, Microsoft Office Suite, Photoshop, Windows media Player, MATLAB, KMP, Eclipse IDE or whatever application you use in your desktop.

So, you can see where C Resides in the world of Computing.

Now you may argue with me that I am just overrating C. So, here I go with some reference to my answer,
C may be an oldie but its a real goody. So, never underestimate the power of C. Again remember the picture and think if C was not there, what possibly would happen. Possibly we would not see computing in the way we see it today.

And here is the answer for Frequently Asked Questions,

Yes we can write anything using C only. but it will just be reinventing the wheel which is already invented by Sun Microsystem (for Java), Microsoft (for .NET), Apple (for Objective C) and related technology advancements.

Prev     Next

C/C++ Installation

After reading the previous article, many people are curious to learn C and wants to know how to use it.

Without any other introduction, I am jumping off to set-up your system. There are multiple steps, you have to perform,

  1. Download and install C and verify the installation
  2. Write a short program
  3. Compile and run the program
  4. Check the output
So, these are the steps you need to follow.

Detailing each steps,

Step 1 - Download and install C and verify the installation

This step is system dependent. That is, it depends on the OS you are using. I will be using Windows 7 and readers who are using Windows 7, can follow the steps below for step 1. For others, I have tried to provide some link, you can check the following links,

For Mac OS

The same installation should work for Windows Vista/Windows 8 as well. If you are still using Windows XP, please upgrade your system to some latest OS like Windows 7 or Windows 8.


We'll use MinGW for our case. So, let's start with the installation.
  • Download the installer from Sourceforge.
  • Double click on the installer.
  • Installer opens up a window. Click Install.
  • It will ask for installation directory. By default this is set to C:\MinGW
  • You can change the directory. I recommend not to change the directory.
  • After the directory selection, click on Continue.
  • It will download required files.
  • Once this is completed, click Continue.
  • It will ask you for installing required packages.
  • Choose mingw32-base

  • If you want to install the compiler for C++ as well, you have to select the mingw32-gcc-g++ too
  • Then click on Installation panel and click Apply Changes
  • Click on Apply.
  • It will download the required files and installation gets completed.
  • Once the installation is complete, click Close.
  • Close any installation window open.
  • Now change the PATH Variable in Windows Advanced Settings to C:\MinGW\bin (Or the directory you have chosen at the time of installation). If you don't know how to change the PATH variable, check this article, Java Installation.
Phew !!!
A lot of stuffs to do. The good news is, you have completed the installation, let's verify it. 


Now open the command prompt from Start > All Programs > Accessories > Command Prompt

Issue the command

For C++ compiler, issue the command

Which should be similar to the following,
gcc: fatal error: no input files
compilation terminated.

g++: fatal error: no input files
compilation terminated.


Its OK, if you see an error. Do not panic. We'll get into that very soon.

With this our Installation is complete. Now we'll move to the next section.

Step 2 - Write a short program

At this point, you may have completed the installation. We will use a simple text editor like Notepad, Notepad++, Vi etc. We will not use any high level IDE for learning purpose, a simple text editor is good.

Now, open the editor and write the following program.
#include <stdio.h>
int main(){
 printf("Hello World");
 return 0;

Save the program in any location with the name first.c.

Step 3 - Compile and run the program

Compile the program

Open command prompt and move to the directory you have saved the file in Step 2.
In my case, I have saved the program in D:\Palash\c\trunk\src\blog

So, I have issued the following commands,
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.


D:\>cd D:\Palash\c\trunk\src\blog


Now, we'll compile the program using C compiler,
To do that, use the command,
gcc first.c -o first

If you have installed C++ compiler as well, you might want to verify the installation as well. To do that, use the command,
g++ first.c -o first

This command will compile the source code and will provide us with an executable output file with the name first. You may wonder how a C program is compiled using C++ compiler. You might read this article for details.

Now let's take a closer look on gcc command. We have issued, gcc command followed by the file name and -o and another String.
gcc is the command to compile a C program. The -o indicates the output file. If you don't provide this option, compiler will provide a default name.

  • In case of Unix and Mac OS, the default name is a.out
  • In case of Windows, this default is the a.exe
So, if you do not provide -o to the compiler, you will loose your previous output file each time compiler compiles a C Program. So, the best practice is to provide output file name to the compiler. Try following this from day 1.
For advanced readers, to check the options to the compiler you can check this list. If you are a beginner, you can safely skip this. We'll look deeper on this later.

Run the program

Your program is compiled, you must run the program to check the output. Simply issue the following command,

Step 4 - Check the output

You should see the following output in the console,

Hello World

With this, the installation and verification process completes.


In this article, we have covered the following areas,
  1. We have downloaded and installed C compiler..
  2. We have written a C Program.
  3. We have checked how to compile a C Program.
  4. We have run the Program.
  5. We have verified the output in the console.
That's it for the day, we'll be checking more in our next articles.

Source Code Distribution

Although it is not a recommended practice, you can download the Source Code of this article. I have my repository hosted in github and published the source code which you can find on Palash90/C.

Prev   Next

First program in C

Now, we've installed C compiler on our system and also verified that it is working fine. Now let's write another program which takes input from the user and greets him/her. Side by side we'll look into different building blocks of the program.

So, here we go with our first program which greets the user by his/her name

#include <stdio.h>

 * This program takes user input and greets the user by his/her name.
 * Author: Palash Kanti Kundu
 * Since: February 25, 2016
int main(){
        // This is variable declaration
        char name[25];
        printf("Enter your name: ");
        //This line takes input from the user
        fgets(name, 25, stdin);
        //This line prints the greeting message
        printf("Hello %s", name);
        return 0; 

Let's first run this program and see it working, then we'll go into the analysis of the program.

From here onwards, keep in mind that there are two steps to run a C program,
  1. Compile the program
  2. Run the program
We'll know why we've to perform these steps. Let's first perform these tasks and give it some try.

$ ls
$ gcc hello_user.c
$ ls
a.out  hello_user.c

For convenience, I started with the file list before compiling.
So, as you know that in the first line I am checking what are the available files in the present directory.

Then, I have compiled the program with the file name. The program has successfully compiled and generated an output file a.out.

So, there is a problem, if you compile more than one program, then the system will retain the last compiled program output file and will overwrite the previous one.

A big problem right ?

Well, the compiler helps us with an option to specify the output file name. Let's take a look on this option.

$ ls
a.out  hello_user.c
$ gcc hello_user.c -o hello_user
$ ls
a.out  hello_user  hello_user.c

Now, if you see that there is another file in the directory with the name hello_user.
So, if you want to safely compile your program without omitting any other program, use -o.

Similarly you can also specify your output files to be stored in any particular directory if you wish. For example, the following line of command compiles the file in src directory and stores the output file in executables directory.

palash@ubuntu:~/git_repo/c/src/blog$ pwd
palash@ubuntu:~/git_repo/c/src/blog$ gcc hello_user.c -o ../../executables/blog/hello_user.out
palash@ubuntu:~/git_repo/c/src/blog$ ls
palash@ubuntu:~/git_repo/c/src/blog$ cd ../../executables/blog
palash@ubuntu:~/git_repo/c/executables/blog$ ls

For program files this option may not excite you but if you have multiple programs in a directory, then you will find this option very much helpful.

Well that was all about compilation for the time being, now let's run this program. In UNIX/Linux/Mac OS, you can run any executable using ./ command.

For example, we have made hello_user.out output file which is an executable file. So we'll run this program with the following command.

palash@ubuntu:~/git_repo/c/executables/blog$ ./hello_user.out
Enter your name: Palash kanti Kundu
Hello Palash kanti Kundu
palash@ubuntu:~/git_repo/c/executables/blog$ ./hello_user.out
Enter your name: Totan Das Kundu
Hello Totan Das Kundu
palash@ubuntu:~/git_repo/c/executables/blog$ ./hello_user.out
Enter your name: Annu Singh   
Hello Annu Singh
palash@ubuntu:~/git_repo/c/executables/blog$ ./hello_user.out
Enter your name: Debasis Das
Hello Debasis Das
palash@ubuntu:~/git_repo/c/executables/blog$ ./hello_user.out
Enter your name: Mita
Hello Mita
palash@ubuntu:~/git_repo/c/executables/blog$ ./hello_user.out
Enter your name: Debabrata Halder
Hello Debabrata Halder

These are sample run of the same program.

For Windows System you will find generated .exe files in the directory. Simply type the output file name in PowerShell and you'll find the similar output.

Now we've run the program and have verified the output against different input.

It's time to dissect the program and verify line by line of the program. We'll look into this section with each of the building blocks of the program.

Preprocessor Directive

The first line of the program includes another file. These type of commands are known as preprocessor directives. This basically instruct the compiler to load some other files from library. Like in our case the library file has the name stdio.h this file comes with any C distribution. It has some built-in functions for system calls.

If you modify the program and remove this line, then compiler won't understand the system calls and will not compile.

Try this yourself.

Blank Lines

The second line is left blank. This line will be ignored by the compiler. In fact you can have as much blank lines as you want and all these lines will be ignored by the compiler.


The third line starts with /* and the seventh line ends with */, this is known as block comments. Any lines within these two constructs are ignored by the compiler. Comments facilitate the purpose of human reading of a particular source code. So that anyone reading the program can understand what purpose a particular piece of code serves. Better comments are necessary for readability and maintainability of the code.

Apart from the paragraph comments, C also supports line comments. Any line starting with // are also ignored by C Compiler. As in our case, we have used line comments on 9, 12 and 14 to describe the purpose of each line of code.

You can use any type of comments any where in the program but conventionally, block comments are used to describe a block of code where as the line comments are generally used for fewer lines of code.


In line 8, we've written int main(). Actually this is a function declaration.
Function is an important building block for a C program. This is a bigger topic to discuss. For now just remember that, we need a function to execute our code. and to run our program we need int main(). Without this line our code will not compile.
If you are curious to know the consequence, just try it out. Its cool thing to try.

Variable Declaration

In line 10, we have declared a variable name. If you have knowledge of some other language you will understand this part. If not, then remember that for performing any input/output or calculation, we need variables.
Variables are nothing but a reference of a location in the memory for fine grained control. We'll discuss this topic in detail in our subsequent section.

Well, if you can't wait you can take a look on the variables. Although the article is targeted for Java, you will get some concept.

Function calls

In line 11, 13 and 15, we've used function calls. We are basically calling built in functions to facilitate working with the hardware. These functions actually deal with the Operating System. We use these functions to instruct Operating System to perform some specific task.

Return Statement

In line 17, we've written return 0;. This is known Return statements. This statements indicates that the function has completed its tasks and if required also returns some output from the function.
This is also a part of functions. When we'll talk about functions, we'll check this guy out.


In line 8 and 17 we've used {}. These known as parentheses/braces. These indicate a block of code. These come in pairs. In a program the number of { should match the number of }.
Keep an eye on these. They are often the cause of compilation failure.

Well, that's all about our first program.

After this article you should be able to 
  1. Compile and run a C program
  2. Identify different type of comments
  3. Identify function calls
  4. Determine the error caused by missing parentheses

Source Code Distribution

The source code of this article can be found on GitHub. You can check out the source code for verification purpose.
Although you can download, compile and run the source code, it is not a recommended practice and defeats the purpose of learning. The source code is meant for verification purpose only.

Source Code Link:

Prev     Next

int main vs. void main

I get many questions similar to 'What is the difference between int main and void main() ?'

Well, this is a bit conceptual. I will try to keep things as simple as possible.

As a first step, let's dissect the main function in C.

What is it ?
Don't complicate things, it's simply a function.

What's so special about it ?
Well, it is the entry point of your application. When your program is run, this init sequence is executed.

Well, if this is a function then there must be a calling function. Who calls main ?
The Operating System itself.

How does it make a call ?
Through the C Runtime.

What to do with the return ?
Well, as you may have understood, a function returns value to its calling function.

So, OS is the calling function, what should it do with a return value ?
OK, here it gets tricky. The return value in C can be either of the two values, EXIT_SUCCESS and EXIT_FAILURE. return 0; basically means a successful run of the program and returns to the OS and the value gets pushed to the call stack.

So, you have got the point, I guess, if you are returning void, that is nothing, then the program returns nothing to the OS after successful execution. So, nothing is pushed to the call stack. So, in times it may crash when it is called from a script or a makefile.

Now, you would likely to ask, which should I use ?
Of course the int main() version and return 0; at the end. Because, that's the correct signal, you are sending to OS. Any other return value indicates an error, which obviously is not the case.
Even some compiler allows void main();, this is not standard.

So, you should avoid the practice of writing void main(); in your programs.

For more details, you can check void main(void) - the Wrong Thing

Prev     Next

Variables in C

If you are coming from programming background, you may find this section similar to other programming languages but if not, you can find this section a bit tricky. I will try my best to go into the most detailed discussion.

This is one of the basic thing any programming language will have. The syntax may differ but surely there will be the concept of variables and data types. So, this is very important for any programmer. Try to understand every bit of it, try as many examples as you can. If you are stuck or cannot digest a particular portion of it, comments are welcome.

To start our discussion, we need to understand what a variable is and why do we require them at all.

Think of a person who can't remember anything or have a very short term memory.

What happens to that person ?

Scenario 1: The person rides a bus and gets a ticket for his travel. After sometime, he completely forgets that he had paid for his trip and again purchases another ticket and after a minute or two, he again forgets it and purchases another one or may be the worst case, he forgets where he has to go.

Scenario 2: The person takes his dinner and forgets after a minute or two and again takes his dinner and forgets again and again he takes his dinner until his body stops him to do so or he is killed by over eating.

These scenarios may look funny to the world but it is really not funny for the person who bears all these.

Similar situation can happen to your program if your program does not have a memory.

Let's take a simple program that does not have a memory.
#include <stdio.h>

 * This program calculates the sum each time it requires.
 * Author: Palash Kanti Kundu
 * Since: March 26, 2016
int main(){
        printf("%d\n", (5+6));
        printf("%d\n", (6+7));
        printf("%d\n", (5+6));
        printf("The perimeter of circle with %d radius is %f\n", 8, ((float) 2*22*8/7));
        printf("The perimeter of circle with %d radius is %f\n", 9, ((float) 2*9*22/7));
        return 0;

In this program, we see that, we do have nothing to store the result of a particular calculation. So, we have to perform the same calculations over and over again. This becomes overhead to the processing unit and also takes more time to execute. Also, the length of the code increases. This is just a program with only 5 calculations. You can imagine the length of the code if it had to perform more than 20 calculations.

Horrible, right ?
At some point, the code will be so clumsy that it would be extremely hard to read or understand what the program wants to do.

So, we have to think of a way that provides more flexibility in terms of code, usability and performance.

Let's rewrite the program where the program deploys some memory to store some of the calculation results.
#include <stdio.h>

 * This program calculates the result and stores in memory.
 * Author: Palash Kanti Kundu
 * Since: March 26, 2016
int main(){
        int i = 5, j = 6, k = 7, radius1 = 8, radius2 = 9;
        float pi = (float) 22/7;
        printf("%d\n", (i+j));
        printf("%d\n", (j+k));
        printf("%d\n", (i+k));
        printf("The perimeter of circle with %d radius is %f\n", radius1, ((float) 2*pi*radius1));
        printf("The perimeter of circle with %d radius is %f\n", radius2, ((float) 2*pi*radius2));

        return 0;

Now, you can see the difference, we've deployed some memory to store some of the calculation results and used them as and when required. This time, not only program performs less processing, the code also became more readable.

The second point is obvious, human beings are good at remembering names and not numbers.

Still, our program is not so good, let's make some more changes to make it more elegant that too using memory and user input.
 * This program calculates the sum each time it requires.
 * Author: Palash Kanti Kundu
 * Since: March 26, 2016
int main(){
 int i, j, radius;
  float pi = (float) 22/7;
 printf("Please enter two numbers to add\n");
 scanf("%d %d", &i, &j);
 printf("%d + %d = %d\n", i, j, (i+j));
 printf("Enter the radius:\n");
 scanf("%d", &radius);
 printf("The perimeter of circle with radius %d is %f\n", radius, (2*pi*radius));
 return 0;

Now this program is more readable, uses less memory and also works with user input. So, you can see that using simple memory blocks in your program always provides more flexibility, more readability and more robustness.

So, this is the point of using memory in our code.

Now, the question is how do we do that ?
We do that using variables.

You already have understood the concept of variable (if not, read again from the begining), now let's find a simple definition.

Variable: Variable is a reserved memory location to store data with a name and also provides a set of operations to be performed on the data. Programmers use the name of the variable to work on.

A variable declaration have the following syntax
data_type variable_name = [value];

If you don't know what do we mean by Data, check this article on Data.

So variable is memory location associated with a name and the particular set of operations that we can perform on that data.

By set of Operations we mean the operations are permitted for a particular variable.

For example, we can perform calculations like 2+2 and we know that the result is 4. Similarly, we can perform 2.3+9.2 and we know that the result is 11.5. We can perform these calculations because addition is legal on two numbers. Also 2 - 1 = 1 and this is a valid calculation. But we cannot do the calculations like, P + A + L or K - U - N. Because, simply these calculations do not have a meaning. We don't know what this calculations are supposed to do. In a nutshell, we don't define these calculations.

Similarly in C we can perform a set of operations on particular variable and cannot perform the same operation on some other variable. The set of supported operations are provided by the Data Type of the variable. The data type also restricts the programmer to assign a restricted set of value for a variable.

For example, we cannot assign a real number to a variable of type integer (whole number).

Another important thing to remember that we cannot use a variable before we declare them.
For example, the following program is invalid.

#include <stdio.h>

/* Program to demonstrate illegal use of variables.
 * Author: Palash Kanti Kundu
 * Since March 26, 2016

int main(){
        printf("Value of C is %d", c);
        int c;
        return 0;


This program is invalid because, we are trying to use the variable c before declaring it.
Although we have declared the variable on the very next line, it won't allow the compilation. Because, the compiler does not know what c is used for. May be after the declaration, the programmer may use it in a different way. So, the compiler does not take a chance and throws the error to the programmer. If you remember, computer is good at following instructions like a slave and it will never take a chance or apply its own logic to overcome a situation. Rather, it will scream to the programmer and will ask to correct it.

So, Variable is a name associated with a memory location and a set of supported operations. We declare a variable with its data type and name and use the name throughout the whole program as and when needed.

Now, what a variable name should look like ?

According to the rules of C,
  • Variable names are case sensitive
  •  A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_".
  • Subsequent characters may be letters, digits, dollar signs, or underscore characters.
  • Variable name must not be a reserved word.
  • Name can not contain white spaces.
  • Digit at start is not allowed
This rules alsmost allow every name to qualified as a good variable name. But at times, you may get confused with a variable name like 'abc' or '_un$789'. So, here are some tips while naming your variable,
  • Don't use '$' or '_' as the first character of variable name. It is allowed but not suggested.
  • Please use proper variable names, which can suggest the way this variable is used.
  • If your variable name is span across more than one word, you can capitalize each first letter of each word.
  • While naming constants, use all capitals while separating each word by '_'
Now, let me show you an example with a valid name and meaningful name,
#include <stdio.h>

/* Program to show different names of variables.
 * Author: Palash Kanti Kundu
 * Since March 26, 2016

int main(){
        int $m = 10;
        float PI = (float) 22/7;
        int maximumValue = 10;

In this program, both the names are valid according to the rules of C but anyone can hardly understand what the variable $m does but while looking out the variable PI, anyone can easily understand that this variable is used to store the value of pi and it is used as a constant. or anyone can easily guess that for this program the maximum allowed value is 10 with the help of the variable name maximumValue.

Source Code Distribution

Although it is not a recommended practice, you can download the Source Code of this article. I have my repository hosted in github and published the source code which you can find in