0% found this document useful (0 votes)
50 views266 pages

C Programming Language

Uploaded by

Kyla Acs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views266 pages

C Programming Language

Uploaded by

Kyla Acs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

C

(Programming
Language)
C
(Programming
Language)
C is a general-purpose computer
programming language.
It was created in the 1970s by
Dennis Ritchie and Bell Labs, and
remains very widely used and
influential.
By design, C's features cleanly
reflect the capabilities of the
targeted CPUs.
C
(Programming
Language)
It has found lasting use in
operating systems, device
drivers, protocol stacks, though
decreasingly for application
software, and is common in
computer architectures that
range from the largest
supercomputers to the smallest
microcontrollers and embedded
systems.
C
(Programming
Language)
C is an imperative procedural
language supporting structured
programming, lexical variable
scope, and recursion, with a
static type system.
It was designed to be compiled to
provide low-level access to
memory and language constructs
that map efficiently to machine
instructions, all with minimal
Why Learn C?
Why Learn C?
• It is one of the most popular
programming language in the
world
• If you know C, you will have no
problem to learn other popular
programming languages such
as Java, Python, C++, C#, etc.,
as the syntax is similar
Why Learn C?
• 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++
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
Get Started With C
Get Started With C
To start using C, you need two
things:
•A text editor, like Notepad, to
write C code
•A compiler, like GCC, to translate
the C code into a language that
the computer will understand
There are many text editors and
compilers to choose from.
C Install IDE
C Install IDE
An IDE (Integrated Development
Environment) is used to edit AND
compile the code.
Popular IDE's include
Code::Blocks, Eclipse, and Visual
Studio. These are all free, and
they can be used to both edit and
debug C code.
C Install IDE
Note: Web-based IDE's can work
as well, but functionality is
limited.
You can find the latest version of
Codeblocks at
[Link]
Download the [Link]
file, which will install the text
editor with a compiler.
C Quickstart
C Quickstart
Let's create our
first C file.
Open
Codeblocks and
go to File > New
> Empty File.
Write the
following C code
and save the file
as
myfirstprogram.
C Quickstart
C Quickstart
C Quickstart
C Syntax
C Syntax
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.
C Syntax
Line 2:
A blank line. C
ignores white
space. But we use it
to make the code
more readable.
C Syntax
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.
C Syntax
Line 4:
printf() is a function
used to output/print
text to the screen.
In our example it
will output "Hello
World".
C Syntax
Note that:
Every C statement
ends with a
semicolon ;
Note:
The body of int
main() could also
been written as:
int main()
{printf("Hello
C Syntax
Remember:
The compiler
ignores white
spaces. However,
multiple lines
makes the code
more readable.
C Syntax
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 Output (Print Text)
C Output (Print Text)
The printf() function
is used to output
values/print text:

You can add as


many printf()
functions as you
want. However,
note that it does not
insert a new line at
the end of the
C New Lines
To insert a new
line, you can use
the \n character:
C New Lines
You can also output multiple lines with
a single printf() function. However, be
aware that this will make the code
harder to read:
C New Lines
Tip:
Two \n
characters after
each other will
create a blank
line:
C New Lines
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 New Lines
Examples of other valid escape
sequences are:
C New Lines
\t
Creates a
horizontal tab
C New Lines
\\
Inserts a
backslash
character (\)
C New Lines
\“
Inserts a
double quote
character
C Comments
C Comments
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.
C Comments
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).
C Comments
This example
uses a single-
line comment
before a line
of code:

This example
uses a single-
line comment
at the end of
a line of code:
C Comments
This example uses a single-line
comment at the end of a line of code:
C Comments
C Multi-line Comments
Multi-line comments start with /*
and ends with */.
Any text between /* and */ will be
ignored by the compiler:
C Comments
C Variables
C Variables
Variables are containers for storing data
values.
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
Declaring (Creating)
Variables
Declaring (Creating)
Variables
To create a variable, specify the type
and assign it a value:
Syntax:

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.
Declaring (Creating)
Variables
So, to create a variable that should
store a number, look at the following
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:
Declaring (Creating)
Variables
Note: If you assign a new value to an
existing variable, it will overwrite the
previous value:
Output Variables
Output Variables
You learned from the output chapter
that you can output values/print text
with the printf() function:
Output Variables
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:
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.
A format specifier starts with a
percentage sign %, followed by a
character.
Format Specifiers
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:
Format Specifiers
To print other types, use %c for char
and %f for float:
Format Specifiers
To print other types, use %c for char
and %f for float:
Format Specifiers
To combine both text and a variable,
separate them with a comma inside the
printf() function:
Format Specifiers
To print different types in a single
printf() function, you can use the
following:
Add Variables Together
Add Variables
Together
To add a variable to another variable,
you can use the + operator:
Declare Multiple
Variables
Declare Multiple
Variables
To declare more than one variable of the
same type, use a comma-separated list:
Declare Multiple
Variables
You can also assign the same value to
multiple variables of the same type:
C Variable Names
C Variable Names
All C variables must be identified with
unique names.
These unique names are called
identifiers.
Identifiers can be short names (like x
and y) or more descriptive names (age,
sum, totalVolume).
C Variable Names
Note: It is recommended to use
descriptive names in order to create
understandable and maintainable code:
C Variable Names
The general rules for naming variables
are:
•Names can contain letters, digits and
underscores
•Names must begin with a letter or an
underscore (_)
•Names are case sensitive (myVar and
myvar are different variables)
•Names cannot contain whitespaces or
special characters like !, #, %, etc.
•Reserved words (such as int) cannot be
C Data Types
C 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:
C Data Types
Basic Data Types
Basic Data Types
The data type specifies the size and
type of information the variable will
store.
Basic Format Specifiers
Basic Format
Specifiers
There are different format specifiers for
each data type. Here are some of them:
Basic Format
Specifiers
Basic Format
Specifiers
Basic Format
Specifiers
Basic Format
Specifiers
Basic Format
Specifiers
C Constants
C Constants
When you don't want others (or
yourself) to override existing variable
values, use the const keyword (this will
declare the variable as "constant",
which means unchangeable and read-
only):
C Constants
C Constants
You should always declare the variable
as constant when you have values that
are unlikely to change:
C Constants
Notes On Constants
Notes On Constants
When you declare a constant variable, it
must be assigned with a value:
Like
this:

