0% found this document useful (0 votes)
3 views

unit-1 Introduction to c

C is a procedural programming language developed by Dennis Ritchie in 1972, primarily for system programming and writing the UNIX operating system. It is known for its speed, efficiency, and versatility, making it a foundational language for learning other programming languages. The document also discusses features of C, differences between high-level and low-level languages, algorithms, flowcharts, and the roles of compilers and interpreters.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

unit-1 Introduction to c

C is a procedural programming language developed by Dennis Ritchie in 1972, primarily for system programming and writing the UNIX operating system. It is known for its speed, efficiency, and versatility, making it a foundational language for learning other programming languages. The document also discusses features of C, differences between high-level and low-level languages, algorithms, flowcharts, and the roles of compilers and interpreters.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Introduction to c

C is a procedural programming language initially developed by Dennis Ritchie


in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed
as a system programming language 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
Features of C Programming Language:

1. Procedural Language

1
2. Fast and Efficient
3. Modularity
4. Statically Type
5. General-Purpose Language
6. Rich set of built-in Operators
7. Libraries with rich Functions
8. Middle-Level Language
9. Portability
10.Easy to Extend

Procedural Language: In a procedural language like C step by step


predefined instructions are carried out. C program may contain more than one
function to perform a particular task.
Fast and Efficient: Newer languages like java, python offer more features
than c programming language but due to additional processing in these
languages, their performance rate gets down effectively.
C programming language is the middle-level language provides programmers
access to direct manipulation with the computer hardware but higher-level
languages do not allow this.
That’s one of the reasons C language is considered the first choice to start
learning programming languages. It’s fast because statically typed languages
are faster than dynamically typed languages.
Modularity: The concept of storing C programming language code in the
form of libraries for further future use is known as modularity. This
programming language does very little on its own most of its power is held by
its libraries. C language has its own library to solve common problems like in
this way, we can use a particular function by using a header file stored in its
library.
Statically Type: C programming language is a statically typed language.
Meaning the type of variable is checked at the time of compilation but not at
run time. This means each time a programmer type a program they have to
mention the type of variables used.
General Purpose Language: From system programming to photo editing
software, the C programming language is used in various applications. Some
of the common applications where it’s used are as follows:
 Operating systems: Windows, Linux, iOS, Android, OXS

2
 Databases: PostgreSQL, Oracle, MySQL, MS SQL Server etc.
Rich set of built-in Operators: It is a diversified language with a rich set of
built-in operators which are used in writing complex or simplified C
programs.

Libraries with rich Functions: Robust libraries and functions in C help even
a beginner coder to code with ease.

Middle-Level Language: As it is a middle-level language so it has the


combined form of both capabilities of assembly language and features of
the high-level language.

Portability: C language is lavishly portable as programs that are written in C


language can run and compile on any system with either none or small
changes.

Easy to Extend: Programs written in C language can be extended means when


a program is already written in it then some more features and operations can
be added to it.

History of C:

3
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

Low level language and high level language:


A language is basically a mode of communication, because it is used to share
information, ideas, and opinions. In computer systems, programming languages
are used by the software developers or programmers to creates applications or
software systems. A programming language provides a way of writing computer
instructions that are used to perform a specific task. Examples of computer
programming languages include C, C++, Java, Python, Ruby, Scala, Perl, C#,
Groovy, Dart, etc.
Based on the closeness of a programming language to the system hardware
(mainly processor), computer programming languages are classified into two
categories namely, high-level languages and low-level languages. The most
fundamental difference between the two is that low-level languages are closer to
the system hardware and require the knowledge of hardware to write the
instructions; whereas high-level programming languages are the machine
independent languages that do not require the hardware knowledge to write
instructions.

What is a High-Level Language?

4
A High-Level Language is a computer programming language that uses
English like statements to write the computer instructions. High-level
languages are most widely programming languages because they are easy to
understand to human being.
Here is a list of some important characteristics of high-level languages −
 It can be easily interpreted as well as compiled in comparison to low-level
language.
 It can be considered as a programmer-friendly language.
 It is easy to understand.
 It is easy to debug.
 It is simple in terms of maintenance.
 It requires a compiler/interpreter to be translated into machine code.
 It can be run on different platforms.
 It can be ported from one location to another.
 It is less memory efficient, i.e., it consumes more memory in comparison
to low-level languages.
 Examples of high-level languages include C, C++, Java, and Python.
 t is widely used.

