Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
35 views

BCSC 1102 Introduction to Programming Lecture 2 Notes

Uploaded by

kintaxima
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
35 views

BCSC 1102 Introduction to Programming Lecture 2 Notes

Uploaded by

kintaxima
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

BCSC 1102 : Intro To Programming Week 2

Dr. Shem Mbandu Angolo, PhD

The Co-operatetive University of Kenya


September - December 2024

Contents
1 Basic Structure of a C Program 3
1.1 Preprocessor Directives . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Global Declarations . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 The main() Function . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Function Definitions . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Statements and Expressions . . . . . . . . . . . . . . . . . . . . . 4
1.7 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.8 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.9 Explanation of the Example . . . . . . . . . . . . . . . . . . . . . 5

2 Data Types 6
2.1 Basic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.1 Integer Types . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.2 Floating-Point Types . . . . . . . . . . . . . . . . . . . . . 7
2.1.3 Character Type . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2 Derived Data Types . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3 User-Defined Data Types . . . . . . . . . . . . . . . . . . . . . . 8

3 Variables in C 8
3.1 Variable Declaration . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 Variable Initialization . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3 Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 Local Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.5 Function Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.6 Block Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.7 Global Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.8 Static Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.8.1 Static Local Variables . . . . . . . . . . . . . . . . . . . . 11
3.8.2 Static Global Variables . . . . . . . . . . . . . . . . . . . 11
3.9 Register Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.10 Extern Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

1
4 Data Type Modifiers 13
4.1 Signed and Unsigned Modifiers . . . . . . . . . . . . . . . . . . . 13
4.1.1 Signed Integers . . . . . . . . . . . . . . . . . . . . . . . . 13
4.1.2 Unsigned Integers . . . . . . . . . . . . . . . . . . . . . . 13
4.2 Short and Long Modifiers . . . . . . . . . . . . . . . . . . . . . . 14
4.2.1 Short Integers . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.2 Long Integers . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.3 Combining Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.4 Storage Size and Value Ranges . . . . . . . . . . . . . . . . . . . 15

5 Constants and literals 16


5.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.1.1 const Keyword . . . . . . . . . . . . . . . . . . . . . . . . 16
5.1.2 #define Directive . . . . . . . . . . . . . . . . . . . . . . 16
5.1.3 Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.1.4 Constant Pointers . . . . . . . . . . . . . . . . . . . . . . 17
5.2 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.2.1 Integer Literals . . . . . . . . . . . . . . . . . . . . . . . . 17
5.2.2 Floating-Point Literals . . . . . . . . . . . . . . . . . . . . 18
5.2.3 Character Literals . . . . . . . . . . . . . . . . . . . . . . 18
5.2.4 String Literals . . . . . . . . . . . . . . . . . . . . . . . . 18
5.2.5 Boolean Literals . . . . . . . . . . . . . . . . . . . . . . . 18

6 Operators 20
6.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . 20
6.1.1 List of Arithmetic Operators . . . . . . . . . . . . . . . . 20
6.2 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . 21
6.3 List of Relational Operators . . . . . . . . . . . . . . . . . . . . . 21
6.4 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
6.4.1 List of Logical Operators . . . . . . . . . . . . . . . . . . 22
6.5 Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 22
6.5.1 List of Bitwise Operators . . . . . . . . . . . . . . . . . . 22
6.6 Operator Precedence and Associativity . . . . . . . . . . . . . . . 23
6.7 Precedence Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2
1 Basic Structure of a C Program
A C program follows a specific structure that includes several essential compo-
nents. Understanding the basic structure is crucial for writing well-organized
and functional C programs. Here are the primary elements of a C program:

1.1 Preprocessor Directives


Preprocessor directives are commands that are processed before the actual com-
pilation of the code begins. They usually include file inclusion and macro defi-
nitions. Preprocessor directives begin with a # symbol.
Example:
1 # include < stdio .h > // Preprocessor directive to
include standard I / O library

1.2 Global Declarations


