How to Program in C

You are fascinated by the world of programming and, since lately you have some free time to dedicate to it, you have decided to learn a little more about it. Following the advice of your friend who is already an expert in the sector, you have chosen the C language, certainly one of the most versatile and still used on the computer scene.

Resolute and determined to carry on your idea, you have opened your now trusted friend Google and, looking for instructions on how to program in C, you ended up straight on my guide, hoping to get the information you need on how to start writing working code. Well, I am happy to inform you that this is exactly the place you were looking for: in the following lines, in fact, I will provide you with a general smattering of the C language, explaining everything you need to write the first working programs.

Before going ahead and getting to the heart of the matter, however, I want to make you an important premise: programming in C is a rather vast topic, which certainly does not completely enter the page you are about to read. Indeed, I will tell you more: the entire structure of this site would not be enough to treat it in depth! Do not be afraid, however, as it will be my care to direct you, in the final stages of this tutorial, to useful resources and insights to enrich, if you wish, your knowledge on the subject. At this point, I would say to ban the chatter and start: I just have to wish you good reading and have fun!

Preliminary Information

Before you throw yourself headlong into learning the basics for program in C, let me give you some more information about this powerful language. First of all, C is a language procedural imperative, that is, capable of manipulating data through mathematical operations, grouped into specific defined procedures functions (which I'll tell you about later in this guide).

It is an ad language high level, which uses a syntax close to human language and relatively distant from assembly language and machine language: in other words, a large part of the existing instructions in C originates from the English language.

Unlike numerous programming languages ​​known to date, the C does not involve the use of objects: each complex data structure (e.g. array, record and any other entity that does not represent a primitive data type) must be manually declared and allocated in memory. However, some "derivatives" of C (such as the C ++, it C # o Objective-C) are instead object-oriented languages.

As you will discover later in this guide, the C is a compiled language: this means that, before it can function, the source code of the written program must be "translated" into machine language by a defined software compiler, which generates an executable file that can be processed by the processor and hardware of the machine, thanks to the coordination of the operating system.

In general, the C language is extremely flexible and is still used in a large number of scenarios: for example, it is possible to use C to write an entire operating system, program connected devices, create libraries dedicated to games, perform complex calculations distributed mathematicians and so on.

If you want to better understand the life cycle of a generic program and deepen the "steps" to be taken to write one efficiently, I suggest you take a look at my study on how to create a program.

Basic Syntax

So, ready to go? Perfect! In the sections to come, I intend to explain the basic concepts of the syntax of the C language, providing you with the necessary notions on the fundamental components of the latter: by doing so, you will acquire the necessary skills to write, in complete autonomy, a small working program.

First, a C program is written using one or more source files, which specify the instructions to be performed to process the data in the chosen way. Unless you intervene through jumps, conditions or special control loops (more on that later), the C uses an approach sequential: this means that, in general, the instructions are executed in the same order as they are specified in the source code.

Statement

Lo statement it is the basic entity of the C language: in simple terms, it is a complete instruction that, in some way, processes data. A C statement always ends with a ; (semicolon) and can perform any type of operation: it can add two numbers, compare two character strings, call a function, declare or assign a value to a variable, and much, much more. In other words, each statement contains a data manipulation “command”. By convention, each C statement should reside on a different line of source code.

Just to give you an example, the statement printf (“Hello everyone!”); contains the command to print the phrase “Hello everyone” on the screen.

The #include Directive

As I have already told you, a C program can run on different source files: this happens, in particular, to keep a certain order in very large projects. Typing everything in a single file of tens of thousands of lines of code could drive even the most patient programmer crazy: it would be a challenge to just modify a single instruction!

Precisely on the basis of this criterion, the C provides for a special directive #include, which is specified at the beginning of each source code and communicates to the compiler the other files to "include" in the program being compiled. Just to give you an example, almost all programs written in C start with the directive #include: in this way, you can use all the C commands specified in the so-called library of standard Input/Output, residing in the installation path of the compiler itself.

The stdio.h library contains the definitions of the basic commands and constants, to allow the programmer to manipulate the input / output (i.e. what is seen on the screen, what is acquired through keyboard and mouse) and file management. . Below you will list the most used ones.

  • printf ()fprintf ()sprintf () - these are commands that allow, respectively, to write data on the standard output device (ie the screen), on file and on character strings.
  • scanf(), fscanf() e sscanf() - these functions, on the other hand, take data respectively from standard input (the keyboard), from files and from character strings.
  • fopen () freopen() - these commands allow you to open a file inside a C program, so you can read data inside it or write others.
  • fread() fwrite() - these functions allow, respectively, reading and writing from a file.

Together with stdio.h, the stdlib.h library is often included in the source code, also included in the C development environment: this contains general functions and constants, including instructions to use to allocate memory and manipulate the data present within it.

The include directive can be specified in two ways: #include denotes the inclusion of a library present in the default development environment, while #include “libreria.h” specifies the inclusion of a library written by the programmer and present in the same folder as the source file in which it is declared.

Types of Data

As I have already explained to you, C is not an object language, therefore the more complex data structures must be declared and structured in memory manually. This does not mean, however, that this language is able to natively manage and manipulate numerous types of data elementary, which can be assigned to the variables necessary for the functioning of the program, acquired as input values ​​or rendered as return values ​​of functions. Below is a list of the most used types of data and the information you need about each of them.

  • tank - is the data type denoting a single character and occupies 8 bit in memory. To specify such a variable, it is sufficient to issue the statement char nomeVariabile;, while the code must be specified for the input / output functions %c for the compiler to correctly interpret the variable you point to.
  • int - this type of data denotes i whole numbers. Occupies 16 bits of data and can contain values ​​ranging from -32767 qualifying. 32767
    . Its identifier, in input / output operations, is %i.
  • float e double - identify i floating point numbers simple and double floating point numbers. They occupy respectively 32 e 64 bit of data and can represent decimals with precision of 6 figures (float) and di 10 figures (double). The identifiers to assign to it are %f % fd.
  • void - in C, this data type identifies the not worth, that is, an entity that does not occupy any space in memory. Generally, the void is specified as a return value or as an input in functions that I don't expect (as if to tell the compiler “be careful, this function or this operation will not return any value or accept no input values”). The void, as it is easy to imagine, does not have a characteristic identifier for the input / output.

Definition of Variables

I'm sure you somehow already know the concept of variable: if we want to formalize it, a variable is nothing more than a “container”, located in memory, which must contain values ​​that can be modified during the flow of execution of a program.

Before moving on, I would like to specify the difference between the declaration of a variable and its definition assignment: in the first case, the compiler is warned that a portion of memory must be allocated to contain data; in the second case, however, the memory is filled with the requested data. It is possible to declare one or more variables without defining them, but it is not possible to define one or more variables without declaring them (the compiler, in this case, would not know where to place the data in memory).

Declaring a variable in C is very simple: just type a statement that specifies the data type that the variable must contain, his name and, if necessary, the initial value (specified with the assignment operator =). For example, you can declare an empty integer variable through the statement int variable;, or assign it the initial value of 10 by giving it instead int variable = 10.

Once a variable has been declared, it can be manipulated in subsequent parts of the code using assignment with the = operator (e.g. variable = 51;), the increment, decrement operators and all that is required by the specified data type. Always keep in mind that, to be used, a variable must be necessarily declared in an earlier part of the code: C, as I explained to you, is a sequential language, so you can't ask a statement to operate on a datum it doesn't know!

Generally, variables can be referred to in C in two different ways: by the operations of assignment using the = operator or output manipulation functions (e.g. printf ()), you simply use its name (e.g. printf ("% i", variable); or sum = add (a, b);); if, on the other hand, you need to write data to a variable using certain input manipulation functions, such as the scanf () function, you need to refer to it through a pointer to the content in memory: to do this, just prepend the character to the variable name & (With art. scanf ("% i", & variable);).

Main Operators

Like all programming languages ​​in the world, programming in C also requires the use of operators, that is of some characters that, inside a statement, can acquire a “special” meaning, thus combining the data of the statement itself. The C language provides a large number of operators for handling the most disparate cases: the most important is the operator of assignment, that is =, which allows you to assign a value (or a more or less complex expression) to a variable or a series of variables. For example, type the statement int a = 1+2+3+4; means to declare an integer variable a and give it the initial value of 10.

In addition to the operator of assignment, there are numerous other operators in C: they are divided into four distinct categories, which I am going to explain to you below.

  • Arithmetic operators - as the name itself implies, are those that allow the execution of basic arithmetic operations: the + denotes addition, the the subtraction, the * multiplication, the / the division, the ++ the increment of one (it can be placed to the right or to the left of the variable to be incremented), the  the decrease of one (same previous rule) and, finally, the % returns the remainder of the integer division between values.
  • Relational operators - they are useful for relating one value to another, and are: > e(major / minor), >= <= (greater / lesser equal to), == != (same and different). They are based on the concept of true / false: for example, in a statement, the expression var = 10> 5 assign to was value it true 1, since the number 10 is greater than the number 5.
  • Logical operators - they follow the same true / false approach as seen above, but are used to compare the connection between two relations, typical of Boolean algebra. They are && (and logico), || (logical or) e (not).
  • Operatori bit a bit - they allow to intervene on the single bytes of the data types char and int, by carrying out exclusions, right / left shifts and comparisons. Mainly, these are used in writing modules for operating systems or device drivers, as they allow to intervene individually on the bytes (or on the words of files written in assembly).

Conditional Checks

As I explained to you at the beginning, C is a language sequential, that is, capable of executing instructions in the same order they appear in the program's source code. However, there are directives that allow you to modify the flow of program execution, changing its order when certain conditions occur / do not occur: these directives take the order of conditional checks. In the following lines I will illustrate the most used.

If/else

If you chew a little English, it will be easy for you to understand conditional control if: issuing this instruction means, in fact, communicating to the program something similar to "if a specific condition occurs, then execute this instruction (s)". Syntactically, the control comes in the form

if (condition) {instructions}

If you wish, you can specify an additional condition using the clause else: combined with the if, it allows to abstract the concept "if a precise condition occurs, then execute these instructions, otherwise (else) execute these others)".

if (condition) {statements} else {other statements}

You can express the condition using operators that return type results true / false, that is, the logical ones and the relational ones. Just to give you a concrete example, I propose a piece of code that can determine the maximum value between two variables, printing it on the screen.

if (a> = b) {printf ("The value of variable a is greater than or equal to that of variable b n"); } else {printf ("The value of variable a is less than that of variable b n"); }

If necessary, you can "enrich" the construct seen above with the clause else if: syntactically similar to if, it allows you to specify additional specific conditions to be taken into consideration, as explained below.

if (condizione1) {statements to handle condition1} else if (condizione2) {instructions to manage condition2} else {instructions to manage all other possible scenarios}

Switch/case

The construct switch/case, just like the one seen above, can affect the sequential execution of instructions in a program's source code. Although its operation is similar to that of the if / else (ie "jump" to a given set of instructions when certain conditions occur), it is used in quite different scenarios: the switch / case, in fact, is suitable for dependent decisions from the value of a variable and not from a Boolean operation. In human language, you can understand it a bit like “jump to case (case) X if the variable to be parsed (switch) takes the value X, otherwise execute the default operation (default)”.

For example, it is possible to use the / case switch in the case of input management: for example, the program behaves when the key is pressed a, another when the button is pressed b, still another when the button is pressed c and so on. Syntactically, this conditional check is expressed as follows.

switch (variable) {case: variable_value1
 education1; education2; ... break; houses: variable_value2
 education3; education4; ... break; default: instructions to manage other break conditions; }

At the end of each set of instructions for handling the various cases, it is essential to specify the clause break to exit the execution cycle and not block the program in an infinite loop, that is, in a condition from which it is unable to exit.

For example, this code excerpt could be used for a program that offers multiple functions at the same time, variable based on keyboard input (in this case, the user is prompted to type the letters a o c to choose the desired functionality).

char scelta; printf ("Scegli la funzione da utilizzare - a per aprire a file, c to close n "); scanf (% c, & choice); switch (choice) {case 'a': instructions to open a file; break; case 'u': instructions to close a file; break; default printf (" Command not recognized! "); Break;}

Ternary Operators

Another form of the if / else condition I told you about earlier involves the use of ternary operators :. These, in fact, allow to "abbreviate" the syntax of the aforementioned conditional, and are particularly used if two different instructions must be given depending on the result (true or false) of the comparison Boolean expression.

condition ? if_education : false_instruction

For example, if you want to compare two variables and notify the user about the outcome, you could use the following code.

(a> = b)? printf ("Variable a is greater than or equal to b"): printf ("Variable a is less than b n");

Functions

Now that you have fully understood the fundamental parts of the C language, it's time to put them together to create something that works. Before doing so, however, it is good to address the concept of function: by definition, a function in C is a piece of code that executes the algorithm necessary to obtain the desired result.

In other words, the function is the set of statements capable of manipulating the incoming data and produce outgoing data that are in line with the programmer's needs. In C, functions can be either declared and definite: in the first case, the compiler is "notified" of the incoming data, the outgoing data and the name of the function itself (eg. int add (int a, int b);), so as to allow the preparation of the various memory areas, while in the second case the statements necessary for data processing are specified, as shown in the example below.

int aggiungi (int a, int b) {// function to select a somma return a + b; }

The value that the function must return is expressed through the clause return, specified just before the end of the function code itself; moreover, all the statements that are part of it must be enclosed in two curly brackets. After being declared and defined, the function can be used anywhere else in the source code, specifying any input values ​​where necessary and, if required, assigning the output value to a variable. In the following code, the value of the variable sum is set to 9.

int somma = aggiungi (5, 4);

Generally speaking, functions are declared before the main body (which I'll talk about shortly) and defined right after it. A declared function can be included in the code that precedes its definition but it must be defined in the source code in which it is called, otherwise an error will be generated during program execution (which, instead, will be compiled without problems).

The "special" Main () Function

Now that you have all, absolutely all the basics of this language, it's time to explain to you how a rather special function works, the one from which the execution of every source code in C starts: the function Main(). It represents the main execution flow of a source code and contains all the instructions necessary to process the data required by the programmer. In other words, the main () function is the "engine" of a C program, which allows you to execute the main algorithm designed by the programmer himself.

Inside it can be used variables and conditional expressions of any type, functions belonging to the libraries specified through the #include clause, functions declared and defined within the same body of the source code and so on. A main function must not be declared, but must be defined directly within the code (usually this is done after the declaration of "global" variables and functions, that is, usable by all functions of the source, and before their definition).

At this point, it is quite easy to guess that a C source code, in order for it to be executed, must contain one and only one main () function. Generally speaking, the main function returns an integer value (which is usually used for handling execution errors) and takes no input values.

int somma (a, b); int main (void) {int x = 5, int y = 6, int somma; somma = aggiungi (x, y); printf ("Il valore finale è% i", somma); return 0; } int somma (a, b) {return a + b; }

Working Code Example

Now that you know all the basic information about this fascinating language, you should be perfectly capable of putting it together and writing a small working program. The first example that I want to illustrate is the classic "Hello World", that is a program that does nothing but print on the screen the greeting "Hello, world!". Below I show you the source code HelloWorld.c, which will then be compiled to become a ready-to-run file.

#include // Include the function defined in the standard I / O library, with printf ()

int main (void){// dichiarazione della funzione principale main
   printf ("Hello, world! n"); // funzione che stampa a video a testo ricevuto eat parameter
   0 return; // dichiara il value di ritorno del main (in genere, il value 0 denotes the ending with success)}

Were you able to fully understand the code illustrated above? Great! So, as an additional proof, I would like to offer you a second source code (to be called, for example, calc.c), slightly more complex, which simulates the behavior of a very basic calculator.

In it, the main function will take care of collecting the data and feeding it to one of the four functions designed to perform the main operations (addition, subtraction, multiplication and division). Finally, the main will always take care of showing the final result.

#includes #includes int addition (int a, int b); // Declaration of the functions that perform the calculations int subtraction (int a, int b); long multiplication (int a, int b); float division (int a, int b); int main (void) {int val1, val2, res1; // Declaration of variables to be used in the main long res2; float val5, val6, res3; char choice; printf ("Which of the four operations do you want to perform? n"); printf ("+ by addition, - by subtraction n"); printf ("* by multiplication, / by division n"); scanf ("% c", & choice); // read keyboard input switch (choice) {// loop switch / case that controls the operation to be performed case '+': printf ("Type the values ​​to add, separated by a space n"); scanf ("% i% i", & val1, & val2); res1 = addition (val1, val2); printf ("The result of the operation is% i n", res1); break; case '-': printf ("Type the values ​​to subtract, separated by a space n"); scanf ("% i% i", & val1, & val2); res1 = subtraction (val1, val2); printf ("The result of the operation is% i n", res1); break; case '*': printf ("Type the values ​​to multiply, separated by a space n"); scanf ("% i% i", & val1, & val2); res2 = multiplication (val1, val2); printf ("The result of the operation is% ld n", res2); break; case '/': printf ("Type the values ​​to divide, separated by a space n"); scanf ("% f% f", & val5, & val6); if (val6 == 0) printf ("Could not divide by 0 n"); else {res3 = division (val5, val6); printf ("The result of the operation is% f n", res3); } break; default: printf ("Invalid choice! n"); break; } return 0; } // Definition of functions to perform operations int addition (int a, int b) {return a + b; } int subtraction (int a, int b) {return ab; } long multiplication (int a, int b) {return a * b; } float division (int a, int b) {return a / b; }

I bet you have been able to perfectly understand how this program works, but are you afraid of not being able to write something like this? Don't throw in the towel and keep practicing: I'm sure that, in a few hours, you'll be able to write a program yourself that works!

How to Compile and Run a C Program

After gaining the basics of the C language, as well as having a look at a working program prototype, it is time to go to practice and understand how to compile and run a C program using various operating systems. I announce immediately that, unlike Windows (which requires additional software), macOS and Linux are natively “set up” for compiling source codes in C: you just need to know the right instructions to give!

Windows

As I mentioned earlier, to transform a C source code into a working program, you need to install an additional component to prepare the operating system for this operation: I'm talking about Visual Studio Community.

To do this, connected to the program's Internet page, press the button Free download resident in the box Visual Studio Community, start the downloaded file (eg. Community.exe), then presses the button Continue, set the check mark next to the item Desktop application development with C ++ in the proposed window, repeat the operation with the voice C ++ / Cli support located in the right pane and, to finish, click on the button Install, to then close the setup window at the end of the procedure.

At this point, call up the Block notes from the folder Windows Accessories from the menu Start (which you can access by clicking on the button in the shape of a flag, located in the lower left corner of the screen), type the code of your program in the editor window and, to save, click on the menu Fillet located at the top left and select the item from it Save with name .... Once this is done, select the item All files give menu to tendin Save eat, attached to the save screen that opens, type the name of your program, followed by the extension .c (With art. calc.c), in the box File name, and then save it on the desktop.

To compile the newly created source code, run a Command Prompt for Developers calling it from the folder Visual Studio from the menu Start, type in the commands cd %USERPROFILE%Desktopcl programname.c, both followed by the button Submit, and then start the newly created program on the desktop (eg. calc.exe) with a double click.

macOS / Linux

As I have already explained to you above, MacOS e Linux they are natively predisposed to the compilation of programs written in C, as these operating systems are strongly based on it. So to compile and run a C program, call the terminal from Launchpad di macOS or from Activity view / main menu of the Linux distribution you are using, type the command cd ~ / Desktop (if you are on macOS) or cd ~ / Desktop (if you are using Linux instead) followed by the key Submit and, again, the command touch nomeprogramma.c (e.g. calc.c), always followed by Enter.

At this point, leaving the Terminal open (you can minimize it if you wish), double-click on the .c file thus created on the Desktop, type in it the code of your C program and save the file. To compile it, call the Terminal and type the command gcc nomeprogramma.c-nomeprogramma followed by pressing the key Submit and, to execute it, issue the command ./nomeprogram, always pressing successively Submit.

I advise you to carefully read any warning messages returned by the compiler: these, in most cases, are an excellent starting point to locate and correct any errors in your program.

Useful Resources

Now that you have all the basics of the case and that you have a clear idea of how to program in C, you are perfectly capable of evaluating if this is the programming language for you. If so, as I promised you at the beginning of this tutorial, I would like to direct you to additional useful resources that can help you further improve your approach with the language in question, as well as increase your knowledge and help you acquire additional specific skills in merit.

  • Notepad ++ - one of the smallest and most flexible editors to write (and correctly indent) source files in C language in the environment Windows. It supports numerous programming languages.
  • Eclipse - is an entire programming framework, useful for organizing and keeping even particularly complex projects organized. It supports all file types expected by programs written in C (source files, object files, headers, libraries and so on) and allows, if necessary, to create UML graphics and help files.
  • HTML.com C Guide - definitely a great free resource. Among the pages of this precious guide, freely accessible by anyone and without any registration, you can find insights and lessons aimed at honing your skills as a C programmer.
  • Language C - Programming principles and reference manual (Kernighan / Ritchie) - is undoubtedly one of the best texts on which to deepen one's knowledge of C, known to experts in the field as the "K&R" (from the initials of the authors). Structured in two parts, this text initially offers instructions on how to approach the language in question, and then turns into a real manual that defines all (or almost) the functions that can be used in the many scenarios envisaged. The two authors, Kernighan and Ritchie, are the ones who designed and developed the entire C language.
  • C / C ++ Programmer's Reference (Schildt) - in my opinion, one of the most complete texts relating to the C language, to be kept absolutely on your desk if you intend to approach this language for professional use. Mainly suitable for more or less advanced users, it contains numerous examples of the most used functions. This manual can also be used by those who, on the other hand, have decided to move towards the "object" version of the C language, the C++.