C programming: Getting to know C


Introduction

In this course we will learn the C programming language from the basics. C is a simple, small, yet very powerful programming language. C is the sturdy foundation in which many modern programming languages (including but not limited to Java, C++, C#, JavaScript, PHP, and PERL) are built upon. The program that runs your calculator, or your digital watch, your washing machine or apps in your smart phone are built in C or other programming language built upon C.

In the eighties there was a little Indian car that took over the Indian car market. It's features: It was small, beloved, indestructible, incredibly adaptable and a classic family car. We are talking about the Maruti 800. Think of C as the Maruti 800 of the programming languages. Back in those days learning t program in C was the passage to the computer wizard zone. In fact, that is how the software giants Apple Inc. and Microsoft were built by Steve Jobs and Bill Gates, respectively. The book we will use to learn C is a small, yet elegant book called "The C Programming Language" by Dennis Ritchie and Brian Kernighan. You can buy a copy of the book here at Amazon. (http://amzn.to/2z2Nhng). Both of them (Kernighan and Ritchie) worked at the legendary Bell Labs, Developed the C programming language. And with the help of C, they wrote UNIX, the operating system that runs the Internet. The UNIX variant of the operating system Linux is the engine to many web-servers (e.g at Google, Amazon, Twitter, Facebook and Flipkart) and inspired many other OSs such as Mac OS, Android etc. This is too the same operating system preferred by many computer scientists.

So, Let's get started!

Anatomy of a C Program

So, now we know that C is a simple, general purpose programming language. Let's take a look at the sample code and get the feel for the syntax and style for the C program. So here we begin the ritual, the "Hello World!" program. For that we need a simple text editor (Notepad on Windows or nano, vim or emacs on Linux). You can download Sublime Text, for great syntax highlighting and code completion. And also you need a C compiler (GCC). It is always best to create a folder for your C training life. Inside that folder create a file named "hello.c" (without the quotes). And type in the code below:

/************************************
hello.c
My first C program
Created by Swastik on 1st Nov, 2017
Copyright (C) 2017 Swastik Nath
************************************/
#include <stdio.h>
int main()
{
	/* code goes here */
	printf("Hello, World! \n");
	return 0;
}

Now save the file (as hello.c if you didn't name it earlier; the suffix .c suggests it's a C program source code). This is now a C program Source file and it's contents are called source code, this can now be compiled with any of the C compiler.

A compiler is a computer program (or set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language, often having a binary code). Source: WikiBooks

If you take a look at the program closely, you will see some sensible indentation (the line formatting to increase readability). It is always best to use proper indentation, for you (or your friend) might come back months later and can still read the code easily or, maybe edit it (especially on a large software project).

The line #include <stdio.h> is called an include statement and it includes the header file called "Standard Input / Output" (short for stdio and the .h extension refer that it is a header file). This line tells the compiler to locate the C header file stdio.h and prepend it's contents to the file before it's conversation into executable binary code. Without the header file, the compiler expects the coder to have explicitly described all the implemented functions in the source code. As, we have not done so, the compiler will run into an error.

Now, let's take a look at the rest of the program. The main() is a function named "main", that we are going to write. Every C program must contain a main function that is the starting point of execution. All C programs require one and at-least one function "main" for execution. The left and right curly braces {} surround the code block, the lines of code each ending with a semi-colon. These lines are called "statements", these statements define the behavior of the function main. The statement printf("Hello, World! \n"); instructs the computer to print out the string Hello, World! followed by a newline. The newline resets the location where the next line of code will be printed. The lines of text enclosed in /* and */ are called comment lines. We may also use statements starting with //.

A comment is an explanatory text you may write to provide a glimpse into your thought process or maybe to give information about the source of the code or coder information etc. It is highly recommended to to include comments in your code. You should be careful while writing the comments though; they can easily be a clutter of distracting text in your source code.

The return 0; statement simply tells the computer that the program executed successfully, by returning the integer value 0. As you can see we started with int main(), which tells the computer that the main function ends by returning an integer (int for integer) value.

Now you can compile it to see the program in action.

Compile and Run

Compilation is the conversion of source file into a runnable program called an executable file by compilers such as cc or gcc, in case of C programming. The gcc takes the .c text file and assuming there are no syntactic errors in your code an executable is made in the same directory. If there are any errors or warnings lurking in your code the compiler will often display an error message, often including the exact line number and column number where the error occurred. Let’s compile our hello world program.

Here, I am assuming that you are on a Linux terminal and already familiar with it. (If not please read my previous notes on Linux Commands on terminals). In the terminal window enter (except the dollar sign)

$ gcc hello.c

You will be simply prompted with the dollar sign on successful compilation. And a new executable file a.out will be placed in the present working directory. You can run the executable with the command:

$ ./a.out

This will display the text Hello, World! in your terminal window.

Yahoo! You've successfully compiled and ran your first C program. Congratulations, Excelent job. Now time for some quiz questions.

Quiz Questions

  1. Every C program must have a main function. (True or False)
  2. How do you call the print function in C?
    (a) printf("hello, World!");
    (b) printf("hello, World!\n");
    (c) printf("hello, World!")
    (d) printf(hello, World!);
  3. Which is the proper defination of main function?
    (a) int main ()
    (b) main ()
    (c) main (int)
    (d) main int ()
  4. Which line is missing from the following piece of code?
    int main() { // this is a comment printf("Hello, World!\n"); return 0; }
  5. The return statement is usually the last statement in the main function. (True or False)

Play with the code : Even the best programmers have errors in their code. Try removing the semi-colon ; and see what kind of error the compiler produces. Or maybe, try replacing printf function with print. Try compiling after removing the parenthesis () after the main, this will produce the same error message as it did without the semi-colon ;. The point I want to make here is that you cannot expect gcc to tell you about all the errors, some of the times you need to use your mind and fix the errors on your own. This should give a taste of what kinds of errors you might see during compilation of the C source codes.

Answers

  1. True
  2. a, b
  3. a, b
  4. #include <stdio.h>
  5. True
Show Comments