Output
Output
#include <stdio.h>
int main() {
printf("Hello World");
return 0;
Output
Hello World
Explanation:
int main() – The main function where the execution of the program begins.
Examples
Syntax of printf
printf("your_name_here")
#include <stdio.h>
int main() {
printf("Rahul");
return 0;
Output
Rahul
#include <stdio.h>
int main() {
// characters at max
char name[100];
scanf("%s", name);+
return 0;
}
Output
Using puts()
The puts() function is another function that is used to print the given string to the
output screen. It is also defined inside the <stdio.h> header file.
Syntax of puts()
puts("name");
#include <stdio.h>
int main() {
puts("Vikas");
return 0;
10
}
Output
Vikas
Using fputs()
The fputs() function is used for file output. We can redirect this function to standard
output buffer "stdout" to print your name on the console screen.
Syntax
fputs("name", stdout);
#include <stdio.h>
int main() {
fputs("Robert", stdout);
return 0;
10
Output
Robert
Using fprintf()
The fprintf() function is used also for file output. It is similar to the printf function,
but we need to specify the output buffer in the function which in this case is stdout.
Syntax
fprintf("name", stdout);
#include <stdio.h>
int main() {
fputs("Robert", stdout);
return 0;
Output
Robert
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
Syntax
Where type is one of C types (such as int), and variable Name 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
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
To output variables in C, you must get familiar with something called "format
specifiers",
C 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, use the format
specifier %d surrounded by double quotes (""), inside the printf() function:
Example
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
You can also just print a value without storing it in a variable, as long as you use the
correct format specifier:
Example
However, it is more sustainable to use variables as they are saved for later and can
be re-used whenever.
C Variable Values
If you assign a new value to an existing variable, it will overwrite the previous value:
Example
Example
Example
int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);
To declare more than one variable of the same type, use a comma-separated list:
Example
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
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);
C Variable Names
All C variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Example
C Variables - Examples
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, and so on). This is done to avoid
confusion.
However, for a practical example of using variables, we have created a program that
stores different data about 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);
In this real-life example, we create a program to calculate the area of a rectangle (by
multiplying the length and width):
Example
Data Types
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);
float 4 bytes Stores fractional numbers, containing one or more decimals. Suffici
digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Suffici
There are different format specifiers for each data type. Here are some of them:
%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 c
Note: It is important that you use the correct format specifier for the specified data
type. If not, the program may produce errors or even crash.
The character must be surrounded by single quotes, like 'A' or 'c', and we use
the %c format specifier to print it:
Example
char myGrade = 'A';
printf("%c", myGrade);
Alternatively, if you are familiar with ASCII, you can use ASCII values to display
certain characters. Note that these values are not surrounded by quotes (''), as they
are numbers:
Example
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
Notes on Characters
If you try to store more than a single character, it will only print the last character:
Example
Note: Don't use the char type for storing multiple characters, as it may produce
errors.
To store multiple characters (or whole words), use strings (which you will learn more
about in a later chapter):
Example
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 (with decimals), like
9.99 or 3.14515.
int
float
float myNum = 5.75;
printf("%f", myNum);
double
The precision of a floating point value indicates how many digits the value can have
after the decimal point. 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).
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the
power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;
printf("%f\n", f1);
printf("%lf", d1);
C Decimal Precision
You have probably already noticed that if you print a floating point number, the
output will show many digits after the decimal point:
Example
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;
printf("%f\n", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
Try it Yourself »
We introduced in the data types chapter that the memory size of a variable varies
depending on the type:
int 2 or 4 bytes
float 4 bytes
double 8 bytes
char 1 byte
The memory size refers to how much space a type occupies in the computer's
memory.
To actually get the size (in bytes) of a data type or variable, use 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));
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.
For example, the size of a char type is 1 byte. Which means if you have an array of
1000 char values, it will occupy 1000 bytes (1 KB) of memory.
Using the right data type for the right purpose will save memory and improve the
performance of your program.
Real-Life Example
Here's a real-life example of using different data types, to calculate and output the
total cost of a number of items:
Example
// Print variables
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);
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
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.
Especially if it was the other way around - the following example automatically
converts the float value 9.99 to an int value of 9:
Example
printf("%d", myInt); // 9
What happened to .99? We might want that data in our program! So be careful. It is
important that you know how the compiler work in these situations, to avoid
unexpected results.
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;
Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in
the division. In this case, you need to manually convert the integer values to
floating-point values. (see below).
Explicit Conversion
Considering our problem from the example above, we can now get the right result:
Example
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;
Real-Life Example
Here's a real-life example of data types and type conversion where we create a
program to calculate the percentage of a user's score in relation to the maximum
score in a game:
Example
/* Calculate the percantage of the user's score in relation to the maximum available
score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0;
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
You should always declare the variable as constant when you have values that are
unlikely to change:
Example
Notes On Constants
Example
Like this:
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
C Operators
Operators
In the example below, we use the + operator to add together two values:
Example
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
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Assignment Operators
In the example below, we use the assignment operator (=) to assign the value 10 to
a variable called x:
Example
int x = 10;
Example
int x = 10;
x += 5;
= 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
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
> Greater than x>y Returns 1 if the first value is greater tha
< Less than x<y Returns 1 if the first value is less than t
>= Greater than or equal to x >= y Returns 1 if the first value is greater tha
value
<= Less than or equal to x <= y Returns 1 if the first value is less than,
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
Try it Yourself »
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, by
combining multiple conditions:
&& AND x < 5 && x < 10 Returns 1 if both statements are true
! NOT !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1
Exercise?
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 take the
values true or false:
Before trying to print the boolean variables, you should know that boolean values
are returned as integers:
0 represents false
Therefore, you must use the %d format specifier to print a boolean value:
Example
For example, you can use a comparison operator, such as the greater than (>)
operator, to compare two values:
Example
From the example above, you can see that the return value is a boolean value (1).
Example
int x = 10;
int y = 9;
printf("%d", x > y);
In the example below, we use the equal to (==) operator to compare different
values:
Example
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
Remember to include the <stdbool.h> header file when working with bool variables.
C Boolean Examples
Let's think of a "real life example" where we need to find out if a person is old
enough to vote.
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
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
Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise
output "Not old enough to vote.":
You will learn more about conditions (if...else) in the next chapter.
C If ... Else
You have already learned that C supports the usual logical conditions from
mathematics:
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Use else if to specify a new condition to test, if the first condition is false
The if Statement
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
Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
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".
C Else
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
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".
C Else If
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
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."
Real-Life Examples
This example shows how you can use if..else to "open a door" if the user enters the
correct code:
Example
if (doorCode == 1337) {
printf("Correct code.\nThe door is now open.");
} else {
printf("Wrong code.\nThe door remains closed.");
}
Try it Yourself »
This example shows how you can use if..else to find out if a number is positive or
negative:
Example
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.");
}
Example
Example
int myNum = 5;
if (myNum % 2 == 0) {
printf("%d is even.\n", myNum);
} else {
printf("%d is odd.\n", myNum);
}
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 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;
}
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.
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");
}
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 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++;
}
Note: Do not forget to increase the variable used in the condition (i++), otherwise
the loop will never end!
C 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);
Do not forget to increase the variable used in the condition, otherwise the loop will
never end!
C While Loop Examples
Real-Life Examples
Example
int countdown = 3;
In this example, we create a program that only print even numbers between 0 and
10 (inclusive):
Example
int i = 0;
Example
Example
int dice = 1;
If the loop passes the values ranging from 1 to 5, it prints "No Yatzy". Whenever it
passes the value 6, it prints "Yatzy!".
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
Expression 1 is executed (one time) before the execution of the code block.
Expression 3 is executed (every time) after the code block has been executed.
Example
int i;
Example explained
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.
C Nested Loops
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)
}
}
Real-Life Examples
To demonstrate a practical example of the for loop, let's create a program that
counts to 100 by tens:
Example
for (i = 0; i <= 100; i += 10) {
printf("%d\n", i);
}
In this example, we create a program that only print even numbers between 0 and
10 (inclusive):
Example
Example
Example
And in this example, we create a program that prints the multiplication table for a
specified number:
Example
int number = 2;
int i;
return 0;
Break
You have already seen the break statement used in an earlier chapter of this tutorial.
It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
Example
int i;
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;
Continue Example
int i = 0;
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, and make sure
all values are of the same data type:
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
// Outputs 25
Change an Array Element
Example
myNumbers[0] = 33;
Example
printf("%d", myNumbers[0]);
You can loop through the array elements with the for loop.
Example
Another common way to create arrays, is to specify the size of the array, and add
elements later:
Example
// 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.
It is important to note that all elements in an array must be of the same data type.
This means you cannot mix different types of values, like integers and floating point
numbers, in the same array:
Example
In the example above, the values 3.15 and 5.99 will be truncated to 3 and 5. In some
cases it might also result in an error, so it is important to always make sure that the
elements in the array are of the same type.
C Array Size
To get the size of an array, you can use the sizeof operator:
Example
Why did the result show 20 instead of 5, when the array contains 5 elements?
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 the first
element in the array):
Example
int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
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 size of 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
It is better to write:
Example
Real-Life Example
Example
And in this example, we create a program that finds the lowest age among different
ages:
Example
int i;
// Loop through the elements of the ages array to find the lowest age
for (i = 0; i < length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}
}
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
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
Remember that: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
To change the value of an element, refer to the index number of the element in each
of the dimensions:
The following example will change the value of the element in the first row
(0) and first column (0):
Example
To loop through a multi-dimensional array, you need one loop for each of the array's
dimensions.
Example
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
C Strings
Strings
Unlike many other programming languages, C does not have a String type to easily
create string variables. Instead, you must use the char type and create an array of
characters to make a string in C:
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);
Access Strings
Since strings are actually arrays in C, you can access a string by referring to its index
number inside square brackets [].
Example
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
You can also loop through the characters of a string, using a for loop:
Example
And like we specified in the arrays chapter, you can also use the sizeof
formula (instead of manually write the size of the array in the loop condition (i < 5))
to make the loop more sustainable:
Example
char carName [] = "Volvo";
int length = sizeof(carName) / sizeof (carName [0]);
int i;
In the examples above, we used a "string literal" to create a string variable. This is
the easiest way to create a string in C.
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);
Why do we include the \0 character at the end? This is known as the "null
terminating character", and must be included when creating strings using this
method. It tells C that this is the end of the string.
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!";
Real-Life Example
C 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 solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
\\ \ Backslash
Example
char txt[] = "We are the so-called \"Vikings\" from the north.";
Example
Example
char txt[] = "The character \\ is called backslash.";
\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
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
Example
Concatenate Strings
To concatenate (combine) two strings, you can use the strcat() function:
Example
// Print str1
printf("%s", str1);
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
// Print str2
printf("%s", str2);
Note that the size of str2 should be large enough to store the copied string (20 in our
example).
Compare Strings
It returns 0 if the two strings are equal, otherwise a value that is not 0:
Example
#include <stdio.h>
int main() {
int grades[100], n, i;
scanf("%d", &n);
// Input grades
scanf("%d", &grades[i]);
sum += grades[i];
// Calculate average
average = sum / n;
return 0;
OUPUT:
Grade 1: 80
Grade 2: 90
Grade 3: 75
Grade 4: 85
Grade 5: 95
FIBINOCCI SERIES
#include <stdio.h>
int main() {
int n, a = 0, b = 1, next, i = 1;
scanf("%d", &n);
while (i <= n) {
next = a + b;
a = b;
b = next;
i++;
return 0;
OUTPUT :
Fibonacci Series: 0 1 1 2 3 5 8
ARMSTRONG NUMBERB
#include <stdio.h>
#include <math.h>
int main() {
scanf("%d", &num);
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
n++;
originalNum = num;
// Calculate the sum of nth powers of digits
while (originalNum != 0) {
originalNum /= 10;
if ((int)result == num)
else
return 0;
OUTPUT:
PALINDROME NUMBER :
#include <stdio.h>
int main() {
scanf("%d", &num);
original = num;
while (num != 0) {
num /= 10;
if (original == reversed)
else
return 0;
OUTPUT:
Examples:
121 → Palindrome
Memory Address
The memory address is the location of where the variable is stored on the computer.
To access it, use the reference operator (&), and the result represents where the
variable is stored:
Example
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.
Pointers 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.
Pointers are one of the things that make C stand out from other programming
languages, like Python and Java.
Pointers
Creating Pointers
You learned from the previous chapter, that we can get the memory address of a
variable with the reference operator &:
Example
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
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.
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
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 and memory management.
But be careful; pointers must be handled with care, since it is possible to damage
data stored in other memory addresses.
Example
You learned from the arrays chapter that you can loop through the array elements
with a for loop:
Example
Result:
25
50
75
100
Instead of printing the value of each array element, let's print the memory address
of each array element:
Example
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f4
0x7ffe70f9d8f8
0x7ffe70f9d8fc
Note that the last number of each of the elements' memory address is different,
with an addition of 4.
Example
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
Result:
16
Ok, so what's the relationship between pointers and arrays? Well, in C, the name of
an array, is actually a pointer to the first element of the array.
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
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f0
This basically means that we can work with arrays through pointers!
How? Since myNumbers is a pointer to the first element in myNumbers, you can use
the * operator to access it:
Example
Result:
25
To access the rest of the elements in myNumbers, you can increment the
pointer/array (+1, +2, etc):
Example
// and so on..
Result:
50
75
Example
Result:
25
50
75
100
Example
Result:
13
17
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.