← All articlesGuides

C programming: the most compact and thorough guide on the web.

Illustration of the letter C between golden curly braces, the symbol of the C language

In this guide I’ll try to share with you the fundamental notions of C programming.

There are hundreds of guides online, but some of them are absurdly long. So I’ll be brief, just enough to give you a general overview; I won’t cover pointers and lists, which are a bit more complex.

At the bottom of the page you’ll also find solved C exercises, tested and working.

This guide assumes you already have a development environment (or IDE) installed on your computer. If you haven’t yet, take a look at this article.

So, let’s get started!

C is a structured programming language, developed in 1972 by- - Just kidding! We don’t care about the history.

0. Prerequisites

A couple of things to keep in mind:

  • The main function in any program is main(). It is mandatory and unique, meaning it must appear exactly once.

  • Before closing the main(), that is before the last closing curly brace, you must always write return 0. If you’re closing a void() instead (I talk about it a few lines below), the return is not needed.

  • The semicolon is used to end a statement, so after that symbol the next statement begins — if there is one.

  • Curly braces are used to delimit blocks of statements.

  • To print a newline when printing to the screen (with printf) you use the \n character.

  • If you want to print a character with an accent, it’s best to write it with an apostrophe (for example, è should be written as e’).

Oh, one more simple concept you’ll find useful later is the difference between a function and a procedure. A function is a set of statements (a routine) that returns a value. A procedure, on the other hand, is a routine that returns no value.

1. Libraries

First of all you need to include the libraries. Our IDE needs them to interpret and compile the program we’re going to write, so without them nothing will work. The standard ones are <stdio.h> and <stdlib.h>, so at the top of the page we write:

#include <stdio.h>
#include <stdlib.h>

If we need to work with strings, chars or character arrays, we’ll also use the <string.h> library.

Another library you’ll find in the solved exercises is <time.h>, which is used to generate random numbers.

2. Variables

Variables are containers, identified by a unique name, that hold a value.

They are always defined by a type and a name. There are several variable types in C:

So, to declare a variable, we pick one of the types listed above and give it a name. For example, with:

int a;
int b;

we have just declared two integer variables, named a and b. Now we need to initialize them, that is assign them a value:

a = 5;
b = 10;

So in this case we have the integer variable named a holding 5, and the integer variable b holding 10.

Declaration and initialization can also happen at the same time. In fact, the previous examples can be condensed into:

int a = 5;
int b = 10;

Depending on the case, we can decide where and when to declare variables: outside or inside the main, for example. A variable declared outside the main is called global, precisely because it can be used by multiple functions within the same program.

But we won’t dwell on this point, since it has no immediate practical use.

3. Operators

Operators let the various elements inside a program interact. They can be classified into three types:

One fundamental concept to pay attention to, regarding operators, is that a single equals sign = means an assignment, while two equals signs == perform a comparison.

So a = 5 means we assigned the value 5 to the variable a.

If we write a == 5 instead, we are checking whether the variable a has value 5.

4. Input / Output

printf

The statement typically used to print to the screen is printf(), which lets you decide what to print and in which format.

The structure of printf is as follows:

printf("testo", argomento/i);

You can also use format specifiers, a kind of placeholder. They change depending on the type of variable they refer to:

But let’s look at a practical example.

int a = 5;

printf("Il valore di a e': %d", a);

As you can see, after the comma you write the variable the format specifier refers to. When the program runs, 5 will appear in place of the %d (that is, the value of a).

scanf

The statement to read a value entered by the user and store it in a variable is scanf(). The syntax is the same as printf(), including the format specifiers. The only difference is in the arguments: the variable where we want the value to be stored must be preceded by the & symbol. A practical example of printf and scanf at work is the following:

int i;
scanf("%d \n", &i);
printf("%d \n", i);

The scanf will store the integer entered by the user inside the variable i, and then the printf will print it to the screen.

5. Arrays

This name usually scares everyone. Don’t panic! An array is nothing more than an organized collection of objects of the same type. If we picture an array as a box, consider that inside it we can only put similar objects (all int, or all char, and so on).

But what does organized mean? It means you can uniquely identify every object in the array in a systematic way, that is using numeric indexes that, in an array of size N, go from 0 to N-1. Before you fall into despair, let’s look at a practical example:

int vett[10];

This means we declared an array of integers called vett, with size 10. So it contains ten numbered slots (from 0 to 9), each of which holds an integer.

The first time I saw an array and how it works, I asked myself: What the heck are these for?

If you’re asking yourself the same question, know that you’ll find the answer after doing a few exercises on this topic.

If you’re not asking it, wow! You’re Bill Gates or a distant relative of his.

6. Conditional statements

In programming, statements are executed from the first to the last. But what do we do when we need to run one rather than another depending on the context? You set conditions that, when met, execute one piece of code rather than another.