These are declarations of variables or functions that can be accessed from any
part of the program. They are placed outside of all functions.
Example:
1 int globalVariable ; // Global variable declaration

1.3 The main() Function


The main() function is the entry point of every C program. It is where the
execution starts. The main() function can have two forms:
• int main(void) { ... }

• int main(int argc, char *argv[]) { ... }


The main() function typically returns an integer value, where 0 usually
signifies successful execution.
Example:
1 int main () {
2 // Code to be executed
3 return 0; // Return statement
4 }

3
1.4 Variable Declarations
Variables must be declared before they are used. Declarations can be within
the main() function or other functions. Variable declarations specify the type
and name of the variable.
Example:
1 int main () {
2 int a , b , sum ; // Variable declaration
3 return 0;
4 }

1.5 Function Definitions


Functions are blocks of code that perform specific tasks and can be called from
the main() function or other functions. Functions help in modularizing the
code.
Example:
1 int add ( int x , int y ) {
2 return x + y ; // Function to add two numbers
3 }

1.6 Statements and Expressions


Statements are the instructions that the program executes. Expressions are
combinations of variables, operators, and values that produce a result.
Example:
1 int main () {
2 int a = 5 , b = 10;
3 int sum = a + b ; // Expression
4 printf (" Sum : % d \ n " , sum ) ; // Statement
5 return 0;
6 }

1.7 Comments
Comments are non-executable parts of the code that provide explanations or an-
notations. They are ignored by the compiler. There are two types of comments
in C:
• Single-line comments (//)
• Multi-line comments (/* ... */)
Example:

4
1 // This is a single - line comment
2 /*
3 This is a
4 multi - line comment
5 */

1.8 Example
Here is a complete example of a basic C program that incorporates all the above
elements:
Code:
1 # include < stdio .h > // Include standard I / O library
2

3 // Global variable declaration


4 int globalVariable = 10;
5

6 // Function declaration
7 int add ( int x , int y ) ;
8

9 int main () {
10 // Local variable declarations
11 int a = 5 , b = 15;
12 int sum ;
13

14 // Function call
15 sum = add (a , b ) ;
16

17 // Print the result


18 printf (" Sum : % d \ n " , sum ) ;
19

20 // Return statement
21 return 0;
22 }
23

24 // Function definition
25 int add ( int x , int y ) {
26 return x + y ;
27 }

1.9 Explanation of the Example


1. Preprocessor Directive:
1 # include < stdio .h >

5
This line includes the Standard Input Output header file necessary for the
printf function.
2. Global Variable:
1 int globalVariable = 10;

This is a global variable that can be accessed by any function in the


program.
3. Function Declaration:
1 int add ( int x , int y ) ;

This declares a function named add that takes two integers as parameters
and returns an integer.
4. main() Function:
1 int main () {
2 int a = 5 , b = 15;
3 int sum ;
4 sum = add (a , b ) ;
5 printf (" Sum : % d \ n " , sum ) ;
6 return 0;
7 }

This is the entry point of the program where variables are declared, the
add function is called, and the result is printed.
5. Function Definition:
1 int add ( int x , int y ) {
2 return x + y ;
3 }

This defines the add function which adds two integers and returns the
result.

By following this structure, you can write well-organized and efficient C


programs.

2 Data Types
Understanding data types and variables is fundamental to programming in C.
Data types specify the type of data that a variable can hold, while variables are
used to store data that can be manipulated throughout the program.
C provides several built-in data types, which can be categorized into basic,
derived, and user-defined types.

6
2.1 Basic Data Types
Basic data types in C include:
• int: Used to store integers.

• float: Used to store single-precision floating-point numbers.


• double: Used to store double-precision floating-point numbers.
• char: Used to store single characters.

2.1.1 Integer Types


Integer types can be signed or unsigned and vary in size.

• short: Typically 2 bytes.


• int: Typically 4 bytes.
• long: Typically 4 or 8 bytes.
• long long: Typically 8 bytes.

Example:
1 short a ;
2 int b ;
3 long c ;
4 long long d ;

2.1.2 Floating-Point Types


Floating-point types are used for real numbers.

• float: Typically 4 bytes.


• double: Typically 8 bytes.
• long double: Typically 10, 12, or 16 bytes.

Example:
1 float x ;
2 double y ;
3 long double z ;

7
2.1.3 Character Type
Character type is used to store single characters.
• char: Typically 1 byte.
Example:
1 char ch = ’A ’;

2.2 Derived Data Types


Derived data types are built from the basic types.
• Arrays: Collection of elements of the same type.
• Pointers: Variables that store memory addresses.
• Functions: Blocks of code that perform specific tasks.

2.3 User-Defined Data Types


User-defined data types provide more flexibility.
• struct: Group of variables of different types.
• union: Group of variables sharing the same memory location.
• enum: Enumeration of named integer constants.
Example of struct:
1 struct Point {
2 int x ;
3 int y ;
4 };

3 Variables in C
Variables are used to store data that can be manipulated throughout the pro-
gram. A variable declaration specifies the type of data it can hold and allocates
memory for it.

3.1 Variable Declaration


A variable must be declared before it can be used.
1 int number ;
2 float salary ;
3 char grade ;

8
3.2 Variable Initialization
Variables can be initialized at the time of declaration.
1 int number = 10;
2 float salary = 5000.50;
3 char grade = ’A ’;

3.3 Variable Scope


In C programming, the scope of a variable refers to the region of the program
where the variable is accessible. Understanding variable scope is essential for
writing efficient and error-free code. Variable scope in C is categorized into
three main types: local scope, global scope, and block scope.

3.4 Local Scope


A variable declared inside a function or a block is known as a local variable.
Local variables are accessible only within the function or block where they are
declared. They are created when the function or block is entered and destroyed
when the function or block is exited.

3.5 Function Scope


Local variables declared inside a function are accessible only within that func-
tion.
Example:
1 # include < stdio .h >
2

3 void function () {
4 int localVar = 10; // Local variable
5 printf (" Local Variable in function : % d \ n " ,
localVar ) ;
6 }
7

8 int main () {
9 function () ;
10 // printf (" Local Variable in main : % d \ n " , localVar
) ; // This will cause an error
11 return 0;
12 }

