0% found this document useful (0 votes)
12 views30 pages

editedNOTES-PPSUnit1-docx

C is a structured programming language developed in 1972 by Dennis Ritchie, known for its efficiency, modularity, and portability, making it suitable for both system and application-level programming. It features a rich library support and direct memory management through pointers, and is widely used in various applications including operating systems, embedded systems, and database management. Despite its declining usage, C remains foundational in the development of many modern programming languages and software applications.

Uploaded by

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

editedNOTES-PPSUnit1-docx

C is a structured programming language developed in 1972 by Dennis Ritchie, known for its efficiency, modularity, and portability, making it suitable for both system and application-level programming. It features a rich library support and direct memory management through pointers, and is widely used in various applications including operating systems, embedded systems, and database management. Despite its declining usage, C remains foundational in the development of many modern programming languages and software applications.

Uploaded by

eshanlodi36
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

What is C Language?

C is considered a structured programming language that supports both low-level and high-level
programming, making it adaptable for both system and application-level programming. It is also recognized
as a middle-level language that combines the attributes of both assembly-level and high-level languages.

Features of C
The C programming language possesses numerous features that make it a prime option for creating system-
level software applications. Below are some of its notable features of C language:

 Modularity – Modularity is a key feature of C that enables developers to write code in small,
reusable modules. This makes it simpler to maintain and debug the code.
 Efficiency – C is a programming language that is highly esteemed for its remarkable efficiency. It is
capable of running at a low level and granting developers an unparalleled level of control over system
resources. This exceptional degree of control is made possible through its profound comprehension of
the underlying hardware, enabling it to optimize and streamline operations with exquisite precision.
As a result, C language is widely acknowledged as a high-performance language that serves as an
indispensable tool for programmers striving to maximize their efficiency and control over intricate
systems.
 Portability – The programming language C provides developers with the ability to write code that
operates at a low level, which grants them greater influence over the hardware that the code is
running on.
 Modularity – C is endowed with the capability to accommodate modular programming techniques,
which ultimately allows for intricate programs to be dissected into smaller, more manageable
functions or modules. This programming paradigm is particularly advantageous as it facilitates
improved code readability, fosters code reuse, and encourages code maintainability.
 Rich Library Support – C, the programming language, has a large library of pre-existing functions
that can be used to help create robust software.
 Memory Management – C provides direct access to memory through pointers, enabling efficient
manipulation and allocation of memory.


History of C Language
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPL, etc.

Initially, C language was developed to be used in UNIX operating system. It inherits many features
of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C language.
Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

C Basic Commands

Commands
Functions

This is the main header file


preprocessor function, which
preprocesses standard input and
#include
output header files from the C
library repository, such as stdio.h
before compiling the program

This C statement, like most


programming languages, is the main
function, which is the point where
void main() the program execution begins. Once
the primary main () has been
executed, all other methods and
functions are performed.
Curly braces are a type of bracket
that can be seen in any computer
{ language, not just C. This represents
the start of a method or function
definition.

The text inside the /* and */ tags


will be considered as comments and
will not be executed or compiled.
/* explanation of C code */
This is to provide the coder with a
clear knowledge of the code and its
application or use.

The output is printed to the console


Printf()
screen using this C command.

This function is being used to wait


getch() for the user's input.it hold output
window.

This C function returns 0 after


return 0 terminating the C program or main
function.

The function or method block is


}
closed with these curly braces.

These are called single line


comments, and they are utilized not
//
only in the C programming
language but in others as well.
This is the function for using a
horizontal tab or an empty tab. This
\t belongs to the group of escape
sequences and is used to format the
programme.

This is the integer type character's


%d
format specifier.

The user data is taken from the


scanf() usual console terminal window
using this C function.

Let’s write a simple C program using above operators to print hello world:-

#include <stdio.h>

#include<conio.h>

void main()

printf("\n Hello World \n");

getch();

Explanation of above code:

As it can be easily seen, the programme starts with a #. Any line in the C programming language that begins
with a # is handled with by the preprocessor at the first stage of the program's execution, the first thing that
happens during compilation of this programme is that the line beginning with # is replaced by whatever is in
the stdio.h header file.