if-else

The if statement lets you check conditions with the following syntax:

if (condizione) {
     istruzione;
}

If the condition is met, the immediately following statement runs. On the contrary, if the condition is false, the statement (or the set of statements) belonging to the if is skipped and execution continues with the following statements, which can be the rest of the program, or an else, that is an alternative statement. For example:

if (condizione) {
     istruzione 1;
} else {
     istruzione 2;
}

You can also use else if, a construct that lets you check more than two different conditions:

if (condizione) {
     istruzione 1;
} else if {
     istruzione 2;
} else {
     istruzione 3;
}

In the solved exercises at the bottom of the article we’ll also see if-else in action.

7. Loops

Now let’s look at the constructs that let you execute statements or blocks of statements repeatedly, until certain conditions are met. Loop statements, like the conditional if-else statements, need certain conditions to be met for the loop to continue or stop. The fundamental loop statements are while, do-while and for.

while

The structure of while is as follows:

while (condizione) {
    istruzione/i;
}

The statement or statements inside the while act on the condition that the while waits to become false in order to exit the loop, otherwise the loop would never end. For example, to print a sequence of digits from 0 to 49, you write:

int a = 0;

while (a != 50) {
    printf("%d ", a);
    a++;
}

where a++ is the increment by 1 that the variable a undergoes until it reaches 50.

do – while

Very similar to while is the do-while, which has the following syntax:

do {
     istruzione/i;
} while (condizione);

Keeping in mind what we said about while, note that this way the statement inside the do-while is executed at least once, regardless of whether the condition specified in the while is true or false. For example, to ask the user a question until they answer correctly, we’ll write:

do {
    printf("Premere 1 per continuare: ");
    scanf("%d", &num);
} while (num !=1);

for

The syntax of for is as follows:

for (inizializzazione; condizione; incremento) {
    istruzione/i;
}

The for is exactly the same as the while, except that it’s more concise and is usually employed when we know in advance the number of iterations to execute. The parameters inside the for must be specified every time and are separated by semicolons. Specifically:

  • The first runs before entering the loop, and initializes a variable. Generally the variable is used as the loop control and keeps track of the number of iterations. Remember that this variable must be declared before the for and initialized inside the for.
  • The second is the condition, which stops the loop when it becomes false.
  • The third parameter is the increment, which runs after each pass of the for; this statement acts on the control variable, increasing (or decreasing) its value.

Let’s take an example with an exercise that counts from zero to one hundred.

int i;

for (i=0; i<=100; i++) {
    printf("%d", i);
}

You should know that arrays and for loops go hand in hand, because a for loop can count a given number of times. This way, using a variable that increases (or decreases) its value on each pass, you can walk through the positions of an array. For example, consider an integer array 100 elements long and say we want to print its contents; we won’t start counting from 1, but from 0, up to ninety-nine (that’s one hundred elements). We’ll use the print statement on the array with the index, incremented each time, taken from the for loop. That is:

int vett[100];

int i;
for (i=0; i<100; i++) {
    printf (“%d”, int_array);
}

Instead, an example of code to fill an array 10 elements long with integers asked as input from the user is the following:

for (i=0; i<10; i++) {
    printf("Inserisci un numero: ");
    scanf("%d", &vett[i]);
}

This way ten numbers will be asked as input and stored in the array, from position 0 to position 9.

8. Final remarks

If we happen to work with character arrays (char), keep in mind that:

1. Each cell of the array corresponds to one letter of the entered word.

2. To avoid problems, it’s best to give char arrays a predefined size. For example, writing

char vett[];

is wrong. It’s better to write it like this:

char vett[10];

3. If we need to know how long the word stored in the array is, I suggest doing it this way:

char vettore[20];
int i, lung;

printf("Inserisci una parola: \n");
scanf("%s", vettore);

lung = strlen(vettore);