9
3.6 Block Scope
Local variables can also be declared within a block, which is a set of statements
enclosed in curly braces ‘‘. Variables declared within a block are accessible only
within that block.
Example:
1 # include < stdio .h >
2

3 int main () {
4 int a = 10;
5

6 if ( a > 5) {
7 int b = 20; // Block scope
8 printf (" Block Variable : % d \ n " , b ) ;
9 }
10

11 // printf (" Block Variable : % d \ n " , b ) ; // This


will cause an error
12

13 return 0;
14 }

3.7 Global Scope


A variable declared outside all functions is known as a global variable. Global
variables are accessible from any function within the program. They are created
when the program starts and destroyed when the program ends.
Example:
1 # include < stdio .h >
2

3 int globalVar = 20; // Global variable


4

5 void function () {
6 printf (" Global Variable in function : % d \ n " ,
globalVar ) ;
7 }
8

9 int main () {
10 function () ;
11 printf (" Global Variable in main : % d \ n " , globalVar )
;
12 return 0;
13 }

10
3.8 Static Variables
Static variables retain their value between function calls. They can be declared
with local or global scope, but they are stored in the static memory area, which
is shared across multiple function calls.

3.8.1 Static Local Variables


Static local variables are declared inside a function with the ‘static‘ keyword.
They retain their value between function calls.
Example:
1 # include < stdio .h >
2

3 void function () {
4 static int count = 0; // Static local variable
5 count ++;
6 printf (" Count : % d \ n " , count ) ;
7 }
8

9 int main () {
10 function () ; // Output : Count : 1
11 function () ; // Output : Count : 2
12 function () ; // Output : Count : 3
13 return 0;
14 }