What is a Low-Level Language?


A Low-Level Language is also a category of computer programming language
in which the computer codes are written in the binary language or machine
codes. Because of this, low-level language is sometimes also known
as machine language. The low-level language is less friendly for human
(programmer), but more friendly for machine because the computer processor
can directly process the codes written in the low-level language.
The following are the important characteristics of a low-level language −
 It can be understood easily by the machine.
 It is considered as a machine-friendly language.
 It is difficult to understand.
 It is difficult to debug.
 Its maintenance is also complex.
 It is not portable.
 It depends on the machine; hence it can't be run on different platforms.
 It requires an assembler that would translate instructions.
 It is not used widely in today's times.

Difference between High-Level Language and Low-Level Language

5
S.No
High-Level Language Low-Level Language
.

It can be considered as a programmer- It is considered as a


1. friendly language. machine-friendly
language.

It requires a compiler/interpreter to be It requires an assembler


2. translated into machine code. that would translate
instructions.

It can be ported from one location to It is not portable.


3.
another.

It is easy to understand. It is difficult to


4.
understand.

5. It is easy to debug. It is difficult to debug.

It is less memory efficient, i.e., it consumes It consumes less memory.


6. more memory in comparison to low-level
languages.

Algorithm in C
Algorithm is a step-by-step procedure, which defines a set of instructions to be
executed in a certain order to get the desired output. Algorithms are generally
created independent of underlying languages, i.e. an algorithm can be
implemented in more than one programming language.
Characteristics of an Algorithm:

6
 Clear and Unambiguous: The algorithm should be clear and
unambiguous. Each of its steps should be clear in all aspects and must lead
to only one meaning.
 Well-Defined Inputs: If an algorithm says to take inputs, it should be well-
defined inputs. It may or may not take input.
 Well-Defined Outputs: The algorithm must clearly define what output will
be yielded and it should be well-defined as well. It should produce at least
1 output.
 Finite-ness: The algorithm must be finite, i.e. it should terminate after a
finite time.
 Feasible: The algorithm must be simple, generic, and practical, such that it
can be executed with the available resources. It must not contain some
future technology or anything.
 Language Independent: The Algorithm designed must be language-
independent, i.e. it must be just plain instructions that can be implemented
in any language, and yet the output will be the same, as expected.
 Input: An algorithm has zero or more inputs. Each that contains a
fundamental operator must accept zero or more inputs.
 Output: An algorithm produces at least one output.Every instruction that
contains a fundamental operator must accept zero or more inputs.
 Definiteness: All instructions in an algorithm must be unambiguous,
precise, and easy to interpret. By referring to any of the instructions in an

7
algorithm one can clearly understand what is to be done. Every
fundamental operator in instruction must be defined without any ambiguity.
 Finiteness: An algorithm must terminate after a finite number of steps in
all test cases. Every instruction which contains a fundamental operator must
be terminated within a finite amount of time. Infinite loops or recursive
functions without base conditions do not possess finiteness.
 Effectiveness: An algorithm must be developed by using very basic,
simple, and feasible operations so that one can trace it out by using just
paper and pencil.

Algorithm Example:
Add two numbers entered by the user

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Flowchart in c:
Flowchart is a graphical representation of an algorithm. Programmers often
use it as a program-planning tool to solve a problem. It makes use of symbols
which are connected among them to indicate the flow of information and
processing.
The process of drawing a flowchart for an algorithm is known as
“flowcharting”.
Symbols Used In Flowchart

Symbol Purpose Description

8
Indicates the flow of logic
Flow line
connecting symbols.

Represents the start and the


Terminal(Stop/Start)
of a flowchart.

Used for input and output


Input/Output
operation.

Used for arithmetic operati


Processing
and data-manipulations.

Used for decision making


Decision between two or more
alternatives.

On-page Connector Used to join different flowl

9
Used to connect the flowch
Off-page Connector
portion on a different page.

Represents a group of
Predefined
statements performing one
Process/Function
processing task.

Rules For Creating Flowchart :


A flowchart is a graphical representation of an algorithm.it should follow some
rules while creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.
Advantages of Flowchart:
 Flowcharts are a better way of communicating the logic of the system.
 Flowcharts act as a guide for blueprint during program designed.
 Flowcharts help in debugging process.
 With the help of flowcharts programs can be easily analyzed.
 It provides better documentation.
 Flowcharts serve as a good proper documentation.
 Easy to trace errors in the software.
 Easy to understand.
 The flowchart can be reused for inconvenience in the future.
 It helps to provide correct logic.