This however, will not work:


Notes On Constants
C Operators
C Operators
Operators are used to perform
operations on variables and values.
In the example below, we use the +
operator to add together two values:
C Operators
C Operators
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:
C Operators
C Operators
C divides the operators into the
following groups:
•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Bitwise operators
Arithmetic Operators
Arithmetic
Operators
Arithmetic operators are used to
perform common mathematical
operations.
Arithmetic
Operators
Arithmetic operators are used to
perform common mathematical
operations.
Arithmetic
Operators
Arithmetic operators are used to
perform common mathematical
operations.
Arithmetic
Operators
Arithmetic operators are used to
perform common mathematical
operations.
Arithmetic
Operators
Arithmetic operators are used to
perform common mathematical
operations.
Arithmetic
Operators
Arithmetic operators are used to
perform common mathematical
operations.
Arithmetic
Operators
Arithmetic operators are used to
perform common mathematical
operations.
Arithmetic
Operators
Arithmetic operators are used to
perform common mathematical
operations.
Assignment Operators
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:
Assignment
Operators
The addition assignment operator (+=)
adds a value to a variable:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Assignment
Operators
A list of all assignment operators:
Comparison Operators
Comparison
Operators
Comparison operators are used to
compare two values.
Note: The return value of a comparison
is either true (1) or false (0).
In the following example, we use the
greater than operator (>) to find out if
5 is greater than 3:
Comparison
Operators
Comparison
Operators
A list of all comparison operators:
Comparison
Operators
A list of all comparison operators:
Comparison
Operators
A list of all comparison operators:
Comparison
Operators
A list of all comparison operators:
Comparison
Operators
A list of all comparison operators:
Comparison
Operators
A list of all comparison operators:
Comparison
Operators
A list of all comparison operators:
Logical Operators
Logical Operators
Logical operators are used to determine
the logic between variables or values:
Logical Operators
Logical operators are used to determine
the logic between variables or values:
Logical Operators
Logical operators are used to determine
the logic between variables or values:
Logical Operators
Logical operators are used to determine
the logic between variables or values:
Sizeof Operator
Sizeof Operator
The memory size (in bytes) of a data
type or a variable can be found with the
sizeof operator:
Sizeof Operator
Conditions and If
Statements
Conditions and If
Statements
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
Conditions and If
Statements
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
Conditions and If
Statements
• 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
The if Statement
The if Statement
Use the if statement to specify a
block of C code to be executed if
a condition is true.
Syntax:

Note that if is in lowercase letters.