3.8.2 Static Global Variables


Static global variables are declared outside all functions with the ‘static‘ key-
word. They are accessible only within the file where they are declared.
Example:
1 # include < stdio .h >
2

3 static int globalVar = 20; // Static global variable


4

5 void function () {
6 printf (" Global Variable in function : % d \ n " ,
globalVar ) ;
7 }
8

9 int main () {
10 function () ;
11 printf (" Global Variable in main : % d \ n " , globalVar )
;
12 return 0;

11
13 }

3.9 Register Variables


Register variables are stored in the CPU registers instead of RAM for faster
access. They are declared with the ‘register‘ keyword. The use of register
variables is limited to local scope, and they cannot be referenced by pointers.
Example:
1 # include < stdio .h >
2

3 void function () {
4 register int i ;
5 for ( i = 0; i < 10; i ++) {
6 printf ("% d " , i ) ;
7 }
8 printf ("\ n ") ;
9 }
10

11 int main () {
12 function () ;
13 return 0;
14 }

3.10 Extern Variables


Extern variables are declared with the ‘extern‘ keyword to indicate that their
definition is in another file. They are used to share variables across multiple
files.
Example:
// File1.c
1 # include < stdio .h >
2

3 extern int globalVar ; // Extern variable declaration


4

5 void function () {
6 printf (" Global Variable in function : % d \ n " ,
globalVar ) ;
7 }

// File2.c
1 # include < stdio .h >
2

3 int globalVar = 20; // Global variable definition

12
4

5 int main () {
6 function () ;
7 printf (" Global Variable in main : % d \ n " , globalVar )
;
8 return 0;
9 }

Understanding variable scope in C is crucial for managing data and mem-


ory effectively. Local, global, static, register, and extern variables each have
unique properties that make them suitable for different situations. By knowing
how and where to declare variables, programmers can write more efficient and
maintainable code.

4 Data Type Modifiers


In C programming, data type modifiers are used to alter the properties of the
basic data types, giving the programmer more control over the storage and
behavior of variables. The primary data type modifiers in C include signed,
unsigned, short, and long.

4.1 Signed and Unsigned Modifiers


The signed and unsigned modifiers are used with integer types to specify
whether the variable can hold both positive and negative values (signed) or
only positive values (unsigned).

4.1.1 Signed Integers


By default, integer types (int, short, long) are signed, meaning they can store
both positive and negative values.
Example:
1 int a = -10; // Signed integer
2 short b = 30000; // Signed short integer
3 long c = -100000 L ; // Signed long integer

4.1.2 Unsigned Integers


The unsigned modifier is used to specify that a variable can only hold non-
negative values. This effectively doubles the maximum value that the variable
can store.
Example:
1 unsigned int a = 10; // Unsigned integer
2 unsigned short b = 60000; // Unsigned short integer

13
3 unsigned long c = 100000 UL ; // Unsigned long integer

4.2 Short and Long Modifiers


The short and long modifiers are used to change the storage size of integer
types.

4.2.1 Short Integers


The short modifier reduces the storage size of the integer type.
Example:
1 short int a = 1000; // Short integer
2 short b = 2000; // Short integer ( int can be omitted )

4.2.2 Long Integers


The long modifier increases the storage size of the integer type. When used
with double, it increases the precision.
Example:
1 long int a = 100000 L ; // Long integer
2 long b = 200000 L ; // Long integer ( int can be omitted
)
3 long long c = 100000000000 LL ; // Long long integer
4

5 double x = 3.14;
6 long double y = 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 L ; // Long double
for higher precision

4.3 Combining Modifiers


Data type modifiers can be combined to achieve the desired storage size and
value range.

Example Combinations

1 unsigned short int a = 50000; // Unsigned short


integer
2 long long int b = 100000000000 LL ; // Long long
integer
3 unsigned long int c = 4000000000 UL ; // Unsigned long
integer