Disadvantages of Flowchart:
 It is difficult to draw flowcharts for large and complex programs.
 There is no standard to determine the amount of detail.
 Difficult to reproduce the flowcharts.

10
 It is very difficult to modify the Flowchart.
 Making a flowchart is costly.
 Some developer thinks that it is waste of time.
 It makes software processes low.
 If changes are done in software, then the flowchart must be redrawn

Flowchart Example:
Add two numbers entered by the user.

Compiler and interpreter:


1. Compiler:
It is a translator which takes input i.e., High-Level Language, and produces an
output of low-level language i.e. machine or assembly language.
 A compiler is more intelligent than an assembler it checks all kinds of
limits, ranges, errors, etc.
 But its program run time is more and occupies a larger part of memory. It
has a slow speed because a compiler goes through the entire program and
then translates the entire program into machine codes.

11
2. Interpreter:
An interpreter is a program that translates a programming language into
a comprehensible language. –
 It translates only one statement of the program at a time.
 Interpreters, more often than not are smaller than compilers.

Let’s see the difference between Compiler and Interpreter:

S.No. Compiler Interpreter

The compiler scans the whole Translates the program one


1.
program in one go. statement at a time.

As it scans the code in one go,


Considering it scans code one line at
2. the errors (if any) are shown at
a time, errors are shown line by line.
the end together.

Due to interpreters being slow in


The main advantage of compilers
3. executing the object code, it is
is its execution time.
preferred less.

It does not convert source code into


It converts the source code into
4. object code instead it scans it line by
object code.
line

It does not require source code It requires source code for later
5
for later execution. execution.

6 Execution of the program takes Execution of the program happens


place only after the whole after every line is checked or
program is compiled. evaluated.

12
S.No. Compiler Interpreter

The machine code is stored in


7 Machine code is nowhere stored.
the disk storage.

Compilers more often take a


In comparison, Interpreters take less
8 large amount of time for
time for analyzing the source code.
analyzing the source code.

9. It is more efficient. It is less efficient.

10. CPU utilization is more. CPU utilization is less.

Any change in source program


Any change in source program
during the translation does not
11. after the compilation requires
require’s retranslation of entire
recompiling of entire code.
code.

Compiler Takes Entire program Interpreter Takes Single instruction


12.
as input as input.

Object code is permanently No object code is saved for future


13.
saved for future use. use.

C, C++, C#, etc are Python, Ruby, Perl, SNOBOL,


Eg. programming languages that are MATLAB, etc are programming
compiler-based. languages that are interpreter-based.

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

13
C accepts both lowercase and uppercase alphabets as variables and functions.
Digits
0123456789
Special Characters
Special Characters in C Programming

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "

^ ! * / |

- \ ~ +

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. For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
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

14
default goto sizeof volatile
const float short unsigned

C Identifiers:
C Identifiers are names given to different entities such as constants, variables,
structures, functions, etc. This tutorial describes C Identifiers.
Example:

int money;
double accountBalance;

Here, money and accountBalance are identifiers.


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

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.
Example of invalid identifiers
 2sum (starts with a numerical digit)
 int (reserved word)
 char (reserved word)
 m+n (special character, i.e., '+')

15
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 upper
letters.

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

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


characters.

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

Example:
int main()
{
int a=10;
int A=20;
printf("Value of a is : %d",a);

16
printf("\nValue of A is :%d",A);
return 0;
}
Output:
Value of a is: 10
Value of A is: 20
Datatypes in C:
A data type in C refers to the type of data used to store the information. Each
data type requires different amounts of memory and has some specific
operations which can be performed over it. It specifies the type of data that the
variable can store like integer, character, floating, double, etc. The data type is
a collection of data with values having fixed values, meaning as well as its
characteristics.

17
The data types in C can be classified as follows:

Types Description

Primitive Data Arithmetic types can be further classified into integer and
Types floating data types.

The data type has no value or operator and it does not


Void Types provide a result to its caller. But void comes under
Primitive data types.

User Defined It is mainly used to assign names to integral constants,


DataTypes which make a program easy to read and maintain

The data types that are derived from the primitive or built-
Derived types
in datatypes are referred to as Derived Data Types.

