First program in C

The best way to start learning C is to code your first program.

Open a text editor and type the following:

#include <stdio.h>

int main(int argc, char *argv[])
    printf("Hello, world!\n");

    return 0;

Save it as helloworld.c, compile it and execute it. If you haven't had problems you'll see the phrase Hello, world! on your screen.

Now let's explain the lines of this code. The first line, #include <stdio.h>, contains a preprocessing directive. This directive indicate to include the stdio.h standard input/output header that permits using functions like printf.

The next line, int main(int argc, char *argv[]), is the main function to begin the program. The type int means that main has a integer return value. The first argument, int argc, is a count of the number of command-line arguments. The second argument, char *argv[], is the array of the command-line arguments themselves. The opening curly brace, {, indicates the beginning of the definition of the main function and the closing curly brace, }, indicates the ending of the definition of the main function.

The line printf("Hello, world!\n"); writes to the standard output the sequence Hello, world!. The \n specifies the end of the current line and the semicolon terminates the statement of printf.

Finally, with return 0; indicates to the system a successful execution returning the integer value 0 in the main function.

No comments:

Post a Comment