The following line is 'void main'. This is the start of a function called main, which takes no arguments (void).
It's important to note that every C programme we'll see contains one or more functions. The 'main' function is
where the program's execution begins once it has been run. While all other functions are called from within
main or other functions (allowing us to customize the order in which they are called), main is called first
from within the system.

After that, you'll notice a curly bracket ({). This essentially determines a function's initial scope. Usually,
near the end, you'll notice a reverse curly bracket (}), which indicates the function's end of scope. All of the
instructions contained within these brackets are handled as a portion of the function's body.

In the body of the main function, there are two lines of code. 'printf("\n Hello World \n"); . Printf is a
function in the system library that outputs formatted strings to standard input output function. It prints any
type of message inside double quotes (" ") except escape sequences (such as '\n', which is converted to a
newline). Ultimately, we may expect this code to produce 'Hello World' as its output.

Applications of C Program
It is a true fact that C is one of the oldest and most fundamental languages which is widely used across the
world. C is fast, portable, and has a rich library. C is a middle-level language but it has benefits of low-level
languages as well as high-level languages. And it is sad to hear that the use of C programming is decreasing
day by day. C has left its mark in almost every domain. C is mainly used to develop applications and for
system development work.

Real-World Applications of C
Use of the C programming language is not limited to the development of operating systems and applications.
It is also used in GUI development, IDE development, etc.

Some uses of C programming language:-

1. Operating Systems

2. Assemblers

3. Text Editors

4. Print Spoolers

5. Modern Programs

6. Databases

7. Utilities

Some exciting real-world applications of C.

1. Operating Systems:-

What is better than writing your own operating system? And yes, with the help of the C programming
language, you can write your own operating system. Windows Kernel, Linux Kernel and Apple’s OS X
kernel are mostly written in C.
2. GUI:-

It stands for Graphical User Interface. The C programming language also helps in developing popular adobe
softwares like Photoshop, Premier Pro, Illustrator etc.

3. Embedded Systems:-

In daily life, we use different embedded systems like coffee machines, microwaves, climate control systems
etc. These all are mostly programmed in C.

4. Database:-
The C programming language helps in developing the popular database management system, MySQL.

5. Ease of Computation:-

C provides faster computation in programs. The implementation of algorithms and data structures is swift in
C. With the help of C, you can perform high degree calculations such as MATLAB, Mathematics etc.

6. Gaming:-

C programming is relatively faster than Java or Python. It has been used in various gaming applications and
graphics. C programming language also helps in creating many popular childhood games like Tic-Tac-Toe,
The Snake game etc.

7. Development of New languages:-

Due to the fast execution and simplicity, many languages like Java, C++, Python, PHP, PERL, JavaScript,
etc were influenced by the development of C. In Python, C is used for building standard libraries. The syntax
and control structures of PERL, PHP and C++ are based upon the C programming language.

8. Google:-
In the Google open source community, the projects are being handled by C/C++. And C/C++ also helped in
developing Google file system and chromium browser.

9. Assemblers:-
Mainly used to translate Assembly language to Machine language. C also helped in
developing GNU assembler.

10. Text Editors:-

C also helped in creating various text editors like Vim, Gedit etc.

11. Drivers:-

Another application of C is to write driver software like Keyboard driver, Network driver, mouse driver etc.

12. Interpreters:-

With the help of C programming language, you can create language interpreters. C helped in developing
different programming language interpreters like Python and MATLAB interpreters etc.
13. Network Devices:-

Another application of C is to design network devices.

14. Compiler Design:-

C also helped in designing several popular compilers like C Lang C, MINGW, Apple C etc. This is one of the
most popular uses of C language.

C - Program Structure
The structure of a C program consists of the following sections:

1. Documentation section / comment section

2. Preprocessor directives / Header files

3. Global variables

4. Main function

5. Executable Part/expression

6. User-define function

Overview of the basic structure of a C program


In the basic structure of a C program given above, we first have the documentation section, where
we provide comments about the program, its author, and other details. This is followed by the
preprocessor directives or the header files section, where we include the header files needed for
our program.

Next, we declare the global variables that are accessible throughout the program. After that, we
have the main function where the execution of the program starts. Inside the main function, we
write our statements and expressions. At the end of the main function, we return an integer value,
usually 0, to indicate that the program has ended successfully, and then in executable part we
define our logic of code. Finally, we define any user define functions we may need in our program.
These functions can be called from the main() function or from any other function in the program.