Different data types also have different ranges up to which they can store
numbers. These ranges may vary from compiler to compiler. Below is a list of
ranges along with the memory requirement and format specifiers on the 32-bit
GCC compiler.
Type Storage Size Value Range
Int (or signed int) 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
Short int(or signed short 2 bytes -32,768 to 32,767
int)
Long(or singed short int) 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 bytes 1.2E-38 to 3.4E+38 (6 decimal places)
double 8 bytes 2.3E-308 to 1.7E+308 (15 decimal places)
Long double 10 bytes 3.4E-4932 to 1.1E+4932 (19 decimal places)
char(or signed char) 1 byte -128 to 127
unsigned char 1 byte 0 to 255

Integer type:

18
 The integer data type in C is used to store the whole numbers without
decimal values.
 Octal values, hexadecimal values, and decimal values can be stored in int
data type in C.
 the size of the int data type by using the sizeof operator in C.
 Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
 Unsigned int is larger in size than signed int and it uses “%u” as a format
specifier in C
Range: -2,147,483,648 to 2,147,483,647
Size: 2 bytes or 4 bytes
Format Specifier: %d

Note: The size of an integer data type is compiler-dependent, when processors


are 16-bit systems, then it shows the output of int as 2 bytes. And when
processors are 32-bit then it shows 2 bytes as well as 4 bytes.

Example:
// C program to print Integer data types.
#include <stdio.h>

int main()
{
// Integer value with positive data.
int a = 9;

// integer value with negative data.


int b = -9;

// U or u is Used for Unsigned int in C.


int c = 89U;

// L or l is used for long int in C.


long int d = 99998L;

19
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n", c);
printf("Integer value with an long int data: %ld", d);

return 0;
}

Output:
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998

Charater Types:
 Character data type allows its variable to store only a single character.
 The storage size of the character is 1.
 It is the most basic data type in C. It stores a single character and requires a
single byte of memory in almost all compilers.

Range: (-128 to 127) or (0 to 255)


Size: 1 byte
Format Specifier: %c

Floating point Types:


 In C programming float data type is used to store floating-point values.
 Float in C is used to store decimal and exponential values.
 It is used to store decimal numbers (numbers with floating point values)
with single precision.
Range: 1.2E-38 to 3.4E+38
Size: 4 bytes

20
Format Specifier: %f

Example:
// C Program to demonstrate use
// of Floating types
#include <stdio.h>

int main()
{

float a = 9.0f;
float b = 2.5f;

// 2x10^-4
float c = 2E-4f;
printf("%f\n",a);
printf("%f\n",b);
printf("%f",c);

return 0;
}
Output:
9.000000
2.500000
0.000200

Double Types
 A Double data type in C is used to store decimal numbers (numbers with
floating point values) with double precision
 It is used to define numeric values which hold numbers with decimal values
in C.

21
 Double data type is basically a precision sort of data type that is capable of
holding 64 bits of decimal numbers or floating points.
 Since double has more precision as compared to that float then it is much
more obvious that it occupies twice the memory as occupied by the
floating-point type. It can easily accommodate about 16 to 17 digits after or
before a decimal point.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
Example:

// C Program to demonstrate
// use of double data type
#include <stdio.h>

int main()
{

double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;

printf("%lf\n", a);

printf("%lf\n", b);

printf("%lf", c);

return 0;
}

Output:
123123123.000000
22
12.293123
2312312312.123123

Format Specifiers:
The format specifiers are used in C for input and output purposes. the compiler
can understand that what type of data is in a variable during taking input using
the scanf() function and printing using printf() function. Here is a list of format
specifiers.

Format Specifier Type

%c Character

%d Signed integer

%e or %E Scientific notation of floats

%f Float values

%g or %G Similar as %e or %E

%hi Signed integer (short)

%hu Unsigned Integer (short)

%i Unsigned integer

%l or %ld or %li Long

%lf Double

%Lf Long double

%lu Unsigned int or unsigned long

%lli or %lld Long long

%llu Unsigned long long

23
Format Specifier Type

%o Octal representation

%p Pointer

%s String

%u Unsigned int

%x or %X Hexadecimal representation

%n Prints nothing

%% Prints % character

These are the basic format specifiers. We can add some other parts with the
format specifiers. These are like below −
 A minus symbol (-) sign tells left alignment
 A number after % specifies the minimum field width. If string is less than
the width, it will be filled with spaces
 A period (.) is used to separate field width and precision

