The best way to learn a new programming language is by writing programs in it. What better place to start than by writing the famous “Hello World” program!
#include <stdio.h>
main()
{
printf("Hello world!\n");
}
Running the program would depend on the system you are using. On a Unix based Operating System, you must create the program in a file which ends in “.c”, such as “first_program.c”, then compile with the command:
cc first_program.c
If there are no errors, the compilation will proceed silently, creating an executable file called “a.out”. Then you can run “a.out”, by typing the command:
./a.out
Let’s look at the code we wrote above in details now. A C program consists of functions and variables. A function contains statements that specify the computing operations to be done, and variables store values used during the computation. In this above program, “main” is a function. In fact, “main” is a special function – your program starts executing at the beginning of “main”. So, every C program must have a “main” somewhere. The first line of the program:
#include <stdio.h>
tells the compiler to include information about the standard input/output library. One way of communicating data between functions is for the calling function to provide a list of values, called arguments, to the function it calls. The parentheses after the function name surround the argument list. Here, “main” is defined to be a function that expects no arguments, which is indicated by the empty list. The statements of a function are enclosed in the braces {}. The function “main” contains only one statement:
printf("Hello world!\n");
A function is called by naming it, followed by a parenthesised list of arguments, so this calls the function “printf” with the argument “Hello world!\n”. “printf” is a library function that prints output, in this case the string characters between the quotes.
A sequence of characters in double quotes, like “Hello world!\n”, is called a character string or string constant. The sequence ‘\n’ in the string is C notation for the newline character, which when printed advances the output to the left margin on the next line. Notice that ‘\n’ represents only a single character. An escape sequence like ‘\n’ provides a general and extensible mechanism for representing hard-to-type or invisible characters. We’ll encounter more escape sequences later in the course.