Introduction

What is C?

C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. The main reason for its popularity is because it is a fundamental language in the field of computer science. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Why Learn C?

  • It is one of the most popular programming languages in the world.
  • If you know C, you will have no problem learning other popular programming languages such as Java, Python, C++, C#, etc, as the syntax is similar.
  • C is very fast, compared to other programming languages, like Java and Python.
  • C is very versatile; it can be used in both applications and technologies.

Difference between C and C++

  • C++ was developed as an extension of C, and both languages have almost the same syntax
  • The main difference between C and C++ is that C++ support classes and objects, while C does not
C Syntax

Syntax

To get started with writing C, open the Scratchpad and write your first "Hello world" C code:

Example

#include <stdio.h> int main() { printf("Hello World!"); return 0; }

Example explained

Line 1:#include <stdio.h> is a header file library that lets us work with input and output functions, such as printf() (used in line 4). Header files add functionality to C programs.

Line 2: A blank line. C ignores white space. But we use it to make the code more readable.

Line 3: Another thing that always appear in a C program is main(). This is called a function. Any code inside its curly brackets {} will be executed.

Line 4: printf() is a function used to output/print text to the screen. In our example, it will output "Hello World!".

Line 5: return 0 ends the main() function.

Line 6: Do not forget to add the closing curly bracket } to actually end the main function.

C Statements

C Statements

A computer program is a list of "instructions" to be "executed" by a computer. In a programming language, these programming instructions are called statements. The following statement "instructs" the compiler to print the text "Hello World" to the screen:

Example

printf("Hello World!");

It is important that you end the statement with a semicolon ; If you forget the semicolon (;), an error will occur and the program will not run:

Example

printf("Hello World!") error: expected ';' before 'return'

Many Statements

Most C programs contain many statements.

The statements are executed, one by one, in the same order as they are written:

Example

printf("Hello World!"); printf("Have a good day!"); return 0

Example explained

From the example above, we have three statements:

  • printf("Hello World!");
  • printf("Have a good day!");
  • return 0;

The first statement is executed first (print "Hello World!" to the screen).
Then the second statement is executed (print "Have a good day!" to the screen).
And at last, the third statement is executed (end the C program successfully).

C Output

Output (Print Text)

To output values or print text in C, you can use the printf() function:

Example

#include <stdio.h> int main() { printf("Hello World!"); return 0; }

Double Quotes

When you are working with text, it must be wrapped inside double quotations marks "".

If you forget the double quotes, an error occurs:

Example

printf("This sentence will work!"); printf(This sentence will produce an error.);

Many printf() Functions

You can use as many printf() functions as you want. However, note that it does not insert a new line at the end of the output:

Example

#include <stdio.h> int main() { printf("Hello World!"); printf("I am learning C."); printf("And it is awesome!"); return 0; }
C Comments

Comments in C

Comments can be used to explain code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