14
4.4 Storage Size and Value Ranges
The storage size and value ranges of the modified data types depend on the
system architecture (32-bit vs. 64-bit) and the compiler. Here is a general
overview of the typical sizes and ranges:

• short: 2 bytes, range: -32,768 to 32,767 (signed), 0 to 65,535 (un-


signed)
• int: 4 bytes, range: -2,147,483,648 to 2,147,483,647 (signed), 0 to
4,294,967,295 (unsigned)
• long: 4 or 8 bytes, range: depends on the system
• long long: 8 bytes, range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
(signed), 0 to 18,446,744,073,709,551,615 (unsigned)
• float: 4 bytes, range: 1.2E-38 to 3.4E+38
• double: 8 bytes, range: 2.3E-308 to 1.7E+308
• long double: 10, 12, or 16 bytes, range: depends on the system

Examples and Usage


Here are some practical examples of using data type modifiers in C programs.

Example 1: Unsigned Integers

1 # include < stdio .h >


2

3 int main () {
4 unsigned int a = 3000000000 U ;
5 printf (" Unsigned int : % u \ n " , a ) ;
6 return 0;
7 }

Example 2: Long Doubles

1 # include < stdio .h >


2

3 int main () {
4 long double pi = 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 L ;
5 printf (" Long double : %.20 Lf \ n " , pi ) ;
6 return 0;
7 }

15
Example 3: Combining Modifiers

1 # include < stdio .h >


2

3 int main () {
4 unsigned long long int largeNumber =
1 8 4 4 6 7 4 4 0 7 3 7 0 9 5 5 1 6 1 5 ULL ;
5 printf (" Unsigned long long int : % llu \ n " ,
largeNumber ) ;
6 return 0;
7 }

Data type modifiers in C provide additional control over the storage size and
value range of variables. By using signed, unsigned, short, and long modifiers,
programmers can optimize memory usage and ensure that variables can hold the
required range of values. Understanding and utilizing these modifiers effectively
is crucial for writing robust and efficient C programs.

5 Constants and literals


Constants and literals are fundamental components of the C programming lan-
guage. They represent fixed values that do not change during the execution of a
program. Understanding how to use constants and literals effectively is crucial
for writing robust and maintainable code.

5.1 Constants
Constants are variables whose value cannot be changed once defined. They are
used to represent fixed values that remain the same throughout the program.

5.1.1 const Keyword


The const keyword is used to declare constant variables. Once a variable is
declared as const, its value cannot be modified.
Example:
1 const int MAX_SIZE = 100;
2 const float PI = 3.14;

5.1.2 #define Directive


The #define preprocessor directive is another way to define constants. It is
commonly used for defining constant values and macros.
Example:

16
1 # define MAX_SIZE 100
2 # define PI 3.14

5.1.3 Enumerations
Enumerations (enum) are user-defined data types that consist of named integer
constants. They are used to assign names to integral constants, making the
code more readable.
Example:
1 enum Days { SUNDAY , MONDAY , TUESDAY , WEDNESDAY ,
THURSDAY , FRIDAY , SATURDAY };

5.1.4 Constant Pointers


Pointers can also be declared as constants. A constant pointer can either be a
pointer to a constant value or a constant pointer to a variable.
Example:
1 const int * ptr1 ; // Pointer to a constant integer
2 int * const ptr2 = & var ; // Constant pointer to an
integer

5.2 Literals
Literals are fixed values used directly in the code. They can be of various types,
including integer, floating-point, character, and string literals.

5.2.1 Integer Literals


Integer literals represent whole numbers without any fractional part. They can
be specified in different bases:
• Decimal (base 10)
• Octal (base 8, prefixed with 0)
• Hexadecimal (base 16, prefixed with 0x)

Example:
1 int decimal = 100;
2 int octal = 0144; // Octal representation of 100
3 int hexadecimal = 0 x64 ; // Hexadecimal representation
of 100