Example
#include <stdio.h>
main()
{
char ch = 'B';
printf("%c", ch); //printing character data
//print decimal or integer data with d and i
int x = 45, y = 90;
printf("%d", x);
printf("%i", y);
float f = 12.67;
printf("%f", f); //print float value

24
printf("%e", f); //print in scientific notation
int a = 67;
printf("%o", a); //print in octal format
printf("%x", a); //print in hexa format
char str[] = "Hello World";
printf("%s", str);
printf("%20s", str); //shift to the right 20 characters including the string
printf("%-20s", str); //left align
printf("%20.5s", str); //shift to the right 20 characters including the string, and
print string up to 5 character
printf("%-20.5s", str); //left align and print string up to 5 character
}

Output
B
45
90
12.670000
1.267000e+001
103
43
Hello World
Hello World
Hello World
Hello
Hello
We can use these format specifiers for the scanf() function also in the same
manner. So we can take the input from scanf() like above how we have printed.
Operators and Expressions in c:
C Operators are symbols that represent operations to be performed on one or
more operands. C provides a wide range of operators, which can be classified
into different categories based on their functionality. Operators are used for
performing operations on variables and values.

25
What are Operators in C?
Operators can be defined as the symbols that help us to perform specific
mathematical, relational, bitwise, conditional, or logical computations on
operands. In other words, we can say that an operator operates the operands.
For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are
operands. The addition operator tells the compiler to add both of the operands
‘a’ and ‘b’. The functionality of the C programming language is incomplete
without the use of operators.
Types of Operators in C
 Arithmetic operators.
 Relational operators.
 Logical operators.
 Assignment operators.
 Increment and decrement operators.
 Bitwise operators.
 Conditional operators.
 Special operators.

Arithmetic operator
These operators are used for numerical calculations (or) to perform arithmetic
operations like addition, subtraction etc.

Operator Description Example a=20,b=10 Output

+ Addition a+b 20+10 30

- subtraction a-b 20-10 10

* multiplication a*b 20*10 200

/ Division a/b 20/10 2(quotient)

% Modular Division a%b 20%10 0 (remainder)

26
Example: Arithmetic Operators:
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);

return 0;
}

Output

a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1

Relational operators
These are used for comparing two expressions.

27
Operator Description Example a=20,b=10 Output

< less than a<b 10<20 1

<= less than (or) equal to a<=b 10<=20 1

> greater than a>b 10>20 0

>= greater than (or) equal to a>=b 10>=20 0

== equal to a==b 10==20 0

!= not equal to a!=b 10!=20 1

The output of a relational expression is either true (1) (or) false (0).

Example: Relational operators:


#include<stdio.h>
int main ( )
{
int a= 10, b = 20;
printf (" %d\n", a<b);
printf (" %d\n", a<=b);
printf (" %d\n", a>b);
printf (" %d\n", a>=b);
printf (" %d\n", a = =b);
printf (" %d\n", a ! =b);
return 0;
}
Output:
11000111

Logical Operators
These are used to combine 2 (or) more expressions logically.
They are logical AND (&&) logical OR ( || ) and logical NOT (!)

28
exp1 exp2 exp1&&exp2

T T T

T F F

F T F

F F F

Logical AND(&&)

exp1 exp2 exp1||exp2

T T T

T F T

F T T

F F F

Logical OR(||)

exp !exp

T F

F T

Logical NOT(!)

Operator Description Example a=20,b=10 Output

&& logical AND (a>b)&&(a<c) (10>20)&&(10<30) 0

|| logical OR (a>b)||(a<=c) (10>20)||(10<30) 1

! logical NOT !(a>b) !(10>20) 1

Example: Logical Operators

29
#include<stdio.h>
int main ( )
{
int a= 10, b = 20, c= 30;
printf (" %d\n", (a>b) && (a<c));
printf (" %d\n", (a>b) | | (a<c));
printf (" %d\n", ! (a>b));
return 0;
}
Output:

011

Assignment operators
It assigns a value to a variable. The types of assignment operators are −
 Simple assignment.
 Simple assignment.

Operator Description Example

= simple assignment a=10

+=,-=,*=,/=,%= compound assignment a+=10"a=a+10a=10"a=a-10

Example: Assignment operators:


#include<stdio.h>
int main ( )
{
int a= 10,;
printf (" %d\n", a);
printf (" %d\n", a+ =10);
return 0;
}

30
Output:
10
20

