You are on page 1of 23

17/10/2023

C Programming Language
Fundamentals
By: Võ Văn Hải
Email: vovanhaiqn@gmail.com

Session Objectives
▸The C Programming Language introduction

▸C Fundamental

▸C Input/Output

▸C Programming Operators

1
17/10/2023

Software Development Process


Introduction

▸Computer Programming Steps:

1. Define the Problem

2. Design the Algorithm

3. Coding

4. Testing & Debugging

5. Install/Deploy

6. Maintenance

Programming Languages
Introduction
▸A programming language is a set of instructions and syntax used to
create software programs. Some of the key features of programming
languages include:
- Syntax: The specific rules and structure used to write code in a programming
language.
- Data Types: The type of values that can be stored in a program, such as numbers,
strings, and booleans.
- Variables: Named memory locations that can store values.
- Operators: Symbols used to perform operations on values, such as addition,
subtraction, and comparison.
- Control Structures: Statements used to control the flow of a program, such as if-else
statements, loops, and function calls.
- Libraries and Frameworks: Collections of pre-written code that can be used to
perform common tasks and speed up development.
- Paradigms: The programming style or philosophy used in the language, such as
procedural, object-oriented, or functional.

2
17/10/2023

Programming Languages
Basic Terminologies
▸ Algorithm: A step-by-step procedure for solving a problem or performing a task.
▸ Variable: A named storage location in memory that holds a value or data.
▸ Data Type: A classification that specifies what type of data a variable can hold, such as integer,
string, or boolean.
▸ Function: A self-contained block of code that performs a specific task and can be called from
other parts of the program.
▸ Control Flow: The order in which statements are executed in a program, including loops and
conditional statements.
▸ Syntax: The set of rules that govern the structure and format of a programming language.
▸ Comment: A piece of text in a program that is ignored by the compiler or interpreter, used to
add notes or explanations to the code.
▸ Debugging: The process of finding and fixing errors or bugs in a program.
▸ IDE: Integrated Development Environment, a software application that provides a
comprehensive development environment for coding, debugging, and testing.
▸ Operator: A symbol or keyword that represents an action or operation to be performed on one
or more values or variables, such as + (addition), – (subtraction), * (multiplication), and /
(division).
▸ Statement: A single line or instruction in a program that performs a specific action or
operation.

The C Programming Language


Introduction
▸What is C?
- C is a general-purpose programming language created by Dennis Ritchie at the Bell
Laboratories in the 1970’s.
- It is a very popular language despite being old. The main reason for its popularity is
because it is a fundamental language in the field of computer science.
- C is strongly associated with UNIX, as it was developed to write the UNIX operating
system.
▸Why Learn C?
- It is one of the most popular programming 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

3
17/10/2023

Get Started with C


▸The C Compiler
- GNU compiler collection, MinGW, Clang, Intel C++ Compiler, Microsoft Visual C++
Compiler, LLC, Borland Turbo C, Tini C Compiler, Portable C Compiler, …

▸The Integrated Development Environments (IDE) : view list


- Code::Blocks link
- Jetbrain Clion link
- Qt link
- Eclipse - link
- Microsoft Visual Studio/ Visual Code (with extension)
- Online:
• https://www.codingninjas.com/studio/online-compiler/online-c-compiler
• https://www.onlinegdb.com/
• Others
▸Others necessary things
- Version control: Git (GitHub/GitLab/Bitbucket)
- Unit test: Cunit, Unity, GTest, Cmocka, …

Get Started with C


First program

Go to Build > Build and Run to run (execute) the program.

Result:

4
17/10/2023

Compiler working

C Fundamentals

10

10

5
17/10/2023

Fundamentals
C Keywords and Identifiers
▸Character set
A character set is a set of alphabets, letters and some special characters that are valid
in C language.
- Alphabets
• Uppercase: A B C ................................... X Y Z
• Lowercase: a b c ...................................... x y z
**C accepts both lowercase and uppercase alphabets as variables and functions.
- Digits
• 0123456789
- Special Characters
, < > . _
( ) ; $ :
% [ ] # ?
' & { } "
^ ! * / |
- \ ~ +
- White space Characters
• Blank space, newline, horizontal tab, carriage return and form feed.

11

11