Comments can be singled-lined or multi-lined.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between (//) and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment printf("Hello World!");

This example uses a single-line comment at the end of a line of code:

Example

printf("Hello World!");// This is a comment

C Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example

/* The code below will print the words Hello World! to the screen, and it is amazing */ printf("Hello World!");
C Variables

Variables are containers for storing data values, like numbers and characters.

In C, there are different types of variables (defined with different keywords), for example:

  • int - stores integers (whole numbers), without decimals, such as 123 or -123.
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99.
  • char - stores single characters, such as 'a' or 'B'. Characters are surrounded by single quotes.

Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

Syntax

type variableName = value;

Where type is one of C types (such as int), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign a value to the variable.

So, to create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign the value 15 to it:

int myNum = 15;

You can also declare a variable without assigning the value, and assign the value later:

Example

// Declare a variable int myNum; // Assign a value to the variable myNum = 15;

Output Variables

You learned from the output chapter that you can output values/print text with the printf() function:

Example

printf("Hello World!");

In many other programming languages (like Python, Java, and C++), you would normally use a print function to display the value of a variable. However, this is not possible in C:

Example

int myNum = 15; printf(myNum); // Nothing happens

Format Specifiers

Format specifiers are used together with the printf() function to tell the compiler what type of data the variable is storing. It is basically a placeholder for the variable value.

A format specifier starts with a percentage sign %code-inline, followed by a character.

For example, to output the value of an int variable, use the format specifier %d surrounded by double quotes (""), inside the printf() function:

Example

int myNum = 15; printf("%d", myNum); // Outputs 15

To print other types, use %c for char and %f for float:

Example

// Create variables int myNum = 15; // Integer (whole number) float myFloatNum = 5.99; // Floating point number char myLetter = 'D'; // Character // Print variables printf("%d\n", myNum); printf("%f\n", myFloatNum); printf("%c\n", myLetter);

To combine both text and a variable, separate them with a comma inside the printf() function:

Example

int myNum = 15; printf("My favorite number is: %d", myNum);

To print different types in a single printf() function, you can use the following:

Example

int myNum = 15; char myLetter = 'D'; printf("My number is %d and my letter is %c", myNum, myLetter);
C Data Types

Data Types

As explained in the Variables chapter, a variable in C must be a specified data type, and you must use a format specifier inside the printf() function to display it:

Example

// Create variables int myNum = 5; // Integer (whole number) float myFloatNum = 5.99; // Floating point number char myLetter = 'D'; // Character // Print variables printf("%d\n", myNum); printf("%f\n", myFloatNum); printf("%c\n", myLetter);

Basic Data Types

The data type specifies the size and type of information the variable will store.

In this tutorial, we will focus on the most basic ones:

DataType Size Description Example
int 2 or 4 bytes Stores whole numbers, without decimals 1
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7 decimal digits 1.99
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits 1.99
char 1 byte Stores a single character/letter/number, or ASCII values 'A'

Basic Format Specifiers

There are different format specifiers for each data type. Here are some of them:

Format Specifier Data Type
%d or %i int
%f or %F float
%lf double
%c char
%s Used for strings (text), which you will learn more about in a later chapter
C Constants

Constants

If you don't want others (or yourself) to change existing variable values, you can use the const keyword.

This will declare the variable as "constant", which means unchangeable and read-only:

Example

const int myNum = 15; // myNum will always be 15 myNum = 10; // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that are unlikely to change:

Example

const int minutesPerHour = 60; const float PI = 3.14;

Good Practice

Another thing about constant variables, is that it is considered good practice to declare them with uppercase.

It is not required, but useful for code readability and common for C programmers:

Example

const int BIRTHYEAR = 1980;
C Operators

Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example

int myNum = 100 + 50;

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

Example

int sum1 = 100 + 50; // 150 (100 + 50) int sum2 = sum1 + 250; // 400 (150 + 250) int sum3 = sum2 + sum2; // 800 (400 + 400)

C divides the operators into the following groups:

  • Arithmetic operators
  • Assingment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example
+ Addition Adds together two values x + y
- Sutraction Substract one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division reminder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example

intx = 10;

The addition assignment operator (+=) adds a value to a variable:

Example

intx = 10; x += 5;

A list of all assignment operators:

Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x/3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x|3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

Example

int x = 5; int y = 3; printf("%d", x > y); // returns 1 (true) because 5 is greater than 3

A list of all comparison operators:

Operator Name Description Example
== Equal to x == y Returns 1 if the values are equal
!= Not equal x != y Returns 1 if the values are not equal
> Greater than x > y Returns 1 if the first value is greater than the second value
< Less than x < y Returns 1 if the first value is greater than the second value
>= Greater than or equal to x >= y Returns 1 if the first value is greater than, or equal to, the second value
<= Less than or equal to x <= y Returns 1 if the first value is less than, or equal to, the second value

Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example
&& Logical and x < 5 && x < 10 Returns 1 if both statements are true
|| Logical or x < 5 || x < 4 Returns 1 if one of the statements is true
! Logical not !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1
C If Else

Conditions and If Statements

You have already learned that C supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to: a == b
  • Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of code to be executed if a condition is true.

Syntax

if (condition) { // block of code to be executed if the condition is true }

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:

Example

if (20 > 18) { printf("20 is greater than 18") }

Example explained

In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false }

Example

int time = 20; if (time < 18) { printf(Good day.""); } else { printf("Good evening.") } // Outputs "Good evening."

Example explained

In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day".

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }

Example

int time = 22; if (time < 10) { printf("Good morning."); } else if (time < 20) { printf("Good day."); } else { printf("Good evening."); } // Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is also false, so we move on to the else condition since condition1 and condition2 is both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

C Switch

Switch Statement

Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

Syntax