Bitwise operators:
The bitwise operators are the operators used to perform the operations on the
data at the bit-level. When we perform the bitwise operations, then it is also
known as bit-level programming. It consists of two digits, either 0 or 1. It is
mainly used in numerical computations to make the calculations faster.

Operator Meaning of operator

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise exclusive OR operator

~ One's complement operator (unary operator)

<< Left shift operator

>> Right shift operator

Let's look at the truth table of the bitwise operators.

X Y X&Y X|Y X^Y

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 1

31
Bitwise AND operator

Bitwise AND operator is denoted by the single ampersand sign (&). Two
integer operands are written on both sides of the (&) operator. If the
corresponding bits of both the operands are 1, then the output of the bitwise
AND operation is 1; otherwise, the output would be 0.

For example,
We have two variables a and b.
a =6;
b=4;
The binary representation of the above two variables are given below:
a = 0110
b = 0100
When we apply the bitwise AND operation in the above two variables, i.e., a&b
, the output would be:
Result = 0100
Program:
#include <stdio.h>
int main()
{
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b is %d",a&b);
return 0;
}

Output

32
Bitwise OR operator

The bitwise OR operator is represented by a single vertical sign (|). Two integer
operands are written on both sides of the (|) symbol. If the bit value of any of
the operand is 1, then the output would be 1, otherwise 0.
For example,
We consider two variables,
a = 23;
b = 10;
The binary representation of the above two variables would be:
a = 0001 0111
b = 0000 1010
When we apply the bitwise OR operator in the above two variables, i.e., a|b , the
n the output would be:
Result = 0001 1111
Program:
#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is %d",a|b);
return 0;
}
Output:

33
Bitwise exclusive OR operator

Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are


written on both sides of the exclusive OR operator. If the corresponding bit of
any of the operand is 1 then the output would be 1, otherwise 0.
We consider two variables a and b,
a = 12;
b = 10;
The binary representation of the above two variables would be:
a = 0000 1100
b = 0000 1010
When we apply the bitwise exclusive OR operator in the above two variables (a
^b), then the result would be:
Result = 0000 1110

Program:

#include <stdio.h>
int main()
{
int a=12,b=10; // variable declarations
printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
return 0;
}

Output:

34
Bitwise complement operator

The bitwise complement operator is also known as one's complement operator.


It is represented by the symbol tilde (~). It takes only one operand or variable
and performs complement operation on an operand. When we apply the
complement operation on any bits, then 0 becomes 1 and 1 becomes 0.

For example,
If we have a variable named 'a',
a = 8;
The binary representation of the above variable is given below:
a = 1000
When we apply the bitwise complement operator to the operand, then the output
would be:
Result = 0111

Program:
#include <stdio.h>
int main()
{
int a=8; // variable declarations
printf("The output of the Bitwise complement operator ~a is %d",~a);
return 0;
}

Output:

35
Bitwise shift operators

Two types of bitwise shift operators exist in C programming. The bitwise shift
operators will shift the bits either on the left-side or right-side. Therefore, we
can say that the bitwise shift operator is divided into two categories:
o Left-shift operator
o Right-shift operator

Left-shift operator

It is an operator that shifts the number of bits to the left-side.


Syntax of the left-shift operator is given below:
Operand << n

Where,

Operand is an integer expression on which we apply the left-shift


operation.

n is the number of bits to be shifted.

In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n'
bits on the left side will be popped out, and 'n' bits on the right-side are filled
with 0.
Example:
Suppose we have a statement:
int a = 5;
The binary representation of 'a' is given below:
a = 0101

36
If we want to left-shift the above representation by 2, then the statement would
be:
a << 2;
0101<<2 = 00010100
Program:
#include <stdio.h>
int main()
{
int a=5; // variable initialization
printf("The value of a<<2 is : %d ", a<<2);
return 0;
}

Output:

Right-shift operator

It is an operator that shifts the number of bits to the right side.

Syntax of the right-shift operator is given below:


Operand >> n;

Where,

Operand is an integer expression on which we apply the right-shift operation.

N is the number of bits to be shifted.

37
In the case of the right-shift operator, 'n' bits will be shifted on the right-side.
The 'n' bits on the right-side will be popped out, and 'n' bits on the left-side are
filled with 0.

Example:
Suppose we have a statement,
int a = 7;
The binary representation of the above variable would be:
a = 0111
If we want to right-shift the above representation by 2, then the statement would
be:
a>>2;
0000 0111 >> 2 = 0000 0001
Program:
#include <stdio.h>
int main()
{
int a=7; // variable initialization
printf("The value of a>>2 is : %d ", a>>2);
return 0;
}