Fundamentals
C Keywords
▸Keywords are predefined, reserved words used in programming that
have special meanings to the compiler. Keywords are part of the syntax,
and they cannot be used as an identifier.
▸As C is a case sensitive language, all keywords must be written in
lowercase. Here is a list of all keywords allowed in ANSI C.
C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

12

12

6
17/10/2023

Fundamentals
C Identifiers
▸Identifier refers to name given to entities such as variables, functions,
structures etc.
▸Identifiers must be unique. They are created to give a unique name to an
entity to identify it during the execution of the program.
- For example:

int money;
double accountBalance;

▸Here, 𝑚𝑜𝑛𝑒𝑦 and 𝑎𝑐𝑐𝑜𝑢𝑛𝑡𝐵𝑎𝑙𝑎𝑛𝑐𝑒 are identifiers.


▸Also remember, identifier names must be different from keywords. You
cannot use int as an identifier because int is a keyword.

13

13

Fundamentals
Rules for naming identifiers
▸A valid identifier can have letters (both uppercase and lowercase letters),
digits and underscores.
▸The first letter of an identifier should be either a letter or an underscore.
▸You cannot use keywords like int, while etc. as identifiers.
▸There is no rule on how long an identifier can be. However, you may run
into problems in some compilers if the identifier is longer than 31
characters.
▸You can choose any name as an identifier if you follow the above rule,
however, give meaningful names to identifiers that make sense.
▸Should read:

Naming convention

14

14

7
17/10/2023

C Variables, Constants and Literals


Variables
▸In programming, a variable is a container (storage area) to hold
data.
- To indicate the storage area, each variable should be given a unique name
(identifier). Variable names are just the symbolic representation of a
memory location. For example:
int playerScore = 95; Note: You should
char ch = 'a'; always try to give
ch = 'l'; meaningful names to
variables.

15

15

C Variables, Constants and Literals


Literals
▸Literals are data used for representing fixed values. They can be used directly in
the code. For example: 1, 2.5, 'c' etc.
1. Interger
- An integer is a numeric literal (associated with numbers) without any fractional or
exponential part. There are three types of integer literals in C programming:
• decimal (base 10)
• octal (base 8)
• hexadecimal (base 16)
2. Floating-point Literals
- A floating-point literal is a numeric literal that has either a fractional form or an exponent
form. For example: -2.0, 0.000034, -0.22E-5
3. Characters
- A character literal is created by enclosing a single character inside single quotation marks.
For example: 'a', 'm', 'F', '2', '}' etc.
4. Escape Sequences
- Sometimes, it is necessary to use characters that cannot be typed or has special meaning
in C programming. For example: newline(enter), tab, question mark etc.

16

16

8
17/10/2023

C Variables, Constants and Literals


Escape Sequences
Escape Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
For example: \n is used for a newline. The backslash \ causes escape from
the normal way the characters are handled by the compiler.

17

17

C Variables, Constants and Literals


Literals (cont.)
5. String Literals
- A string literal is a sequence of characters enclosed in double-quote marks. For
example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having a single character.
"Earth is round\n" //prints string with a newline

18

18

9
17/10/2023

C Variables, Constants and Literals


Constants
▸If you want to define a variable whose value cannot be changed, you can
use the const keyword. This will create a constant. For example,

const double PI = 3.14;

▸Here, PI is a symbolic constant; its value cannot be changed.

const double PI = 3.14;


PI = 2.9; //Error

▸You can also define a constant using the #define preprocessor directive.

#define X 5

printf("%d",X);

19

19

C Data Types
Basic Types
▸In C programming, data types are declarations for variables. This
determines the type and size of data associated with variables.
Type Size (bytes) Format Specifier
int at least 2, usually 4 %d, %i
char 1 %c
float 4 %f
double 8 %lf
short int 2 usually %hd
unsigned int ko co so sau phay at least 2, usually 4 %u
long int at least 4, usually 8 %ld, %li
long long int at least 8 %lld, %lli
unsigned long int at least 4 %lu
unsigned long long int at least 8 %llu
signed char 1 %c
unsigned char 1 %c
long double at least 10, usually 12 or 16 %Lf
20

20

10
17/10/2023

C Data Types
Basic Types
▸In C programming, data types are declarations for variables. This determines the
type and size of data associated with variables. Depend on compiler, the
datatype size may be differed.