17
5.2.2 Floating-Point Literals
Floating-point literals represent real numbers with a fractional part. They can
be written in either decimal form or exponential (scientific) notation.
Example:
1 float decimalFloat = 3.14;
2 double scientificFloat = 1.23 e4 ; // 1.23 * 10^4

5.2.3 Character Literals


Character literals represent single characters enclosed in single quotes. They
can also represent escape sequences.
Example:
1 char letter = ’A ’;
2 char newline = ’\n ’; // Newline character
3 char tab = ’\t ’; // Tab character

5.2.4 String Literals


String literals represent sequences of characters enclosed in double quotes. They
are stored as arrays of characters with a null terminator (\0).
Example:
1 char greeting [] = " Hello , World !";

5.2.5 Boolean Literals


In C, boolean literals are represented by the integers 0 (false) and 1 (true). The
stdbool.h header file can be included to use the bool data type and the true
and false literals.
Example:
1 # include < stdbool .h >
2

3 bool flag = true ;

Examples and Usage


Using Constants in a Program
Example:

18
1 # include < stdio .h >
2

3 # define PI 3.14
4

5 int main () {
6 const int radius = 5;
7 float area ;
8

9 area = PI * radius * radius ;


10 printf (" Area of the circle : % f \ n " , area ) ;
11

12 return 0;
13 }

Using Literals in a Program


Example:
1 # include < stdio .h >
2

3 int main () {
4 int decimal = 100;
5 int octal = 0144;
6 int hexadecimal = 0 x64 ;
7 float decimalFloat = 3.14;
8 double scientificFloat = 1.23 e4 ;
9 char letter = ’A ’;
10 char greeting [] = " Hello , World !";
11 bool flag = true ;
12

13 printf (" Decimal : % d \ n " , decimal ) ;


14 printf (" Octal : % o \ n " , octal ) ;
15 printf (" Hexadecimal : % x \ n " , hexadecimal ) ;
16 printf (" Floating Point : % f \ n " , decimalFloat ) ;
17 printf (" Scientific Notation : % e \ n " ,
scientificFloat ) ;
18 printf (" Character : % c \ n " , letter ) ;
19 printf (" String : % s \ n " , greeting ) ;
20 printf (" Boolean : % d \ n " , flag ) ;
21

22 return 0;
23 }

Constants and literals are essential for defining fixed values in C programs.
Constants provide a way to define immutable values, improving code readability

19
and maintainability. Literals represent fixed values directly in the code and come
in various forms such as integers, floating-point numbers, characters, and strings.
Understanding and using constants and literals effectively is fundamental to
writing robust and efficient C programs.

6 Operators
Operators are special symbols in C that perform operations on variables and
values. They are used to manipulate data and variables and form the backbone
of any programming language. In C, operators are classified into several types,
including arithmetic, relational, logical, and bitwise operators.

6.1 Arithmetic Operators


Arithmetic operators are used to perform basic mathematical operations such
as addition, subtraction, multiplication, division, and modulus.

6.1.1 List of Arithmetic Operators


• Addition (+): Adds two operands.
• Subtraction (-): Subtracts the second operand from the first.
• Multiplication (*): Multiplies two operands.

• Division (/): Divides the first operand by the second.


• Modulus (%): Returns the remainder of the division of the first operand
by the second.
• Increment (++): Increases an integer value by one.

• Decrement (–): Decreases an integer value by one.

Examples

1 int a = 10 , b = 5 , result ;
2

3 result = a + b; // Addition : result is 15


4 result = a - b; // Subtraction : result is 5
5 result = a * b; // Multiplication : result is 50
6 result = a / b; // Division : result is 2
7 result = a % b; // Modulus : result is 0
8

9 a ++; // Increment : a is now 11


10 b - -; // Decrement : b is now 4

20
6.2 Relational Operators
Relational operators are used to compare two values. They return either true
(1) or false (0).

6.3 List of Relational Operators


• Equal to (==): Checks if two operands are equal.
• Not equal to (!=): Checks if two operands are not equal.

