🆘C Tutorial
The main difference between C and C++ is that C++ support classes and objects, while C does not
Quick syntax review of a hello world:
#include <stdio.h>
is a header file library that lets us work with input and output functions, such as printf()
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
printf()
is a function used to output/print text to the screen.
Note that: Every C statement ends with a semicolon ;
To insert a new line, you can use the \n character:
Single-line comments start with two forward slashes (//
).
Multi-line comments start with /*
and ends with */
.
C Variables
different types of variables in C:
int
- stores integers (whole numbers), without decimals, such as123
or-123
float
- stores floating point numbers, with decimals, such as19.99
or-19.99
char
- stores single characters, such as'a'
or'B'
. Characters are surrounded by single quotes
To create a variable, we must specify the type and assign it a value:
Variable called theVarInt, type int, and it's value is 24:
or we can assign value later:
if we wanted to print out the value assigned to theVarInt it would not be a printf(theVarInt);
C Format Specifiers
Format specifiers are used together with the printf()
function to tell the compiler what type of data the variable is storing.
int would use the format specifier %d
surrounded by double quotes (""
), inside the printf()
function:
(%c
for char
and %f
for float)
To combine both text and a variable, separate them with a comma inside the printf()
function:
And to print different type in a same printf:
Change Variable Values
If you assign a new value to an existing variable, it will overwrite the previous value:
you can also assign a value using another variable:
Add Variables Together
Using the + operator:
Declare Multiple Variables
if we want to declare multiple (same type) variable, we can do it in one line with comma separated values:
or same value:
Real life example: calculate area of rectangle:
C Character Data Types
But we can also use ASCII to print out char values:
To store multiple characters or words, we need to use strings:
Numeric Types
Use int
when you need to store a whole number without decimals, like 35 or 1000, and float
or double
when you need a floating point number
The precision of float
is six or seven decimal digits, while double
variables have a precision of about 15 digits. Therefore, it is often safer to use double
for most calculations - but note that it takes up twice as much memory as float
(8 bytes vs. 4 bytes).
If we want to be more precise with our outputs, we can use a dot (.
) followed by a number that specifies how many digits that should be shown after the decimal point:
Get the Memory Size
If we want to print out the memory size of a var → we need to use the sizeof
operator.
it's better to use the %lu
format specifier to print the result:
real-life example of using different data types, to calculate and output the total cost of a number of items:
Type Conversion
if we need to use 2 int but the result is a float (5/2=2.5), we can use implicit conversion:
if you assign an int
value to a float
type:
and the other way around:
The conversion is tricky:
the result is 2 and not 2.5 because we assigned the value of sum with 2 int, we need to manually convert the integer values to floating-point values
or
Real life example
create a program to calculate the percentage of a user's score in relation to the maximum score in a game:
C Constants
If we do not want anyone to be able to change a variable we can use the const
keyword.
It will make the variable unchangeable and read-only:
When you declare a constant variable, it must be assigned with a value
C Operators
Operators are used to perform operations on variables and values.
you can have arithmetic operators:
assignment operators:
Comparisons operators:
Logical operators:
C Booleans
Good to know we must import booleans:
A boolean variable is declared with the bool
keyword and can only take the values true
or false
It's good to know that boolean values are returned as integers (1=true, 0=false)
So to print it we must use %d
You can use bool
to compare values:
or 2 bool variables:
Real life example:
Output "Old enough to vote!" if myAge
is greater than or equal to 18
. Otherwise output "Not old enough to vote.":
C If ... Else
Combined to the conditions we just saw, we can add conditional statements:
Short Hand If...Else (Ternary Operator)
As a one-liner enjoyer it's good to know that this exists:
to replace simple if else statements, we can use this syntax:
Example:
turns into:
Real life example:
use if..else
to "open a door" if the user enters the correct code
C Switch
The switch
statement selects one of many code blocks to be executed:
Quick little switch condition to see the mood today:
if the mood variable has some chances of not being in our switch case, we can add a default case that specifies some code to run if there is no case match:
C While Loop
Loops can execute a block of code as long as a specified condition is reached.
Another variable of the while loop is the do/while loop:
C For Loop
If we know how many occurrences we want to have, we can use the for loop that takes 3 expressions
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.
We can also play with nested loops, but it will multiply by the number of occurrences of the first loop:
C Break and Continue
The break
statement can also be used to jump out of a loop.
The continue
statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
C Arrays
C Strings
here is the syntax for a string in C:
for the printf output we need the format specifier %s
for strings and %c
format specifier to print a single character.
If we wanted to modify a single character in a string, we would refer to the index like in an array since strings are quite litterally char arrays, and we would use single quotes for the assignment:
You can use the for loop just like any other way we learnt earlier:
another interestig way of printing out strings is to use {} and single quotes:
and to finish the size of a string is pretty straightforward:
If we want to print out " or ' or \ (special chars)in our strings without it breaking the function we need to put escape characters:
String functions:
We can perform some interesting stuff on strings if we include <string.h>
header file in our program ->
first we need to know the difference between strlen() and sizeof()
sizeof
and strlen
behaves differently, as sizeof
also includes the \0
character when counting:
and sizeof() will return the memory size in bytes and not the length as we understand it:
If we want to concatenate strings, we can use the strcat() function but we need to be aware of buffer overflow:
In C, when you declare an array of characters like char string1[12]
, you're allocating space for 12 characters, including the null terminator '\0'
. However, when you initialize string1
with "hello"
, it already consumes 6 characters (5 for "hello" and 1 for '\0'
). So, string1
has only 6 characters left before reaching its maximum capacity.
Copy strings:
we need to use the strcpy() function if we want to assign the value of one string to another
notice how while using strcpy we put the var that we want to assign something to in first
Compare strings:
If we want to compare 2 strings, we need to use the strcmp() function:
the output is either ->
0 == equal
!0 == not equal
C User Input
To capture user input, we need to use the scanf() function:
Like this:
and for multiple inputs:
scanf() considers space chars as escape chars so if you were to write your name "John Doe" it would ouput only John
Use the scanf()
function to get a single word as input, and use fgets()
for multiple words.
fgets() takes the following parameters: the name of the string variable, sizeof
(string_name), and stdin
:
C Memory Address
To access memory addresses in C you have to put a & before the variable:
the memory address is in hexadecimal form
C Pointers
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.
you can dereference a pointer by calling it with a * character before ->
You can also declare pointers thes 2 ways in C:
Pointers & Arrays
let's say we have the following array:
Note that the last number of each of the elements' memory address is different, with an addition of 4.
It is because the size of an int
type is typically 4 bytes ->
In c, the name of the array is a direct pointer to the first element of the array
The memory address of the first element is the same as the name of the array:
So if we want to access to an element of the array through a pointer, we have to take the array (which points to the first element) and add 1,2,3... ->
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
We first define the data type (like int
) and specify the name of the array followed by
square brackets []
To access an array element, refer to its index number:
Now if we wanted to change the value assigned to a array value:
And finally, we could use the for loop to iterate through an array:
Now if we wanted to know the size of an array:
the output is equal to 20 because the output refers to the size of bytes and since an int is usually equal to 4 bytes, 4x5=20
if we wanted to output the size as we think of it (the number of variables in the array):
sizeof(myNumbers)
gives the total size in bytes of themyNumbers
array. SincemyNumbers
is an array of integers (int
), and there are five integers in the array, the total size would be5 * sizeof(int)
.sizeof(myNumbers[0])
gives the size in bytes of the first element of themyNumbers
array, which is an integer (int
).By dividing the total size of the array (
sizeof(myNumbers)
) by the size of a single element (sizeof(myNumbers[0])
), we get the number of elements in the array.
We can make our for loop better by specifying the length of our array in the for loop:
A real life example of a program that calculates the average of different users:
another useful thing good to know is multi dimensional arrays:
lets create a 2D array:
To access the values of the array, you first specify the which row you want then which column:
if you want to change the value of an element in the array it's the same, you first choose the row, then the element in the row:
Last updated