First C Program: Explained

 Just a few days ago we took a look at how to get started programming using C. Today, we will take apart and examine the first program we wrote using C. To refresh your memory, here is the program we wrote:

#include <stdio.h>

int main()
 printf("Hello, World! \n");
 return 0;

The first line of the program, '#include <stdio.h>" is called the include line. This line includes a header file into your program, called 'stdio.h', which allows you to use built in function. More on includes will come in a later tutorial.

The line that reads 'int main()' is your main function, that is where you write your code. The code in this function is the code that will be executed at runtime. The C programming language uses curly braces '{ }' to designate the start and end of a function. Any code in between the braces is considered to be a part of that function.

The code inside the main method is where are the fun stuff happens. The first line of the main function reads:

printf("Hello, World! \n");

This line is actually a function call to a function called printf(), which will output what ever your write in double quotes. In this case the program will print 'Hello World!'. Notice it does not print the '\n'. That is because the '\n' is an extension which means 'new line'. Everything following the '\n' in the printf statement, which in this case there is nothing, will be printed on a new line. In the case there is nothing after the '\n' the program will print a new line and go on to execute the next statement. There are many other extensions which we will discuss later.

The next and final line in the main function reads:

return 0;

If we jump back up to the start of the main program, you will notice there is a keyword int before the word main. This keyword tells us what the return type of the function is, in this case it is an int or integer. The keyword tells us what this function must return, in other words output by the time the function has been executed.

In the case of this program we are returning '0'. We return '0' just to satisfy the condition of the function having the return type of an int. You could have returned any integer number you wanted here. As a convention, normally we return '0' to signify the function has been completed successfully with no errors.

As you will see later on, you can have multiple returns in a function. For example, you may want to return '0' if there were no errors or a '1' if their was an error. It is important to note, a functions final output may consist of only ONE return statement. There could be multiple in the function, but only one value can be returned at the end.

More tutorials coming soon! Let me know how you like the tutorials by commenting below and if there is any specific topics or languages you would like covered.

Programming Using C: Variables and printf

Get Started Programming Using C