This is a great classic in programming, the first program you run displays Hello world. This course does not escape the tradition. Here is a first program in C that we will detail:
#include <stdio.h>
// My first program
int main(void) {
/*
Program starts here
and displays "Hello world"
*/
printf("Hello World\n");
return 0;
}
In the following course, you will be able to test the programs directly in your browser using the interface below:
The first line of the program #include <stdio.h>
is a preprocessor directive. It specifies
we use a library of functions that is in another file, here the stdio.h
file. This
library is necessary because it contains the printf
function that will be used
in the program. Without this inclusion, the program will not run because it will
not know where to find theprintf
function.
We will come back later in detail on the syntax and the different uses of this line.
Just remember that it allows you to use the printf
function.
Comments are lines that are ignored by the program. They are only used only to help the understanding of the code. There are two types of comments :
//
/*
and ends with */
Here is an example:
// A single line comment
/* a multi-line
comment */
When learning programming, we tend to neglect comments because the programs we write are - by their pedagogical nature - ephemeral. The problem is that young developers keep this bad habit in their first projects. Neglecting comments always leads to being caught up by karma:
A C program must always have a main function (also called main program), whose syntax is:
int main(void) {
// Inner code of the main function
...
}
It is too early to explain the syntax of this code, but it is imperative to know that this main function will be executed first. You must place between the braces the lines of code that will be executed when the application starts.
In C, the instructions are run sequentially, that is to say that the first line of the main function will be executed first, then the second and so on.
printf
is a function that belongs to the stdio.h
library. printf
means
print formatted. It displays the text which is between the parentheses. The double
quotation marks indicate that it is a text.
At the end of the text is the special character \n
, which tells the printf
function
to display a line break. It is often used to make the display clearer.
The last line of the main function (return 0;
) is used here to indicate that the
program has ended under normal conditions and there were no errors.
Modify the Hello world program so that it displays Bonjour le monde. Run and check that it works properly.
In exercise 1, did you remember to change the comments? If so, I congratulate you.
If not, now is the time to do so.
What is the syntax for creating multi-line comments in C?
What syntax allows you to create comments on a single line in C?
What are comments for?
Where does the program execution start?
About #include <stdio.h>
...