C Introduction
C Introduction
What is C?
C is a general-purpose programming language created by Dennis Ritchie at
the Bell Laboratories in 1972.
Why Learn C?
It is one of the most popular programming language 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
Get Started
C Get Started
Get Started With C
To start using C, you need two things:
C Syntax
Syntax
You have already seen the following code a couple of times in the first
chapters. Let's break it down to understand it better:
Example
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
Try it Yourself »
Example explained
Don't worry if you don't understand how #include <stdio.h> works. Just
think of it as something that (almost) always appears in your program.
Line 2: A blank line. C ignores white space. But we use it to make the
code more readable.
Note: The body of int main() could also been written as:
int main(){printf("Hello World!");return 0;}
Example
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
Try it Yourself »
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.");
return 0;
}
Try it Yourself »
C New Lines
New Lines
To insert a new line, you can use the \n character:
Example
#include <stdio.h>
int main() {
printf("Hello World!\n");
printf("I am learning C.");
return 0;
}
Try it Yourself »
You can also output multiple lines with a single printf() function. However,
this could make the code harder to read:
Example
#include <stdio.h>
int main() {
printf("Hello World!\nI am learning C.\nAnd it is awesome!");
return 0;
}
Try it Yourself »
Tip: Two \n characters after each other will create a blank line:
Example
#include <stdio.h>
int main() {
printf("Hello World!\n\n");
printf("I am learning C.");
return 0;
}
Try it Yourself »
What is \n exactly?
The newline character (\n) is called an escape sequence, and it forces the
cursor to change its position to the beginning of the next line on the screen.
This results in a new line.
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.
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).
Example
// This is a comment
printf("Hello World!");
Try it Yourself »
Example
printf("Hello World!"); // This is a comment
Try it Yourself »
C Multi-line Comments
Multi-line comments start with /* and ends with */.
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
printf("Hello World!");
Try it Yourself »
Good to know: Before version C99 (released in 1999), you could only use
multi-line comments in C.
C Variables
Variables are containers for storing data values, like numbers and
characters.
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:
You can also declare a variable without assigning the value, and assign the
value later:
Example
// Declare a variable
int myNum;
Output Variables
You learned from the output chapter that you can output values/print text
with the printf() function:
Example
printf("Hello World!");
Try it Yourself »
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
Try it Yourself »
To output variables in C, you must get familiar with something called "format
specifiers".
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.
For example, to output the value of an int variable, you must use the format
specifier %d or %i surrounded by double quotes, inside the printf() function:
Example
int myNum = 15;
printf("%d", myNum); // Outputs 15
Try it Yourself »
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);
Try it Yourself »
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);
Try it Yourself »
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);
Try it Yourself »
You will learn more about Data Types in the next chapter.
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
Try it Yourself »
Example
int myNum = 15;
Try it Yourself »
Example
// Create a variable and assign the value 15 to it
int myNum = 15;
Example
int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);
Try it Yourself »
Example
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
Try it Yourself »
You can also assign the same value to multiple variables of the same type:
Example
int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);
Try it Yourself »
C Variable Names
All C variables must be identified with unique names.
Example
// Good
int minutesPerHour = 60;
Real-Life Example
Often in our examples, we simplify variable names to match their data type
(myInt or myNum for int types, myChar for char types etc). This is done to
avoid confusion.
However, if you want a real-life example on how variables can be used, take
a look at the following, where we have made a program that stores different
data of a college student:
Example
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';
// Print variables
printf("Student id: %d\n", studentID);
printf("Student age: %d\n", studentAge);
printf("Student fee: %f\n", studentFee);
printf("Student grade: %c", studentGrade);
Try it Yourself »
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);
Try it Yourself »
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7 decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits
char 1 byte Stores a single character/letter/number, or ASCII values
%d or %i int
%f float
%lf double
%c char
%s Used for strings (text), which you will learn more about in a later chapter
Example
float myFloatNum = 3.5;
double myDoubleNum = 19.99;
If you want to remove the extra zeros (set decimal precision), you can use a
dot (.) followed by a number that specifies how many digits that should be
shown after the decimal point:
Example
float myFloatNum = 3.5;
Try it Yourself »
C Type Conversion
Type Conversion
Sometimes, you have to convert the value of one data type to another type.
This is known as type conversion.
For example, if you try to divide two integers, 5 by 2, you would expect the
result to be 2.5. But since we are working with integers (and not floating-
point values), the following example will just output 2:
Example
int x = 5;
int y = 2;
int sum = 5 / 2;
To get the right result, you need to know how type conversion works.
Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a
value of one type to another.
Example
// Automatic conversion: int to float
float myFloat = 9;
Try it Yourself »
As you can see, the compiler automatically converts the int value 9 to a float
value of 9.000000.
This can be risky, as you might lose control over specific values in certain
situations.
Example
// Automatic conversion: float to int
int myInt = 9.99;
printf("%d", myInt); // 9
Try it Yourself »
As another example, if you divide two integers: 5 by 2, you know that the
sum is 2.5. And as you know from the beginning of this page, if you store the
sum as an integer, the result will only display the number 2. Therefore, it
would be better to store the sum as a float or a double, right?
Example
float sum = 5 / 2;
Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in
front of the value.
Considering our problem from the example above, we can now get the right
result:
Example
// Manual conversion: int to float
float sum = (float) 5 / 2;
Example
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
And since you learned about "decimal precision" in the previous chapter, you
could make the output even cleaner by removing the extra zeros (if you
like):
Example
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
Try it Yourself »
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;
Try it Yourself »
Notes On Constants
When you declare a constant variable, it must be assigned with a value:
Example
Like this:
Try it Yourself »
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;
Try it Yourself »
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;
Try it Yourself »
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)
Try it Yourself »
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description
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
int x = 10;
Try it Yourself »
+= x += 3 x=x+3 Try it »
-= x -= 3 x=x-3 Try it »
*= x *= 3 x=x*3 Try it »
/= x /= 3 x=x/3 Try it »
%= x %= 3 x=x%3 Try it »
|= x |= 3 x=x|3 Try it »
^= x ^= 3 x=x^3 Try it »
>>= x >>= 3 x = x >> 3 Try it »
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.
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
Try it Yourself »
== Equal to x == y
!= Not equal x != y
Logical Operators
You can also test for true or false values with logical operators.
&& Logical and Returns true if both statements are true x < 5 && x < 10 Try it »
|| Logical or Returns true if one of the statements is true x < 5 || x < 4 Try it »
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10) Try it »
Size of Operator
The memory size (in bytes) of a data type or a variable can be found with
the sizeof operator:
Example
int myInt;
float myFloat;
double myDouble;
char myChar;
printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));
Try it Yourself »
Note that we use the %lu format specifer to print the result, instead of %d. It is
because the compiler expects the sizeof operator to return a long unsigned
int (%lu), instead of int (%d). On some computers it might work with %d, but it
is safer to use %lu.
C Booleans
Booleans
Very often, in programming, you will need a data type that can only have
one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
Boolean Variables
In C, the bool type is not a built-in data type, like int or char.
It was introduced in C99, and you must import the following header file to
use it:
#include <stdbool.h>
A boolean variable is declared with the bool keyword and can only take the
values true or false:
bool isProgrammingFun = true;
bool isFishTasty = false;
Before trying to print the boolean variables, you should know that boolean
values are returned as integers:
Therefore, you must use the %d format specifier to print a boolean value:
Example
// Create boolean variables
bool isProgrammingFun = true;
bool isFishTasty = false;
Try it Yourself »
For example, you can use a comparison operator, such as the greater
than (>) operator, to compare two values:
Example
printf("%d", 10 > 9); // Returns 1 (true) because 10 is greater than 9
Try it Yourself »
From the example above, you can see that the return value is a boolean
value (1).
Try it Yourself »
Example
printf("%d", 10 == 10); // Returns 1 (true), because 10 is equal to 10
printf("%d", 10 == 15); // Returns 0 (false), because 10 is not equal
to 15
printf("%d", 5 == 55); // Returns 0 (false) because 5 is not equal to
55
Try it Yourself »
You are not limited to only compare numbers. You can also compare boolean
variables, or even special structures, like arrays (which you will learn more
about in a later chapter):
Example
bool isHamburgerTasty = true;
bool isPizzaTasty = true;
Try it Yourself »
In the example below, we use the >= comparison operator to find out if the
age (25) is greater than OR equal to the voting age limit, which is set to 18:
Example
int myAge = 25;
int votingAge = 18;
printf("%d", myAge >= votingAge); // Returns 1 (true), meaning 25 year
olds are allowed to vote!
Try it Yourself »
Cool, right? An even better approach (since we are on a roll now), would be
to wrap the code above in an if...else statement, so we can perform
different actions depending on the result:
Example
Try it Yourself »
You will learn more about conditions (if...else) in the next chapter.
C If ... Else
Conditions and If Statements
You have already learned that C supports the usual logical conditions from
mathematics:
You can use these conditions to perform different actions for different
decisions.
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
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate
an error.
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");
}
Try it Yourself »
Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
Try it Yourself »
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".
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."
Try it Yourself »
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".
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."
Try it Yourself »
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."
Another Example
This example shows how you can use if..else to find out if a number is
positive or negative:
Example
int myNum = 10; // Is this a positive or negative number?
if (myNum > 0) {
printf("The value is a positive number.");
} else if (myNum < 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
Try it Yourself »
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
Try it Yourself »
Example
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");
Try it Yourself »
C Switch
Switch Statement
Instead of writing many if..else statements, you can use
the switch statement.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
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;
}
Try it Yourself »
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.
A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
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");
}
Try it Yourself »
Note: The default keyword must be used as the last statement in the switch,
and it does not need a break.
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++;
}
Try it Yourself »
Note: Do not forget to increase the variable used in the condition (i++),
otherwise the loop will never end!
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);
Try it Yourself »
Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
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 (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been
executed.
Try it Yourself »
Example explained
Statement 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.
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
Another Example
This example will only print even values between 0 and 10:
Example
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
Try it Yourself »
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)
}
}
Try it Yourself »
Example
int i;
Try it Yourself »
Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
Example
int i;
Break Example
int i = 0;
Try it Yourself »
Continue Example
int i = 0;
Try it Yourself »
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 [].
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
Try it Yourself »
Example
myNumbers[0] = 33;
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
// Now outputs 33 instead of 25
Try it Yourself »
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
Try it Yourself »
Example
// Declare an array of four integers:
int myNumbers[4];
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Try it Yourself »
Using this method, you should know the size of the array, in order for
the program to store enough memory.
You are not able to change the size of the array after creation.
C Multidimensional Arrays
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known
as single dimension arrays. These are great, and something you will use a
lot while programming in C. However, if you want to store data as a tabular
form, like a table with rows and columns, you need to get familiar
with multidimensional arrays.
Arrays can have any number of dimensions. In this chapter, we will introduce
the most common; two-dimensional arrays (2D).
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
The first dimension represents the number of rows [2], while the second
dimension represents the number of columns [3]. The values are placed in
row-order, and can be visualized like this:
This statement accesses the value of the element in the first row
(0) and third column (2) of the matrix array.
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
Try it Yourself »
Remember that: Array indexes start with 0: [0] is the first element. [1] is
the second element, etc.
The following example will change the value of the element in the first row
(0) and first column (0):
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
Try it Yourself »
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
Try it Yourself »
C Strings
Strings
Strings are used for storing text/characters.
To output the string, you can use the printf() function together with the
format specifier %s to tell C that we are now working with strings:
Example
char greetings[] = "Hello World!";
printf("%s", greetings);
Try it Yourself »
Access Strings
Since strings are actually arrays in C, you can access a string by referring to
its index number inside square brackets [].
Example
char greetings[] = "Hello World!";
printf("%c", greetings[0]);
Try it Yourself »
Note that we have to use the %c format specifier to print a single character.
Modify Strings
To change the value of a specific character in a string, refer to the index
number, and use single quotes:
Example
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!
Try it Yourself »
Example
char carName[] = "Volvo";
int i;
Try it Yourself »
You should also note that you can create a string with a set of characters.
This example will produce the same result as the example in the beginning of
this page:
Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
printf("%s", greetings);
Try it Yourself »
Differences
The difference between the two ways of creating strings, is that the first
method is easier to write, and you do not have to include the \0 character, as
C will do it for you.
You should note that the size of both arrays is the same: They both have 13
characters (space also counts as a character by the way), including
the \0 character:
Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
char greetings2[] = "Hello World!";
Try it Yourself »
C Special Characters
Strings - Special Characters
Because strings must be written within quotes, C will misunderstand this
string, and generate an error:
char txt[] = "We are the so-called "Vikings" from the north.";
The backslash (\) escape character turns special characters into string
characters:
\\ \ Backslash
Example
char txt[] = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »
Example
char txt[] = "It\'s alright.";
Try it Yourself »
Example
char txt[] = "The character \\ is called backslash.";
Try it Yourself »
Escape Result
Character
\n New Line
\t Tab
\0 Null
C String Functions
String Functions
C also has many useful string functions, which can be used to perform
certain operations on strings.
To use them, you must include the <string.h> header file in your program:
#include <string.h>
String Length
For example, to get the length of a string, you can use the strlen() function:
Example
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));
Try it Yourself »
In the Strings chapter, we used sizeof to get the size of a string/array. Note
that sizeof and strlen behaves differently, as sizeof also includes
the \0 character when counting:
Example
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 27
Try it Yourself »
It is also important that you know that sizeof will always return the memory
size (in bytes), and not the actual string length:
Example
char alphabet[50] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 50
Try it Yourself »
Concatenate Strings
To concatenate (combine) two strings, you can use the strcat() function:
Example
char str1[20] = "Hello ";
char str2[] = "World!";
// Print str1
printf("%s", str1);
Try it Yourself »
Note that the size of str1 should be large enough to store the result of the
two strings combined (20 in our example).
Copy Strings
To copy the value of one string to another, you can use the strcpy() function:
Example
char str1[20] = "Hello World!";
char str2[20];
// Print str2
printf("%s", str2);
Try it Yourself »
Note that the size of str2 should be large enough to store the copied string
(20 in our example).
Compare Strings
To compare two strings, you can use the strcmp() function.
It returns 0 if the two strings are equal, otherwise a value that is not 0:
Example
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";
Try it Yourself »
C User Input
User Input
You have already learned that printf() is used to output values in C.
Example
// Create an integer variable that will store the number we get from
the user
int myNum;
Run example »
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.
Tip: You will learn more about memory addresses and functions in the next
chapter.
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;
Run example »
Example
// Create a string
char firstName[30];
Run example »
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 (&).
Example
char fullName[30];
printf("Type your full name: \n");
scanf("%s", &fullName);
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];
Run example »
Use the scanf() function to get a single word as input, and use fgets() for
multiple words.
C Memory Address
Memory Address
When a variable is created in C, a memory address is assigned to the
variable.
The memory address is the location of where the variable is stored on the
computer.
Example
int myAge = 43;
printf("%p", &myAge); // Outputs 0x7ffe5367e044
Try it Yourself »
Note: The memory address is in hexadecimal form (0x..). You will probably
not get the same result in your program, as this depends on where the
variable is stored on your computer.
You should also note that &myAge is often called a "pointer". A pointer basically
stores the memory address of a variable as its value. To print pointer values,
we use the %p format specifier.
You will learn much more about pointers in the next chapter.
Pointers are one of the things that make C stand out from other
programming languages, like Python and Java.
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
Try it Yourself »
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
Try it Yourself »
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.
Difference
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
Try it Yourself »
Note that the * sign can be confusing here, as it does two different things in
our code:
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.
Example
int myNumbers[4] = {25, 50, 75, 100};
You learned from the arrays chapter that you can loop through the array
elements with a for loop:
Example
int myNumbers[4] = {25, 50, 75, 100};
int i;
Try it Yourself »
Instead of printing the value of each array element, let's print the memory
address of each array element:
Example
int myNumbers[4] = {25, 50, 75, 100};
int i;
Try it Yourself »
Note that the last number of each of the elements' memory address is
different, with an addition of 4.
Example
// Create an int variable
int myInt;
So from the "memory address example" above, you can see that the
compiler reserves 4 bytes of memory for each array element, which means
that the entire array takes up 16 bytes (4 * 4) of memory storage:
Example
int myNumbers[4] = {25, 50, 75, 100};
Confused? Let's try to understand this better, and use our "memory address
example" above again.
The memory address of the first element is the same as the name of the
array:
Example
int myNumbers[4] = {25, 50, 75, 100};
Try it Yourself »
This basically means that we can work with arrays through pointers!
Example
int myNumbers[4] = {25, 50, 75, 100};
// Get the value of the first element in myNumbers
printf("%d", *myNumbers);
Try it Yourself »
To access the rest of the elements in myNumbers, you can increment the
pointer/array (+1, +2, etc):
Example
int myNumbers[4] = {25, 50, 75, 100};
// and so on..
Try it Yourself »
Example
int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;
Try it Yourself »
Example
int myNumbers[4] = {25, 50, 75, 100};
Try it Yourself »
This way of working with arrays might seem a bit excessive. Especially with
simple arrays like in the examples above. However, for large arrays, it can
be much more efficient to access and manipulate arrays with pointers.
And since strings are actually arrays, you can also use pointers to
access strings.
For now, it's great that you know how this works. But like we specified in the
previous chapter; pointers must be handled with care, since it is possible
to overwrite other data stored in memory.