for (i=0; i<lung; i++) {
    if (condizione) {
        istruzione;
}

The strlen command, included in the <string.h> library, will measure the length of the word entered by the user. This way the for won’t count the empty slots too.

In this case, if the user enters a 12-character word, the array will have 12 occupied cells and 8 free ones, since its length is 20. So if we didn’t use strlen to measure the number of letters in the entered word, and wrote the for with a generic i < n, the 8 empty cells would be counted too and the program wouldn’t work properly.

9. Solved exercises

Finally, here we are. Below you’ll find solved and working exercises (compiled and tested with the Eclipse IDE) of various kinds.

You’re free to copy them, modify them, print them and throw them in the bin, if that’s what you want to do.

Reversed array

Given an array of length 10, ask the user for the numbers as input and print them first in insertion order and then in reverse

/*
 * ArrayContrario1.c
 *
 *  Created on: 29/gen/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main() {
    int vett[10];
    int i;

    for (i = 0; i < 10; i++) {
        printf("Inserisci un numero: ");
        scanf("%d", &vett);
    }

    printf("\nIl vettore e' il seguente: ");
    for (i = 0; i < 10; i++) {
        printf("%d ", vett);
    }

    printf("\nIl vettore al contrario e' il seguente: ");
    for (i = 9; i >= 0; i--) {
        printf("%d ", vett);
    }
    return 0;
}
Maximum and minimum of an array

Enter 10 numbers as input into an array of length 10. Print the largest and the smallest number in that array.

/*
 * ArrayMaxMin1.c
 *
 *  Created on: 29/gen/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>

int main() {
    int vett[10];
    int i, min;
    int max = 0;

    for (i = 0; i < 10; i++) {
        printf("Inserisci un numero: ");
        scanf("%d", &vett);
    }

    for (i = 0; i < 10; i++) {
        if (max < vett)
            max = vett;
    }
    printf("Il numero piu' grande dell'array e': %d \n", max);

    min = max;
    for (i = 0; i < 10; i++) {
        if (min > vett)
            min = vett;
    }
    printf("Il numero piu' piccolo dell'array e': %d \n", min);

    return 0;
}
Even or odd array

Ask for 10 numbers as input. Check whether the entered numbers are even or odd. Print all the odd ones first, then all the even ones.

/*
 * ArrayPariDispari.c
 *
 *  Created on: 28/gen/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>

int main() {
    int vett[10];
    int i;

    for (i = 0; i < 10; i++) {
        printf("Inserisci un numero: \n");
        scanf("%d", &vett);
    }

    for (i = 0; i < 10; i++) {
        if (vett % 2 != 0) {
            printf("Numero dispari: %d \n", vett);
        }
    }

    for (i = 0; i < 10; i++) {
        if (vett % 2 == 0) {
            printf("Numero pari: %d \n", vett);
        }
    }

    return 0;
}
Even or odd position in an array

Ask for 10 numbers as input. Check whether an even position holds an even number. If so, print “Even”. Do the same with the odd ones. In all other cases print “Not valid”.

/*
 * ArrayPariDispari2.c
 *
 *  Created on: 28/gen/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>

int main() {
    int vett[10];
    int i;

    for (i = 0; i < 10; i++) {
        printf("Inserisci un numero: \n");
        scanf("%d", &vett);
    }

    for (i = 0; i < 10; i++) {
        if (i % 2 == 0 && vett % 2 == 0) {
            printf("Pari \n");
        } else if (i % 2 != 0 && vett % 2 != 0) {
            printf("Dispari \n");
        } else if (i % 2 == 0 && vett % 2 != 0) {
            printf("Non va bene \n");
        } else if (i % 2 != 0 && vett % 2 == 0) {
            printf("Non va bene \n");
        }
    }
    return 0;
}
Adding the elements of an array

Add together all the elements of two arrays of size 5.

/*
 * ArraySomma.c
 *
 *  Created on: 02/feb/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>

int main() {
    int vett1[5];
    int vett2[5];
    int vettsomma[5];
    int i;

    for (i = 0; i < 5; i++) {
        printf("\nInserisci un numero: ");
        scanf("%d", &vett1);
    }

    for (i = 0; i < 5; i++) {
        printf("\nInserisci un numero: ");
        scanf("%d", &vett2);
    }

    for (i = 0; i < 5; i++) {
        vettsomma = vett1 + vett2;
    }
    printf("\nLa somma dei due vettori e':");

    for (i = 0; i < 5; i++) {
        printf("%d ", vettsomma);
    }

    return 0;
}
Checking whether the elements of an integer array and a character array are all equal

Ask for five numbers as input and save them in an array of size 5. Ask for a word as input and save it in a char array of size 10. Check whether the first one has all equal elements. Do the same for the second one.

/*
 * ArrayUguali.c
 *
 *  Created on: 30/gen/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
    int vett[5];
    char vett1[10];
    int i, lung;
    int uguale = 1;
    int uguale1 = 1;

    for (i = 0; i < 5; i++) {
        printf("Inserisci un numero: ");
        scanf("%d", &vett);
    }

    for (i = 0; i < 4 && uguale == 1; i++) {
        if (vett == vett)
            uguale = 1;
        else {
            uguale = 0;
        }
    }

    if (uguale == 1) {
        printf("Il vettore ha tutti gli elementi uguali");
    } else {
        printf("Il vettore non ha tutti gli elementi uguali");
    }

    printf("\nInserisci una parola: ");
    scanf("%s", vett1);

    lung = strlen(vett1);

    for (i = 0; i < lung - 1; i++) {
        if (vett1 == vett1)
            uguale1 = 1;
        else {
            uguale1 = 0;
        }
    }

    if (uguale1 == 1) {
        printf("Il vettore char ha tutti gli elementi uguali");
    } else {
        printf("Il vettore char non ha tutti gli elementi uguali");
    }

    return 0;
}
Checking whether an integer array has two equal consecutive elements

Ask for ten numbers as input. Sort the array in ascending order and check whether there are two equal consecutive numbers.

/*
 * EsercizioEsame3Febb.c
 *
 *  Created on: 04/feb/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>

int main() {
    int vett[10];
    int i, k, temp;

    for (i = 0; i < 10; i++) {
        printf("Inserisci un numero: ");
        scanf("%d", &vett);
    }

    for (i = 0; i < 10 - 1; i++) {
        for (k = 0; k < 10 - 1; k++) {
            if (vett > vett) {
                temp = vett;
                vett = vett;
                vett = temp;
            }
        }
    }

    for (i = 0; i < 10 - 1; i++) {
        if (vett == vett) {
            printf("\nHo trovato due %d consecutivi.", vett);
        }
    }
    return 0;
}
Average calculation

Ask the user how many numbers they want to enter, then calculate the average of the entered numbers.

/*
 * Media.c
 *
 *  Created on: 02/feb/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>

int main() {
    int i, n;
    float somma = 0;
    float media;

    printf("Quanti numeri vuoi inserire? ");
    scanf("%d", &n);

    float vett;

    for (i = 0; i < n; i++) {
        printf("\nInserisci un numero: ");
        scanf("%f", &vett);
    }

    for (i = 0; i < n; i++) {
        somma = somma + vett;
    }

    media = somma / n;

    printf("\nLa media dei numeri inseriti e': %f", media);

    return 0;
}
Factorial calculation

Ask the user for a number as input, then calculate its factorial.

/*
 * Fattoriale.c
 *
 *  Created on: 19/set/2014
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>

int main() {

    int n, m;
    int fattoriale = 1;

    printf("Inserisci un numero: ");
    scanf("%d", &n);

    for (m = n; m > 1; m--) {
        fattoriale = fattoriale * m;
    }

    printf("Il fattoriale di %d e' %d\n", n, fattoriale);

    return 0;
}
Palindrome word

Ask the user for a word and check whether it is a palindrome (that is, whether it reads the same from right to left as from left to right).

/*
 * Palindroma.c
 *
 *  Created on: 28/gen/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
    char vett[15];
    int i, k, lung;
    int pal = 0;

    printf("Inserisci una parola: \n");
    scanf("%s", vett);

    lung = strlen(vett);

    for (i = 0, k = lung - 1; i < lung / 2 && pal == 0; i++, k--) {
        if (vett == vett)
            pal = 1;
    }

    if (pal == 1) {
        printf("\nLa parola %s e' palindroma.", vett);
    } else
        printf("\nLa parola %s non e' palindroma", vett);
    return 0;
}
Vowel and consonant count

Create an array of characters. Ask the user for a word as input and count its vowels and consonants. Then, if any, turn the vowels from lowercase to uppercase.

/*
 * Vocali1.c
 *
 *  Created on: 27/gen/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
    char vettore[20];
    int vocali = 0;
    int consonanti = 0;
    int i, lung;

    printf("Inserisci una parola: \n");
    scanf("%s", vettore);

    lung = strlen(vettore);

    for (i = 0; i < lung; i++) {
        if (vettore == 'a' || vettore == 'e' || vettore == 'i'
                || vettore == 'o' || vettore == 'u')
            vocali++;
        else
            consonanti++;
    }

    for (i = 0; i < lung; i++) {
        if (vettore == 'a')
            vettore = 'A';
        else if (vettore == 'e')
            vettore = 'E';
        else if (vettore == 'i')
            vettore = 'I';
        else if (vettore == 'o')
            vettore = 'O';
        else if (vettore == 'u')
            vettore = 'U';
    }

    printf("Il numero delle vocali e': %d \n", vocali);
    printf("Il numero delle consonanti e': %d \n", consonanti);
    printf("La parola con le vocali maiuscole e' %s", vettore);

    return 0;
}
Letter present in the sentence

Enter a word or sentence and count how many times its first letter appears in it.

/*
 * StringaInput1.c
 *
 *  Created on: 29/gen/2015
 *  Author: Fabio Biocchetti
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
    char parola[20];
    int i, lung;
    int count;

    printf("\nInserisci una parola o frase: ");
    scanf("%s", parola);

    lung = strlen(parola);

    for (i = 0; i < lung; i++) {
        if (parola[0] == parola) {
            count++;
        }
    }
    printf("\nLa prima lettera e' presente %d volte.", count);

    return 0;
}