• Greater than (¿): Checks if the left operand is greater than the right
operand.
• Less than (¡): Checks if the left operand is less than the right operand.
• Greater than or equal to (¿=): Checks if the left operand is greater
than or equal to the right operand.

• Less than or equal to (¡=): Checks if the left operand is less than or
equal to the right operand.

Examples

1 int a = 10 , b = 5;
2 int result ;
3

4 result = ( a == b ) ; // Equal to : result is 0 ( false )


5 result = ( a != b ) ; // Not equal to : result is 1 ( true
)
6 result = ( a > b ) ; // Greater than : result is 1 ( true
)
7 result = ( a < b ) ; // Less than : result is 0 ( false )
8 result = ( a >= b ) ; // Greater than or equal to :
result is 1 ( true )
9 result = ( a <= b ) ; // Less than or equal to : result
is 0 ( false )

6.4 Logical Operators


Logical operators are used to perform logical operations and return true or false
based on the logical relationship between the operands.

21
6.4.1 List of Logical Operators
• Logical AND (&&): Returns true if both operands are true.
• Logical OR (——): Returns true if at least one of the operands is true.
• Logical NOT (!): Returns true if the operand is false and vice versa.

Examples

1 int a = 1 , b = 0;
2 int result ;
3

4 result = ( a && b ) ; // Logical AND : result is 0 ( false


)
5 result = ( a || b ) ; // Logical OR : result is 1 ( true )
6 result = !a; // Logical NOT : result is 0 ( false
)
7 result = !b; // Logical NOT : result is 1 ( true )

6.5 Bitwise Operators


Bitwise operators are used to perform bit-level operations on integer types. They
manipulate individual bits of the operands.

6.5.1 List of Bitwise Operators


• Bitwise AND (&): Performs a bitwise AND operation.
• Bitwise OR (—): Performs a bitwise OR operation.
• Bitwise XOR (ˆ): Performs a bitwise XOR operation.
• Bitwise NOT (˜): Performs a bitwise NOT operation.
• Left shift (¡¡): Shifts bits to the left.
• Right shift (¿¿): Shifts bits to the right.

Examples

1 int a = 5 , b = 3; // a = 0101 , b = 0011 in binary


2 int result ;
3

4 result = a & b ; // Bitwise AND : result is 1 (0001 in


binary )
5 result = a | b ; // Bitwise OR : result is 7 (0111 in
binary )

22
6 result = a ^ b ; // Bitwise XOR : result is 6 (0110 in
binary )
7 result = ~ a ; // Bitwise NOT : result is -6
(1111...1010 in binary )
8 result = a << 1; // Left shift : result is 10 (1010 in
binary )
9 result = a >> 1; // Right shift : result is 2 (0010 in
binary )

6.6 Operator Precedence and Associativity


Operator precedence determines the order in which operators are evaluated in
an expression. Operators with higher precedence are evaluated before operators
with lower precedence. Associativity determines the order in which operators
of the same precedence are evaluated.

6.7 Precedence Table


• Highest: () [] -> .
• Unary: + - ++ -- ! ~

• Multiplicative: * / %
• Additive: + -
• Shift: << >>
• Relational: < <= > >=

• Equality: == !=
• Bitwise AND: &
• Bitwise XOR: ^

• Bitwise OR: |
• Logical AND: &&
• Logical OR: ||
• Conditional: ?:

• Assignment: = += -= *= /= %= &= ^= |= <<= >>=


• Lowest: ,

23
Examples

1 int a = 10 , b = 5 , c = 2;
2 int result ;
3

4 result = a + b * c ; // Multiplication has higher


precedence than addition : result is 20
5 result = ( a + b ) * c ; // Parentheses change the order
of evaluation : result is 30
6

7 result = a < b && b < c ; // Relational operators have


higher precedence than logical AND : result is 0 (
false )
8 result = a == b || b == c ; // Equality operators have
higher precedence than logical OR : result is 0 (
false )

24

You might also like