1. Documentation section: The documentation section consists of a set of comment lines giving the
name of the program, the author, and other details, which the compiler ignores

2. Preprocessor directives / Header files: These are the lines in the program that start with '#'. As we
discussed earlier, they are used to include header files in the program.

3. Global variables: These variables are declared outside all the functions and can be accessed from any
program part.

4. Main function: Every C program must have one main function. The execution of the program starts
from the main function.
5. User-define functions: These are the additional functions you write for your program. They must be
declared and defined in your program before you use them.

Example:
// Documentation section
// Program to calculate the area of a circle
// Header files
#include <stdio.h>

// Global variable
#define PI 3.14159

// Function to calculate the area of a circle


double calculateArea(double radius)
{
return PI * radius * radius;
}

// Main function
int main() {
double radius, area;
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
area = calculateArea(radius);
printf("The area of the circle is: %.2lf\n", area);
return 0;}

The C character set


A character set in C Programming Language is set of all valid character which is used to form a words,
numbers and expression’s in source program.

The character set is fundamental raw material of any language and they are used to represent information like
natural language, computer language will also have well defined Character set, that is useful to build the
programs.

Now, in this section we learn about the type of the Character set and discuss about all type of it in brief.

Type of C character set

There are four type of character set in C programming.

 Alphabets
 Digit
 Special Character

White space Alphabets :


Alphabets has a two case.

1. Upper case A-Z


2. Lower case a-z.

In C programming, small letters and capital letters are distinct.

Digit

C programming support 10 digit which are used to construct numerical value.

 Digit 0-9.

Alphabets ASCII Code Alphabets ASCII Code

A 65 a 97

B 66 b 98

C 67 c 99

D 68 d 100

E 69 e 101

F 70 f 102

G 71 g 103

H 72 h 104

I 73 i 105

J 74 j 106

K 75 k 107

L 76 l 108

M 77 m 109

N 78 n 110

O 79 o 111

P 80 p 112
Q 81 q 113

R 82 r 114

S 83 s 115

T 84 t 116

U 85 u 117

V 86 v 118

W 87 w 119

X 88 x 120

Y 89 y 121

Z 90 z 122

Alphabets ASCII Code

0 48

1 49

2 50

3 51

4 52

5 53

6 54

7 55

8 56

9 57

Special character

C programming supports set of special symbols that include symbols to perform mathematical operation,
check condition and other special symbol.

 Special character %, &, *, .


Special Character ASCII Code Special Character ASCII Code

~ 126 – 45

! 33 _ 95

@ 64 + 43

# 35 = 61

$ 36 { 123

% 37 } 125

& 38 | 124

* 42 \ 92

( 40 ; 58

) 41 : 59

‘ 39 / 47

“ 34 ? 63

62
< 60 >

White space

In computer programming, white space is a character that represent vertical space in typography.

 White space \b,\v,\? and so on.

White Space Meaning White Space Meaning

\b blank space \\ back slash

\t horizontal tab \’ single quote

\v vertical tab \” double quote

\r carriage return \? Question mark

\f form feed \0 null


\n new line \a alarm (bell)

Variables in C

A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be
reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:


The example of declaring the variable is given below:

1. int a;
2. float b;
3. char c;

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

1. int a=10,b=20; //declaring 2 variable of integer type


2. float f=20.8;
3. char c='A';

Rules for defining variables


o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:


1. int 2;
2. int a b;
3. int long;

Types of Variables in C

There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1(){
int x=10;//local variable
}
we must have to initialize the local variable before it is used.

Example: // C program to declare and print local variable inside a function.

#include <stdio.h>
void function()
{
int x = 10; // local variable
printf("%d", x);
}
int main()
{
function(); }

Global Variable
A variable that is declared outside the function or block is called a global variable. Any function can change
the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable


void function1(){
int x=10;//local variable
}// C program to demonstrate use of static variable
#include <stdio.h>

void function()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\tStatic: %d\n", x, y);
}

int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}
Example: // C program to demonstrate use of global variable
#include <stdio.h>
int x = 20; // global variable
void function1() {
printf("Function 1: %d\n", x); }

void function2() {
printf("Function 2: %d\n", x); }