Compiler char short int long long float long


double double void* size_t intptr_t
long

32-bit 1 2 4 4 8 4 8 8 4 4 4
Microsoft
32-bit 1 2 4 4 8 4 8 12 4 4 4
GNU gcc
32-bit 1 2 4 4 8 4 8 12 4 4 4
Clang

64-bit 1 2 4 4 8 4 8 8 8 8 8
Microsoft
64-bit 1 2 4 8 8 4 8 16 8 8 8
GNU gcc
64-bit 1 2 4 8 8 4 8 16 8 8 8
Clang
64-bit 1 2 4 4 8 4 8 16 8 8 8
MinGW
21

21

Binary, Octal, Decimal, and Hexadecimal numbers


▸In mathematics, a “base” or a “radix” is the number of different digits or
combination of digits and letters that a system of counting uses to
represent numbers. ~Wiki~
▸For example,
- Base 10 (Decimal) — Represent any number using 10 digits [0–9]

- Base 2 (Binary) — Represent any number using 2 digits [0–1]

- Base 8 (Octal) — Represent any number using 8 digits [0–7]

- Base 16(Hexadecimal) — Represent any number using 10 digits and 6 characters [0–
9, A, B, C, D, E, F]

22

22

11
17/10/2023

Binary, Octal, Decimal, and Hexadecimal numbers

▸Binary value can be assigned


in a variable by
using "0b" notation
- int num = 0b1010;
▸Decimal value can be
assigned directly
- int a = 100 ;
▸Octal value can be assigned
by using "0" notation
- int b = 0144 ;
▸Hexadecimal value can be
assigned by
using "0X" or "0x" notation
- int c = 0x64 ;.
https://www.cs.ucf.edu/courses/cop3502h/spr2007/binaryOctal.pdf
23

23

C Data Types
Derived Data Types
▸Data types that are derived from fundamental data types are derived
types.
- For example: arrays, pointers, function types, structures, etc.

▸We will learn about these derived data types in later.


- bool type 2 value : T&F
- Enumerated type sexual {male, female}
- Complex types

24

24

12
17/10/2023

C Input / Output

25

25

C Input Output (I/O)


C output
▸In C programming, 𝑝𝑟𝑖𝑛𝑡𝑓() is one of the main output function. The
function sends formatted output to the screen.
int main() {
// Displays the string inside quotations Result:
printf("C Programming\n");
//Display an integer number C Programming
int testInteger = 5;
printf("Number = %d\n", testInteger);
Number = 5
//Display a float number float number = 13.500000
float number1 = 13.5;
double number2 = 12.4; double number = 12.400000
printf("float number = %f\n", number1);
printf("double number = %lf\n", number2); character = a
//Display a character
char chr = 'a';
printf("character = %c", chr);

return 0;
}

26

26

13
17/10/2023

C Input Output (I/O)


C Input
▸ In C programming, 𝑠𝑐𝑎𝑛𝑓() is one of the commonly used function to take input from the
user. The 𝑠𝑐𝑎𝑛𝑓() function reads formatted input from the standard input such as
keyboards. Take multiple inputs from the user
int main() {
int main() {
int testInteger;
int a; float b;
printf("Enter an integer: "); scanf("%d", &testInteger);
printf("Enter integer and then a float: ");
printf("Number = %d",testInteger);
// Taking multiple inputs
scanf("%d%f", &a, &b);
float num1;
printf("You entered %d and %f", a, b);
double num2;
return 0;
}
printf("Enter a number: "); scanf("%f", &num1);
printf("Enter another number: "); scanf("%lf", &num2);
int main() { ASCII Value
printf("num1 = %f\n", num1); char chr;
printf("num2 = %lf", num2); printf("Enter a character: ");
scanf("%c", &chr);
char chr; // When %c is used, a character is displayed
printf("Enter a character: "); scanf("%c",&chr); printf("You entered %c.\n",chr);
printf("You entered %c.", chr); // When %d is used, ASCII value is displayed
printf("ASCII value is %d.", chr);
return 0; return 0;
} }
27

27

C Input Output (I/O)


Format Specifiers for I/O
Data Type Format Specifier
int %d
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
signed char %c
unsigned char %c
long double %Lf
28

28

14
17/10/2023

