Interview Questions

A Simple Example

Let us understand how a simple C program works. I am taking the first program of all C developers as my choice to explain this.

#include <stdio.h>
  printf (“Hello World!);

(Type in the above program in any editor, save the file as first.c and compile using cc –c first.c –o first in your present directory. You will be able to execute the program by ./first. You can see the output as Hello World.)

As you can see, first line of the file has a # (Hash) include - this indicates that you are in turn including a .h file (header file) which is a system library in unix/linux. This library has the printf function defined in it.

Point to note: you need to declare a function before using it.

Second line is main() – All C programs will have 1 main() function/method MANDATORILY. This main() method is the instruction to operating system to start executing lines from this place.

Third line is { and fifth line is } – this indicates start and end of a function. Each function starts with opening bracket and ends with closing bracket.

Fourth line is printf(“Hello World!”); - this indicates that you are calling function print() with argument (also called as parameter) to print the data that is specified within “” (double quotes). Here we are printing Hello World!.

When you are compiling using cc –c first.c –o first – here you are saying compile the first.c file and create an output first. Output is the executable file created by compiling your 5 lines of code and linking it with system library stdio.h.

That's all! You have just written your first C program.

Let us see key takeaways from this lesson:
1. All C programs will have 1 main() method.
2. All methods start with method name, followed by () and the contents of the method within { and }.
3. Including system libraries is possible using #include construct.
4. All C programs are saved in files with .c extension.
5. CC is the C compiler that is used to compile and run the code.
6. Output is a binary file and that can now run in Unix/Linux operating systems.

If you have to relate to the first paragraph, we said C is a procedural programming language and is built around the functionality that is being developed. In our example, we wanted to print a statement Hello World on the screen. We achieved that with main() method/function.