int main()
{
function1();
function2();
return 0;
}

Static Variable
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If you call this function many times, the local variable will print the same value for each function call, e.g,
11,11,11 and so on. But the static variable will print the incremented value in each function call, e.g. 11,
12, 13 and so on.

Example:// C program to demonstrate use of static variable


#include <stdio.h>
void function()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\tStatic: %d\n", x, y);
}

int main(){
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}

Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We can explicitly
declare an automatic variable using auto keyword.
void main(){
int x=10;//local variable (also
automatic)auto int y=20;//automatic
variable
}

Example:// C program to demonstrate use of automatic variable


#include <stdio.h>
void function()
{
int x = 10; // local variable (also automatic)
auto int y = 20; // automatic variable
printf("Auto Variable: %d", y);
}
int main()
{

function();
return 0;
}
External Variable

We can share a variable in multiple C source files by using an external variable. To declare an external
variable, you need to use extern keyword.

myfile.h

extern int x=10;//external variable (also global)


Program (Example) :
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void


Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32
reserved words (keywords) in the C language.

A list of 32 keywords in the c language is given below:

auto break case char const continue default Do

double else enum extern float for goto If

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

We will learn about all the C language keywords later.

C Identifiers

C identifiers represent the name in the C program, for example, variables, functions, arrays, structures, unions, labels,
etc. An identifier can be composed of letters such as uppercase, lowercase letters, underscore, digits, but the starting
letter should be either an alphabet or an underscore. If the identifier is not used in the external linkage, then it is
called as an internal identifier. If the identifier is used in the external linkage, then it is called as an external identifier.

We can say that an identifier is a collection of alphanumeric characters that begins either with an alphabetical
character or an underscore, which are used to represent various programming elements such as variables,
functions, arrays, structures, unions, labels, etc. There are 52 alphabetical characters (uppercase and
lowercase), underscore character, and ten numerical digits (0-9) that represent the identifiers. There is a total
of 63 alphanumerical characters that represent the identifiers.

Rules for constructing C identifiers


o The first character of an identifier should be either an alphabet or an underscore, and then it can be
followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers
are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifiers

total, sum, average, _m _, sum_1, etc.

Types of identifiers
o Internal identifier
o External identifier

Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal identifier. The internal
identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier. The external
identifiers can be function names, global variables.

Differences between Keyword and Identifier

Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It must be written in a lowercase letter. It can be written in both lowercase and uppercase letters.

Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.

It is a combination of alphabetical characters. It is a combination of alphanumeric characters.

It does not contain the underscore character. It can contain the underscore character.

Let's understand through an example.

int main()

int a=10;
int A=20;
printf("Value of a is : %d",a);
printf("\nValue of A is :%d",A);
return 0;
}

Output

Value of a is : 10
Value of A is :20

The above output shows that the values of both the variables, 'a' and 'A' are different. Therefore, we conclude
that the identifiers are case sensitive.

Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c
programming" etc.

There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program" etc.

2 ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor

1) C const keyword

The const keyword is used to define constant in C programming.

const float PI=3.14;


Now, the value of PI variable can't be changed.

#include<stdio.h>
int main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}

Output: The value of PI is: 3.140000


If you try to change the the value of PI, it will render compile time error.

#include<stdio.h>
int main(){
const float PI=3.14;
PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}

Output:

Compile Time Error: Cannot modify a const object

2) C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data
type.

Syntax:

#define token value

Let's see an example of #define to define a constant.

#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
}
Let's see an example of #define to create a macro.
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
Output: Minimum between 10 and 20 is: 10

Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string
literal, or a symbol. For example, the following C statement consists of five tokens –
printf("Hello, World! \n");

Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program.
They precede the type that they modify. We have four different storage classes in a C program –
 auto
 register
 static
 extern

The auto Storage Class


The auto storage class is the default storage class for all local variables.

The register Storage Class


The register storage class is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word) and can't have
the unary '&' operator applied to it (as it does not have a memory location).
The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'register' does not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope. Therefore,
making local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope
to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member to be
shared by all the objects of its class.

The extern Storage Class


The extern storage class is used to give a reference of a global variable that is visible to ALL the program
files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a
storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other
files, then extern will be used in another file to provide the reference of defined variable or function. Just for
understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global
variables or functions

