Getting Started with C Programming
Learn the basics of C, and how to compile and run your first C program. It will help you understand how basic programming works. Includes exercises for practice.
Creating a C Program
Before studying C in depth, it's recommended to start with some basic programs to familiarize yourself with C programming. This introduction aims to provide a minimal foundation, especially for those who have never programmed before.
To start programming in C, you need a program called a compiler, which converts the code we write into a file that our operating system can open. For example, we open Microsoft Word by double-clicking on an executable file with a .exe
extension. Each operating system can open a different type of executable. We can't open a Windows executable on Linux, or vice versa. Compilers are responsible for creating the executable file for each operating system.
However, for an introduction, explaining the process of running C on different operating systems is somewhat cumbersome. So we'll use Replit, which is an online tool to run C programs regardless of the operating system we're using.
Let's create a new Repl, selecting the C template and writing the title helloworld
. By default, Replit will display code like this:
#include <stdio.h>
int main(void) {
printf("Hello World\n");
return 0;
}
When you click Run, it will display the phrase Hello World
on the screen. This will be shown in a panel called the console. Here are several key concepts to understand in application development:
- C code is code that programmers familiar with the C language understand. However, the computer doesn't understand this code.
- When we click Run, the C code is passed to a compiler. This compiler translates the C code into code that the computer understands. This code is called machine code. In addition to translating the code for the computer, it also executes it. This step would be like opening an application on our computer.
- Finally, we visualize the program on the computer. In this case, there is no graphical interface, so everything we visualize will be through a command console (also known as CLI).
The workflow we'll use to develop C programs is basically to first write code, and then click Run for Replit to automatically compile and execute the code, so we can see the result on the screen.
Syntax
If we write the code incorrectly, when we execute Run it will give an error, which will be shown in the command console. To see this in action, let's remove the semicolon ;
from the end of the printf
line in the code. When clicking Run the console will give an error:
./main.c:4:26: error: expected ';' after expression
printf("Hello World\n")
Generally, we resolve the errors the program gives us by reading the error message. In this case, it indicates that it expected a semicolon ;
after the expression.
An expression, in very simplified terms, is a type of text we write in the code that has a unique value. For example, "Hello World\n"
is not the same as "Hello Kitty\n"
.
The group of expressions that generally form a line in the code is called a statement. In this case, the statement would be printf("Hello World\n");
.
In C, all statements must have a semicolon ;
at the end. However, the compiler gives an error that it expects a semicolon after the expression. This is because the compiler treats the entire statement as a value, that is, it treats it as a final expression. But a programmer should treat it as a programmer, not as a machine. So we treat the line printf("Hello World\n");
as a statement, and since it's a statement, it must have a semicolon at the end ;
.
The use of the semicolon is a syntactic rule. Just as in English sentences end with a period, in C statements end with a semicolon. Without these rules, the compiler wouldn't know when one statement ends and another begins.
A large part of the errors when programming is writing the language syntax incorrectly. That's why it's important to review these concepts, which are basic at first glance, but so important for locating and correcting errors in the code.
✍️ Exercise: Copy and paste the following code, and fix the errors it has. When clicking Run it should display all the text.
#include <stdio.h>
int main(void) {
printf("Hello\n")
printf("You are\n")
printf("fixing the code\n");
printf("your first time\n!")
return 0;
}
✍️ Exercise: Which of the following statements is correct?
A.
printf('Hello World');
B.
printf("Hello World");
C.
printf('Hello World\n);
D. None of the above
Program Structure
From the console output, we can infer that the statement printf("Hello World\n");
displays the phrase Hello World
on the screen. For this to work, the rest of the code must always be included:
#include <stdio.h>
int main(void) {
printf("Hello\n");
return 0;
}
The first line, #include <stdio.h>
is called a preprocessor directive. This directive tells the compiler that it must include another file. Hence it's called include
. The file it needs to load is called stdio.h
. Here we need to understand that C is a language. By itself, it does nothing. That's why files like stdio.h
exist, which give it functionality. In this case, stdio
stands for standard input/output. An output can be the computer screen. When we display Hello World
on the screen, we're actually using an output function from the stdio.h
file. This file was created by C developers and is included with any C compiler. In addition to displaying on the screen, the stdio.h
file also allows us to write text with the keyboard, open files, and other basic but very important functions when we're creating a program. Otherwise, the program would do nothing, and therefore would be useless.
The second line, int main(void) {
is actually a code block:
int main(void) {
}
We know it's a block because it's wrapped in curly braces {}
. This block is very important as it's where the program is executed. All programs, from the smallest to the largest, must have this block. This block is called a function. Functions, as their name suggests, perform functions. Whether it's displaying text on the screen or opening a text file, each function has its purpose. In the case of this function, it's about executing the entire program. We can create as many functions as we want, and call them whatever we like. However, we can't change the name of this function. It must always be called main
. Syntactically we see that it has more words, like int
or (void)
in parentheses. We'll see later what they mean, the important thing is to understand that everything that goes inside this block will be executed when the program starts.
Inside this block we only have two statements left:
printf("Hello World\n");
We've already intuited that this statement displays Hello World
on the screen, in the console. printf
is the name of the function. This function exists thanks to the file we loaded earlier, called stdio.h
. If we don't load this file, the compiler would give us an error. Because it doesn't know what printf
means. The word printf
is short for print formatted. Print in English also serves as a synonym for display on screen. Following the word printf
there are parentheses. These parentheses ()
, in the universal language of programming, mean: whatever the function does, I want you to consider this value I'm passing. Think of a washing machine. If you don't put clothes in a washing machine, it would have no use. Similarly, if you don't indicate the text to display to a function that prints text on the screen, it won't do anything. So inside these parentheses we indicate the text we want it to display. However, there's another syntactic rule, the quotes ""
. The compiler is not a mind reader, and needs to know if what we're writing is a function, or simply text we want to display on the screen. For this, we delimit the text between two double quotes ""
. If we write printf("printf");
the compiler will distinguish which printf
refers to the function, and which printf
will be displayed on the screen. Another detail in the statement is that after the word World
a combination of characters is shown: \n
. Within any text, if we include \n
, we're telling the function to add a line break. To show for example a paragraph break, which would be two lines, we would simply add two \n
at the end, resulting in: "Hello World\n\n"
.
Finally, there's the last statement:
return 0;
This statement tells the program that main
has finished, that is, there's no more program, and the 0 also communicates that everything went well, without errors. At this point, depending on the system, the console will either close automatically or will close when we press any key. In Replit it doesn't close, as it stores previous results for didactic purposes.
✍️ Exercise: What does the following statement display on the screen:
printf("printf");
?A.
Hello World
B.
Printf
C. Nothing
D.
printf
✍️ Exercise: Display the following text respecting line breaks:
Hi,
How are you?
Regards.
Comments
Everything written in the code file is subsequently analyzed by the compiler. Each word, each character in the code, is meticulously analyzed to determine what it means. Sometimes, we need to write things inside the code file that we don't want to follow a rule. For example: a comment to explain what a part of the code does. This comment is only for yourself, or for someone else to better understand the code.
Comments, although they're inside the code, are ignored by the compiler, so they won't be loaded into the final program, and can only be read by users who have the source code.
In C, you can add a comment per line, or use several contiguous lines. To comment on a line, you must first write two consecutive slashes //
and then the comment:
#include <stdio.h>
int main(void) {
// Print to the screen Hello World
printf("Hello World\n");
return 0;
}
In this case the comment is above the function. It can also be included at the end of a statement:
#include <stdio.h>
int main(void) {
printf("Hello World\n"); // Print to the screen Hello World
return 0;
}
And if the comment is longer, instead of writing two slashes per line, you can write slash and asterisk /*
at the beginning, and asterisk and slash at the end */
:
#include <stdio.h>
/* This is a simple program that
shows how to print text in
a console
*/
int main(void) {
printf("Hello World\n");
return 0;
}
Another common use of multi-line comments is to comment out blocks of code that we don't want to execute at the time of development.
✍️ Exercise: What are comments used for?
A. To clarify certain confusing parts of the code
B. To document the project
C. To add reminders
D. All of the above are correct
✍️ Exercise: Comment out the statements that are incorrectly made using a multi-line comment and run the program to verify that it works.
#include <stdio.h>
int main(void) {
printf("Hello World\n");
printf("This is a test")
printf('And I'm testing more');
return 0;
}