Output:

Increment and Decrement operators:


Increment Operator

38
Increment Operators are the unary operators used to increment or add 1 to the
operand value. The Increment operand is denoted by the double plus symbol (+
+). It has two types, Pre Increment and Post Increment Operators.
Pre-increment Operator
The pre-increment operator is used to increase the original value of the operand
by 1 before assigning it to the expression.
Syntax:
X = ++A;

Example 1: Program to use the pre-increment operator in C


#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer variables
int x, y, z;
printf (" Input the value of X: ");
scanf (" %d", &x);
printf (" Input the value of Y: ");
scanf (" %d", &y);
printf (" Input the value of Z: ");
scanf (" %d", &z);
// use pre increment operator to update the value by 1
++x;
++y;
++z;

printf (" \n The updated value of the X: %d ", x);


printf (" \n The updated value of the Y: %d ", y);
printf (" \n The updated value of the Z: %d ", z);
return 0;
}
Output:

39
Input the value of X: 10
Input the value of Y: 15
Input the value of Z: 20

The updated value of the X: 11


The updated value of the Y: 16
The updated value of the Z: 21
Post increment Operator

The post-increment operator is used to increment the original value of the


operand by 1 after assigning it to the expression.

Syntax
X = A++;

In the above syntax, the value of operand 'A' is assigned to the variable 'X'.
After that, the value of variable 'A' is incremented by 1.
Example 2: Program to use the post-increment operator in C
#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer variables
int x, y, z, a, b, c;
printf (" Input the value of X: ");
scanf (" %d", &x);
printf (" Input the value of Y: ");
scanf (" %d", &y);
printf (" Input the value of Z: ");
scanf (" %d", &z);
// use post-increment operator to update the value by 1
a = x++;
b = y++;
c = z++;
40
printf (" \n The original value of a: %d", a);
printf (" \n The original value of b: %d", b);
printf (" \n The original value of c: %d", c);

printf (" \n\n The updated value of the X: %d ", x);


printf (" \n The updated value of the Y: %d ", y);
printf (" \n The updated value of the Z: %d ", z);
return 0;
}

Output:
Input the value of X: 10
Input the value of Y: 15
Input the value of Z: 20

The original value of a: 10


The original value of b: 15
The original value of c: 20

The updated value of the X: 11


The updated value of the Y: 16
The updated value of the Z: 21

Decrement Operator

Decrement Operator is the unary operator, which is used to decrease the original
value of the operand by 1. The decrement operator is represented as the double
minus symbol (--). It has two types, Pre Decrement and Post Decrement
operators.
Pre Decrement Operator

The Pre Decrement Operator decreases the operand value by 1 before assigning
it to the mathematical expression. In other words, the original value of the
operand is first decreases, and then a new value is assigned to the other variable.

41
Syntax
B = --A;
In the above syntax, the value of operand 'A' is decreased by 1, and then a new
value is assigned to the variable 'B'.

Example 3: Program to demonstrate the pre decrement operator in C


#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer variables
int x, y, z;
printf (" Input the value of X: ");
scanf (" %d", &x);
printf (" \n Input the value of Y: ");
scanf (" %d", &y);
printf ("n Input the value of Z: ");
scanf (" %d", &z);
// use pre decrement operator to update the value by 1
--x;
--y;
--z;

printf (" \n The updated value of the X: %d ", x);


printf (" \n The updated value of the Y: %d ", y);
printf (" \n The updated value of the Z: %d ", z);
return 0;
}

Output:
Input the value of X: 5
Input the value of Y: 6

42
Input the value of Z: 7

The updated value of the X: 6


The updated value of the Y: 7
The updated value of the Z: 8

Post decrement Operator:


Post decrement operator is used to decrease the original value of the operand by
1 after assigning to the expression.
Syntax
B = A--;
In the above syntax, the value of operand 'A' is assigned to the variable 'B', and
then the value of A is decreased by 1.
Example 4: Program to use the post decrement operator in C
#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer variables
int x, y, z, a, b, c;
printf (" Input the value of X: ");
scanf (" %d", &x);
printf (" Input the value of Y: ");
scanf (" %d", &y);
printf (" Input the value of Z: ");
scanf (" %d", &z);
// use post-decrement operator to update the value by 1
a = x--;
b = y--;
c = z--;