C Comments
▸There are two ways to add comments in C: /**
* This method takes two parameters and
- // Single Line Comment * then finds the maximum between them
- /∗ ⋯ ∗/ Multi-line Comment * @param x parameter x
▸Use of Comments in C * @param y parameter y
* @return maximum value
- Make Code Easier to Understand
*/
- Using Comments for debugging int findMax(int x, int y){
if(x>y)
return x;
//sample inline comment
return y;
}
▸Note:
- Comments are not and should not be used as a substitute to explain poorly written
code.
- Always try to write clean, understandable code, and then use comments as an
addition.
- In most cases, always use comments to explain 'why' rather than 'how' and you are
good to go.

29

29

C Programming Operators

30

30

15
17/10/2023

Operators in C ++a khac a++


== la so sanh true false= la gan gia tri
Types of Operators in C sau cho gia tri trc dau =
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators

++a++

31

31

C Programming Operators
C Arithmetic Operators
▸An operator is a symbol that operates on a value or a variable. For
example: + is an operator to perform addition.
▸C has a wide range of operators to perform various operations.
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)

▸Note: Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,


// Either one of the operands is a floating-point number
a/b = 2.5
a/d = 2.5
c/b = 2.5
// Both operands are integers
c/d = 2

32

32

16
17/10/2023

C Programming Operators
C Increment and Decrement Operators
▸C programming has two operators increment ++ and decrement -- to
change the value of an operand (constant or variable) by 1.
▸Increment ++ increases the value by 1 whereas decrement -- decreases
the value by 1. These two operators are unary operators, meaning they
only operate on a single operand.
int main()
{ Results
int a = 10, b = 100;
float c = 10.5, d = 100.5; ++a = 11
--b = 99
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b); ++c = 11.500000
printf("++c = %f \n", ++c);
--d = 99.500000
printf("--d = %f \n", --d);

return 0;
}
33

33

C Programming Operators
C Assignment Operators
▸An assignment operator is used for assigning a value to a variable. The
most common assignment operator is = int main()
{
Operator Example Same as int a = 5, c;
= a=b a=b
c = a; // c is 5
+= a += b a = a+b printf("c = %d\n", c);
-= a -= b a = a-b c += a; // c is 10
printf("c = %d\n", c);
*= a *= b a = a*b c -= a; // c is 5
/= a /= b a = a/b printf("c = %d\n", c);
c *= a; // c is 25
%= a %= b a = a%b printf("c = %d\n", c);
c /= a; // c is 5
c=5 printf("c = %d\n", c);
c = 10 c %= a; // c = 0
c=5 printf("c = %d\n", c);
Results
c = 25
c=5 return 0;
c=0 }
34

34

17
17/10/2023

C Programming Operators
C Relational Operators
▸A relational operator checks the relationship between two operands. If
the relation is true, it returns 1; if the relation is false, it returns value 0.
▸Relational operators are used in decision making and loops.
Operator Meaning of Operator Example int a = 5, b = 5, c = 10;

== Equal to 5 == 3 is evaluated to 0 printf("%d == %d is %d \n", a, b, a == b);


> Greater than 5 > 3 is evaluated to 1 printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
< Less than 5 < 3 is evaluated to 0 printf("%d > %d is %d \n", a, c, a > c);
!= Not equal to 5 != 3 is evaluated to 1 printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
>= Greater than or equal to 5 >= 3 is evaluated to 1 printf("%d != %d is %d \n", a, b, a != b);
<= Less than or equal to 5 <= 3 is evaluated to 0 printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
5 == 5 is 1 5 > 10 is 0 5 != 5 is 0 5 >= 10 is 0
5 == 10 is 0 5 < 5 is 0 5 != 10 is 1 5 <= 5 is 1
5 > 5 is 0 5 < 10 is 1 5 >= 5 is 1 5 <= 10 is 1

35

35

C Programming Operators
C Logical Operators
▸An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used in
decision making in C programming.
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);
(a == b) && (c > b) is 1
result = (a == b) && (c < b); (a == b) && (c < b) is 0
printf("(a == b) && (c < b) is %d \n", result); (a == b) || (c < b) is 1
(a != b) || (c < b) is 0
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result); !(a != b) is 1
!(a == b) is 0
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", result);

36

36

