First Steps
Get started with learning about the structure of a C program for printing to the screen.
We'll cover the following
For our first step into the vast world of C, we’ll start by writing a simple program to display something to the console. We’ll then see some related things that’ll be helpful in the long run.
C uses the printf
function to output whatever data we have.
A first C program
The printf
function is part of a C library (the standard I/O library) which contains many other useful functions as well. It is a standard practice to include the library into your code. This can be done by typing #include <stdio.h>
at the top of our code. This #include
line is called an include directive, as it’s an instruction to include the library in our code.
In general, C standard libraries can be made available for our use by including appropriate files with a .h
extension (such as stdio.h
) in our programs. These are called header files.
Now, on to the main part of the lesson. Let’s print “Hello world” in our console:
#include <stdio.h>int main(void){printf("Hello world");return 0;}
Again, don’t worry about int main(void)
, the enclosing curly brackets {
and }
, and the statement return 0;
. It’s simply the context in which our code runs. "Hello world"
is a piece of text which we call a string. More on that later.
Congratulations! We’ve written our first ever C code.
A note on the printf
function
The printf
function can actually be used in much fancier ways such as:
#include <stdio.h>int main(void) {printf("Hello %s", "world");return 0;}
Here, you’ll see there are two separate strings "Hello %s"
and "world"
but once again the same message Hello world
is printed to the screen. That’s because the syntax %s
serves as a place holder, and is replaced by the text world
before the string is printed.
There are other kinds of placeholders (%d
, %c
etc.) used with the printf
function that we’ll see in the next lessons but we won’t always stop to talk about them. All this will become clear with time.
Code comments
Code comments are remarks that are left in the code for a human reader, and they are not executed when the program is run. In C, we can use //
for a single-line comment, or the pair /*
and */
for opening and closing a comment that spans multiple lines:
#include <stdio.h>int main(void) {// Here is a print statementprintf("Hello world\n");/* Here is a print statementthat uses %s */printf("Hello %s", "world");return 0;}
You may have noticed that we sneaked in a \n
at the end of the string on line 5—the so-called newline character. That’s what causes the next output to be printed to a new line. Try removing it to see how the output changes.
In the next lesson, we’ll learn about variables and how they are essential to our code.