printf (" \n The original value of a: %d", a);

43
printf (" \n The original value of b: %d", b);
printf (" \n The original value of c: %d", c);

printf (" \n\n The updated value of the X: %d ", x);


printf (" \n The updated value of the Y: %d ", y);
printf (" \n The updated value of the Z: %d ", z);
return 0;
}

Output:
Input the value of X: 6
Input the value of Y: 12
Input the value of Z: 18

The original value of a: 6


The original value of b: 12
The original value of c: 18

The updated value of the X: 5


The updated value of the Y: 11
The updated value of the Z: 17

Example 5: Program to perform the pre increment and pre decrement operator
#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer data type variable
int i, j, x, y;
printf (" Enter the value of i " );
scanf (" %d", &i);

44
printf (" Enter the value of j " );
scanf (" %d", &j);

// use pre increment operator to update original value by 1


x = ++i;
printf (" After using the pre-incrementing, the value of i is %d \n", i);
printf (" The value of x is %d \n", x);

// use pre decrement operator to decrease original value by 1


y = --j;
printf (" After using the pre decrementing, the value of j is %d \n", j);
printf (" The value of y is %d \n", y);
return 0;
}
Output:
Enter the value of i
5
Enter the value of j
10
After using the pre-incrementing, the value of i is 6
The value of x is 6
After using the pre-decrementing, the value of j is 9
The value of y is 9

Example 6: Program to print the post increment and post decrement operator
#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer data type variable
int i, j, x, y;

45
printf (" Enter the value of i " );
scanf (" %d", &i);
printf (" Enter the value of j " );
scanf (" %d", &j);

// use post increment operator to update original value by 1


x = i++;
printf (" After using the post-incrementing, the value of i is %d \n", i);
printf (" The value of x is %d \n", x);

// use post decrement operator to decrease original value by 1


y = j--;
printf (" After using the post-decrementing, the value of j is %d \n", j);
printf (" The value of y is %d \n", y);
return 0;
}
Output:
Enter the value of i 10
Enter the value of j 20
After using the post-incrementing, the value of i is 11
The value of x is 10
After using the post-decrementing, the value of j is 19
The value of y is 20

Difference between the Increment and Decrement Operator in C

Increment Operator Decrement Operator

It is used to increment the value of a variable by It is used to decrease the operand values by 1.
1.

The increment operator is represented as the The decrement operator is represented as the
double plus (++) symbol. double minus (--) symbol.

46
It has two types: pre-increment operator and Similarly, it has two types: the pre-decrement
post-increment operator. operator and the post-decrement operator.

Pre increment operator means the value of the Pre decrement means the value of the operato
operator is incremented first and then used in decremented first and then assigned in the
the expression. expression.
The post-increment operator means the operand Whereas the post decrement operator means t
is first used in the expression and then performs operand is first used in the expression and the
the increment operation to the original value by performs the decrement operation to the
1. operand's original value by 1.

Syntax for the pre increment operator: X = ++a; Syntax for the pre decrement operator: X = --
Syntax for the post increment operator: X = a+ Syntax for the post decrement operator: X = a
+;

Both operators' works only to the single Both operators' works only to the single opera
operand, not values. not values.

Operator precedence and Associativity:

Operator precedence determines which operation is performed first in an


expression with more than one operators with different precedence.
For example: Solve

10 + 20 * 30
Operators Associativity is used when two operators of same precedence
appear in an expression. Associativity can be either Left to Right
or Right to Left.
For example: ‘*’ and ‘/’ have same precedence and their associativity
is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”
Operators Precedence and Associativity are two characteristics of
operators that determine the evaluation order of sub-expressions in
absence of brackets
Operators Precedence & Associativity Table
Operator Meaning of operator Associativity
() Functional call Left to right
[] Array element reference
-> Indirect member selection
47
. Direct member selection
! Logical negation Right to left
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Dereference (Address)
* Pointer reference
sizeof Returns the size of an object
(type) Typecast (conversion)
* Multiply Left to right
/ Divide
% Remainder
+ Binary plus(Addition) Left to right
- Binary minus(subtraction)
<< Left shift Left to right
>> Right shift
< Less than Left to right
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to Left to right
!= Not equal to
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Right to left
= Simple assignment Right to left
*= Assign product
/= Assign quotient
%= Assign remainder
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
48
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
, Separator of expressions Left to right

49

You might also like