18
17/10/2023

C Programming Operators
C Bitwise Operators
▸During computation, mathematical operations like addition, subtraction,
multiplication, division, etc. are converted to bit-level which makes processing
faster and saves power.
Operators Meaning of operators X Y X&Y X|Y X^Y
& Bitwise AND 0 0 0
0 0
| Bitwise OR
0 1 1
^ Bitwise exclusive OR 0 1
~ Bitwise complement 1 0 0 1 1
<< Shift left
1 1 1 1 0
>> Shift right

Here, we will assume that A = 50 and B = 25 A&B = 00010000 16 dec


in binary format as follows.
A|B = 00111011 59 dec
A = 00110010 A^B = 00101011 43 dec
B = 00011001 ~A = 11001101 50 dec
A << 2 = 11001000 200 dec
A >> 2 = 00001100 12 dec
37

37

C Programming Operators
C Bitwise Operators - example
//C Program to demonstrate use of bitwise operators
int main() {
// a = 5(00000101), b = 9(00001001)
unsigned char a = 5, b = 9;

// The result is 00000001


printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a & b);

// The result is 00001101


printf("a|b = %d\n", a | b);

// The result is 00001100


printf("a^b = %d\n", a ^ b);

// The result is 11111010


printf("~a = %d\n", a = ~a);

// The result is 00010010


printf("b<<1 = %d\n", b << 1);

// The result is 00000100


printf("b>>1 = %d\n", b >> 1);

return 0;
}

38

38

19
17/10/2023

C Programming Operators
Other Operators
▸Comma Operator
- Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

▸The 𝑠𝑖𝑧𝑒𝑜𝑓 operator


- The 𝑠𝑖𝑧𝑒𝑜𝑓 is a unary operator that returns the size of data (constants, variables,
array, structure, etc.).
int a;
float b; Size of int = 4 bytes
double c;
char d; Size of float = 4 bytes
printf("Size of int=%lu bytes\n", sizeof(a)); Size of double = 8 bytes
printf("Size of float=%lu bytes\n", sizeof(b));
printf("Size of double=%lu bytes\n", sizeof(c)); Size of char = 1 byte
printf("Size of char=%lu byte\n", sizeof(d));

39

39

Operators Precedence in C
▸The concept of operator precedence and associativity in C helps in
determining which operators will be given priority when there are
multiple operators in the expression.
▸It is very common to have multiple operators in C language and the
compiler first evaluates the operator with higher precedence.
▸It helps to maintain the ambiguity of the expression and helps us in
avoiding unnecessary use of parenthesis.
Example
10 + 20 * 30

40

40

20
17/10/2023

Operator Precedence and Associativity Table


Precedence Operator Description Associativity
() Parentheses (function call)

[] Array Subscript (Square Brackets)


1 . Dot Operator Left-to-Right

-> Structure Pointer Operator


++ , — Postfix increment, decrement
++ / — Prefix increment, decrement
+/– Unary plus, minus

!,~ Logical NOT, Bitwise complement


2 (type) Cast Operator Right-to-Left

* Dereference Operator
& Addressof Operator
sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

41

41

Operator Precedence and Associativity Table


Cont.

Precedence Operator Description Associativity

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

< , <= Relational less than, less than or equal to


6 Left-to-Right
> , >= Relational greater than, greater than or equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

42

42

21
17/10/2023

Operator Precedence and Associativity Table


Cont.
Precedence Operator Description Associativity

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division assignment


14 Right-to-Left
%= , &= Modulus, bitwise AND assignment

^= , |= Bitwise exclusive, inclusive OR assignment

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right

43

43

Reviews
▸We have learned about the following topics so far:
1. Variables and Constants

2. Data Types

3. Input and Output in C programming

4. Operators

44

44

22
17/10/2023

Exercises
Write programs that:
1. to Add / Sum Two Numbers.

2. to Swap Values of Two Variables.

3. to Multiply two Floating Point Numbers

4. to convert feet to meter

5. to convert Celsius to Fahrenheit and vice versa

6. to find the Size of data types

7. to Print ASCII Value (tip: read character, print number of this char)

8. to Calculate Area of Circle

9. to Calculate Area of Square

10. to convert days to years, weeks and days

45

45

Thanks for your listening!

46

46

23

You might also like