Operators in C
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C
language is rich in built-in operators and provides the following types of operators −
 Arithmetic Operators
 Assignment Operators
 Relational Operators
 Logical Operators
 Unary Operators
 Bitwise Operators
 Ternary/Conditional operators
 Special Operators.
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume variable A holds
10 and variable B holds 20 then –

Description Example
Operator

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B% A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

// C program to demonstrate syntax of binary arithmetic


// operators
#include <stdio.h>
int main()
{

int a = 10, b = 4, res;

// printing a and b
printf("a is %d and b is %d\n", a, b);

res = a + b; // addition

printf("a + b is %d\n", res);


res = a - b; // subtraction
printf("a - b is %d\n", res);
res = a * b; // multiplication

printf("a * b is %d\n", res);


res = a / b; // division

printf("a / b is %d\n", res);


res = a % b; // modulus

printf("a %% b is %d\n", res);


return 0;
}

Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then –

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not. If the values are (A != B)
not equal, then the condition becomes true. is true.

> Checks if the value of left operand is greater than the value of right (A > B)
operand. If yes, then the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right (A < B)
operand. If yes, then the condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the value (A >= B)
of right operand. If yes, then the condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the value of (A <= B)
right operand. If yes, then the condition becomes true. is true.

Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then –

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then (A &&
the condition becomes true. B) is
false.

|| Called Logical OR Operator. If any of the two operands is non-zero, (A || B)


then the condition becomes true. is true.

! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it B) is
false. true.

Bitwise Operators
Bitwise operators works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101

A&B = 0000 1100


A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B'
holds 13, then –

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (A & B)
operands. = 12,
i.e., 0000
1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) =


61, i.e.,
0011
1101

^ Binary XOR Operator copies the bit if it is set in one operand but not (A ^ B)
both. = 49,
i.e., 0011
0001

~ (~A ) =
Binary One's Complement Operator is unary and has the effect of ~(60),
'flipping' bits. i.e,. -
0111101

<< Binary Left Shift Operator. The left operands value is moved left by the A << 2 =
number of bits specified by the right operand. 240 i.e.,
1111
0000

>> Binary Right Shift Operator. The left operands value is moved right by A >> 2 =
the number of bits specified by the right operand. 15 i.e.,
0000
1111

Assignment Operators
The following table lists the assignment operators supported by the C language –

Operator Description Example

= Simple assignment operator. Assigns values from right side operands to C=A+
left side operand B will
assign the
value of
A + B to
C

+= Add AND assignment operator. It adds the right operand to the left C += A is
operand and assign the result to the left operand. equivalent
to C = C
+A

-= Subtract AND assignment operator. It subtracts the right operand from C -= A is


the left operand and assigns the result to the left operand. equivalent
to C = C -
A

*= Multiply AND assignment operator. It multiplies the right operand with C *= A is


the left operand and assigns the result to the left operand. equivalent
to C = C
*A

/= Divide AND assignment operator. It divides the left operand with the C /= A is
right operand and assigns the result to the left operand. equivalent
to C = C /
A

%= Modulus AND assignment operator. It takes modulus using two C %= A


operands and assigns the result to the left operand. is
equivalent
to C = C
%A

<<= Left shift AND assignment operator. C <<= 2


is same as
C = C <<
2

>>= Right shift AND assignment operator. C >>= 2


is same as
C = C >>
2

&= Bitwise AND assignment operator. C &= 2 is


same as C
=C&2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is


same as C
=C^2

|= Bitwise inclusive OR and assignment operator. C |= 2 is


same as C
=C|2

Special Operators ↦ sizeof & ternary


Besides the operators discussed above, there are a few other important operators including sizeof() and

? : supported by the C Language.

Operator Description Example

sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 2.

& &a; returns the actual address of the


Returns the address of a variable.
variable.

* Pointer to a variable. *a;

?: If Condition is true? then value X :


Conditional Expression.
otherwise value Y

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has
a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom.
Within
Category Operator Associativity an
expressi
on,
Postfix () [] -> . ++ - - Left to right higher
precede
Unary + - ! ~ ++ - - (type)* & sizeof Right to left nce
operator
s will be
Multiplicative */% Left to right evaluate
d first.
Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

You might also like