switch (expression) { case x: // code block break; case y: // code block break; default: // code block }

This is how it works:

  • The switch expression is evaluated once
  • The value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed
  • The break statement breaks out of the switch block and stops the execution
  • The default statement is optional, and specifies some code to run if there is no case match

The example below uses the weekday number to calculate the weekday name:

Example

int day = 4; switch (day) { case 1: printf("Monday"); break; case 2: printf("Tuesday"); break; case 3: printf("Wednesday"); break; case 4: printf("Thursday"); break; case 5: printf("Friday"); break; case 6: printf("Saturday"); break; case 7: printf("Sunday"); break; } // Outputs "Thursday" (day 4)

The break Keyword

When C reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

The default Keyword

The default keyword specifies some code to run if there is no case match:

Example

int day = 4; switch (day) { case 6: printf("Today is Saturday"); break; case 7: printf("Today is Sunday") break; default: printf("Looking forward to the Weekend"); } // Outputs "Looking forward to the Weekend"
C While Loop

Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax

while (condition) { // code block to be executed }

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Example

int i = 0; while (i < 5) { printf("%d\n", i); i++; }

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do { // code block to be executed } while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Example

int i = 0; do { printf("%d\n" i); i++; } while (i < 5);
C For Loop

For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Syntax

for (expression 1; expression 2; expression 3) { // code block to be executed }

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example

int i; for (i = 0; i < 5; i++) { printf("%d\n" i); }

Example explained

Expression 1 sets a variable before the loop starts (int i = 0).

Expression 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.

Expression 3 increases a value (i++) each time the code block in the loop has been executed.

Nested Loops

It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

int i, j; // Outer loop for (i = 1; i <= 2; ++i) { printf("Outer: %d\n" i); // Executes 2 times // Inner loop for (j = 1; j <= 3; ++j) { printf(" Inner: %d\n" j); // Executes 6 times (2 * 3) } }
C Arrays

Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To create an array, define the data type (like int) and specify the name of the array followed by square brackets [].

To insert values to it, use a comma-separated list, inside curly braces:

Syntax

int myNumbers[] = {25, 50, 75, 100};

We have now created a variable that holds an array of four integers.

Access the Elements of an Array

To access an array element, refer to its index number.

Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

This statement accesses the value of the first element [0] in myNumbers:

Example

int myNumbers[] = {25, 50, 75, 100}; printf("%d", myNumbers[0]); // Outputs 25

Change an Array Element

To change the value of a specific element, refer to the index number:

Syntax

myNumbers[0] = 33;

Example

int myNumbers[] = {25, 50, 75, 100}; myNumbers[0] = 33; printf("%d", myNumbers[0]); // Now outputs 33 instead of 25

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

Example

int myNumbers[] = {25, 50, 75, 100}; int i; for (i = 0; i < 4; i++) { printf("%d\n", myNumbers[i]); }

Set Array Size

Another common way to create arrays, is to specify the size of the array, and add elements later:

Example

// Declare an array of four integers: int myNumbers[4]; // Add elements myNumbers[0] = 25; myNumbers[1] = 50; myNumbers[2] = 75; myNumbers[3] = 100;

Using this method, you should know the number of array elements in advance, in order for the program to store enough memory.

You are not able to change the size of the array after creation.

Get Array Size or Length

To get the size of an array, you can use the sizeof operator:

Example

int myNumbers[] = {25, 50, 75, 100}; printf("%lu" sizeof(myNumbers)); // Prints 20

Why did the result show 20 instead of 5, when the array contains 5 elements?

- It is because the sizeof operator returns the sizeof a type in bytes.

You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.

Knowing the memory size of an array is great when you are working with larger programs that require good memory management.

But when you just want to find out how many elements an array has, you can use the following formula (which divides the size of the array by the size of one array element):

Example

int myNumbers[] = {25, 50, 75, 100}; int length = sizeof(myNumbers) / sizeof(myNumbers[0]); printf("%d", length); // Prints 5

Making Better Loops

In the array loops section in the previous chapter, we wrote the size of the array in the loop condition (i < 4). This is not ideal, since it will only work for arrays of a specified size.

However, by using the sizeof formula from the example above, we can now make loops that work for arrays of any size, which is more sustainable.

Instead of writing:

Example

int myNumbers[] = {25, 50, 75, 100}; int i; for (i = 0; i < 4; i++) { printf("%d\n", myNumbers[i]); }

It is better to write:

Example

int myNumbers[] = {25, 50, 75, 100}; int length = sizeof(myNumbers) / sizeof(myNumbers[0]); int i; for (i = 0; i < length; i++) { printf("%d\n", myNumbers[i]); }
C Users Input

User Input

You have already learned that printf() is used to output values in C.

To get user input, you can use the scanf() function:

Example

// Create an integer variable that will store the number we get from the user int myNum; // Ask the user to type a number printf("Type a number: \n"); // Get and save the number the user types scanf("%d" , &myNum); // Output the number the user typed printf("Your number is: %d", myNum);

The scanf() function takes two arguments: the format specifier of the variable (%d in the example above) and the reference operator (&myNum), which stores the memory address of the variable.

Multiple Inputs

The scanf() function also allow multiple inputs (an integer and a character in the following example):

Example

// Create an int and a char variable int myNum; char myChar; // Ask the user to type a number AND a character printf("Type a number AND a character and press enter: \n") // Get and save the number AND character the user types scanf("%d %c", &myNum, &myChar); // Print the number printf("Your number is: %d\n", myNum); // Print the character printf("Your character is: %c\n", myChar);

Take String Input

You can also get a string entered by the user:

Example

// Create a string char firstName[30]; // Ask the user to input some text printf("Enter your first name: \n"); // Get and save the text scanf("%s", firstName); // Output the text printf("Hello %s", firstName);

Note: When working with strings in scanf(), you must specify the size of the string/array (we used a very high number, 30 in our example, but atleast then we are certain it will store enough characters for the first name), and you don't have to use the reference operator (&).

However, the scanf() function has some limitations: it considers space (whitespace, tabs, etc) as a terminating character, which means that it can only display a single word (even if you type many words). For example:

Example

char fullName[30]; printf("Type your full name: \n"); scanf("%s", &fullName); printf("Hello %s", fullName); // Type your full name: John Doe // Hello John

From the example above, you would expect the program to print "John Doe", but it only prints "John".

That's why, when working with strings, we often use the fgets() function to read a line of text. Note that you must include the following arguments: the name of the string variable, sizeof(string_name), and stdin:

Example

char fullName[30]; printf("Type your full name: \n"); fgets(fullName, sizeof(fullName), stdin); printf("Hello %s", fullName); // Type your full name: John Doe // Hello John Doe

Use the scanf() function to get a single word as input, and use fgets() for multiple words.

C Pointers

Creating Pointers

You learned from the previous chapter, that we can get the memory address of a variable with the reference operator &:

Example

int myAge = 43; // an int variable printf("%d", myAge); // Outputs the value of myAge (43) printf("%p", &myAge); // Outputs the memory address of myAge (0x7ffe5367e044)

A pointer is a variable that stores the memory address of another variable as its value.

A pointer variable points to a data type (like int) of the same type, and is created with the * operator.

The address of the variable you are working with is assigned to the pointer:

Example

int myAge = 43; // An int variable int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge // Output the value of myAge (43) printf("%d\n", myAge); // Output the memory address of myAge (0x7ffe5367e044) printf("%p\n", &myAge); // Output the memory address of myAge with the pointer (0x7ffe5367e044) printf("%p\n", ptr);

Example explained

Create a pointer variable with the name ptr, that points to an int variable (myAge). Note that the type of the pointer has to match the type of the variable you're working with (int in our example).

Use the & operator to store the memory address of the myAge variable, and assign it to the pointer.

Now, ptr holds the value of myAge's memory address.

Dereference

In the example above, we used the pointer variable to get the memory address of a variable (used together with the & reference operator).

You can also get the value of the variable the pointer points to, by using the * operator (the dereference operator):

Example

int myAge = 43; // Variable declaration int* ptr = &myAge; // Pointer declaration // Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044) printf("%p\n", ptr); // Dereference: Output the value of myAge with the pointer (43) printf("%d\n", *ptr);

Note that the * sign can be confusing here, as it does two different things in our code:

  • When used in declaration (int* ptr), it creates a pointer variable.
  • When not used in declaration, it act as a dereference operator.

Good To Know: There are two ways to declare pointer variables in C:

int* myNum; int *myNum;

Notes on Pointers

Pointers are one of the things that make C stand out from other programming languages, like Python and Java.

They are important in C, because they allow us to manipulate the data in the computer's memory. This can reduce the code and improve the performance. If you are familiar with data structures like lists, trees and graphs, you should know that pointers are especially useful for implementing those. And sometimes you even have to use pointers, for example when working with files.

But be careful; pointers must be handled with care, since it is possible to damage data stored in other memory addresses.