Uppercase letters (If or IF) will generate
an error.
The if Statement
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:
The if Statement
The if Statement
We can also test variables:
The if Statement
The if Statement
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
The else Statement
Use the else statement to
specify a block of code to be
executed if the condition is false.
Syntax:
The else Statement
Example:
The else Statement
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
The else if
Statement
Use the else if statement to
specify a new condition if the
first condition is false.
Syntax:
The else if
Statement
Example:
The else if
Statement
The else if
Statement
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
The else if
Statement
This example shows how you can
use if..else if to find out if a
number is positive or negative:
The else if
Statement
C Short Hand If Else
C Short Hand If Else
There is also a short-hand if else,
which is known as the ternary
operator because it consists of
three operands. It can be used to
replace multiple lines of code
with a single line. It is often used
to replace simple if else
statements:
C Short Hand If Else
Instead of writing:
Example
C Short Hand If Else
C Short Hand If Else
You can simply write:
Example
C Short Hand If Else
Switch Statement
Switch Statement
Instead of
writing many
if..else
statements, you
can use the
switch
statement.
The switch
statement
selects one of
Switch Statement
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
Switch Statement
• 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
Switch Statement
The
example
uses the
weekday
number to
calculate
the
weekday
name:
Switch Statement
Switch Statement
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.
Switch Statement
The default
Keyword
The default
keyword
specifies
some code
to run if
there is no
case match:
Switch Statement
While Loop
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 Loop
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
While Loop
The Do/While Loop
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
The Do/While Loop
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
The Do/While Loop
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 Loop
Statement 1 is executed (one
time) before the execution of the
code block.
Statement 2 defines the
condition for executing the code
block.
Statement 3 is executed (every
time) after the code block has
been executed.
For Loop
The example below will print the
numbers 0 to 4:
Example
For Loop
For Loop
Example explained
Statement 1 sets a variable before
the loop starts (int i = 0).
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
For Loop
This example will only print even
values between 0 and 10:
Example
For Loop
C Break and Continue
C Break and
Continue
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.
C Break and
Continue
This example jumps out of the
loop when i is equal to 4:
Example
C Break and
Continue
C Break and
Continue
Continue
The continue statement breaks
one iteration (in the loop), if a
specified condition occurs, and
continues with the next iteration
in the loop.
C Break and
Continue
This example skips the value of
4:
Example
C Break and
Continue
C Break and
Continue
Break and Continue in While
Loop
You can also use break and
continue in while loops:
Break Example
C Break and
Continue
C Break and
Continue
Break and Continue in While
Loop
You can also use break and
continue in while loops:
Continue Example
C Break and
Continue
C Arrays
C 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 [].
C Arrays
To insert values to it, use a
comma-separated list, inside
curly braces:

We have now created a variable


that holds an array of four
integers.
Access the Elements of
an Array
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.
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.
Access the Elements
of
an Array
Change an Array
Element
Change an Array
Element
To change the value of a specific
element, refer to the index
number:
Example

Example
Change an Array
Element
Loop Through an Array
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
Loop Through an
Array
Set Array Size
Set Array Size
Another common way to create
arrays, is to specify the size of
the array, and add elements
later:
Example
Set Array Size
C Strings
C Strings
Strings are used for storing
text/characters.
For example, "Hello World" is a
string of characters.
Unlike many other programming
languages, C does not have a
String type to easily create
string variables. However, you
can use the char type and create
C Strings

Note that you have to use double


quotes.
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:
C Strings
Example
Access Strings
Access Strings
Since strings are actually arrays
in C, you can access a string by
referring to its index number
inside square brackets [].
This example prints the first
character (0) in greetings:
Example
Access Strings

Note that we have to use the %c


format specifier to print a single
character.
Modify Strings
Modify Strings
To change the value of a specific
character in a string, refer to the
index number, and use single
quotes:
Example
Modify Strings
Another Way of Creating
Strings
Another Way of
Creating Strings
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 to create a string with a set
of characters. This example will
produce the same result as the
Another Way of
Creating Strings
Example
Another Way of
Creating Strings
Why do we include the \0
character at the end?
This is known as the "null
termininating character", and
must be included when creating
strings using this method. It tells
C that this is the end of the
string.
Differences
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
Differences
Example
C User Input
C User 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:
C User Input
Example
Output a number entered by the
user:
C User Input
C User Input
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.
User Input Strings
User Input Strings
You can
also get a
string
entered by
the user:
Example
Output the
name of a
user:
User Input Strings
User Input Strings
Note that you must specify the
size of the string/array (we used
a very high number, 30, but
atleast then we are certain it
will store enough characters for
the first name), and you don't
have to specify the reference
operator (&) when working with
strings in scanf().
C Memory Address
C 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.
When we assign a value to the
variable, it is stored in this
memory address.
C Memory Address
To access it, use the reference
operator (&), and the result will
represent where the variable is
stored:
Example
C Memory Address
C Memory Address
Note: The memory address is in
hexadecimal form (0x..). You
probably won't get the same
result in your program.
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
C Memory Address
Why is it useful to know the
memory address?
Pointers are important in C,
because they give you the ability
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
C Pointers
C Pointers
We can get the memory address
of a variable with the reference
operator &:
Example
C Pointers
C Pointers
In the example above, &myAge is
also known as a pointer.
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're
working with is assigned to the
C Pointers
Example
C Pointers
C Pointers
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.
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
Dereference
In the example above, we used
the pointer variable to get the
memory address of a variable
(used together with the &
reference operator).
However, you can also get the
value of the variable the pointer
points to, by using the *
operator (the dereference
operator):
Dereference
Example
Dereference
Dereference
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.
Dereference
Why Should Learn About
Pointers?
Pointers are important in C,
because they give you the
ability to manipulate the data in
the computer's memory - this
can reduce the code and
improve the performance.
Dereference
Good To Know:
There are three ways to declare
pointer variables, but the first
way is mostly used:
Thank you for
watching!
Please do subscribe to my channel and don't
forget to click the notification bell to keep you
updated for more informative topics or
discussions.
Created by:
MARILOU BARSOBIA MANGROBANG
BSCS / MPA / MIT
Professor / Tutor
2022

You might also like