0% found this document useful (0 votes)
21 views25 pages

Unit I

C programming

Uploaded by

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

Unit I

C programming

Uploaded by

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

UNIT –I

Introduction: Block diagram of a computer and it’s components, binary number system,
algorithms and Flowcharts.
C Preliminaries: Keywords, Identifiers, Constants, Variables, Data Types, Formatted I/O
functions and the Structure of a C Program with suitable illustrative programs.
Operators: Arithmetic Operators, Assignment Operators, Relational Operators, Logical
Operators, Increment and Decrement Operators, Bitwise Operators, Ternary Operator and
Special Operators.
SAMPLE QUESTIONS

1) Write about Computer systems?


2) Explain about Hardware and Software Concepts?
3) What is an algorithm? Explain the criterias/properties/conditions? Explain with an
example?
4) Explain about Pseudo code?
5) What is flow chart? Advantages and div-advantages of a flow chart? Explain with an
example?
6) What are the program development steps? Explain in-detail?
7) What are the computer languages ? Explain in-detail?
8) What is the Structure of a c program ? Explain with an example program?
9) What is an identifier ? Rules of an identifier ? Explain with an valid and in-valid
examples?
10) Explain about basic data types and sizes?
11) Explain about Constants ?
12) What is variable ? Rules of variable? Explain with an valid and in-valid examples?
Explain about Operators( Arthmetic , relational and logical operators, increment and
decrement operators, assignment operator)?
13) What is conditional operator/ternary operator?

Computer System
 In the year of 1822 ‘Charless Babbage ‘ invented the computer . So, he is called as
father of computer.
 Computer is an electronic device which accepts the input, process the input and
displays the output.

Comparision of Computer and Human parts:-

Computer Human
Central Processing Unit(CPU) Brain
Input units(Keyboard,Mouse,etc) Eye,Ear
Output units(Monitor,Printer , etc.) Mouth , Pen (in hand)
Storage device(RAM,HardDisk,etc.) Writing in the book

Prepared By K CHANDRAM Asst.Professor , Anurag University


Comparision of Computer and Human functionalities:-

Functions Computer` Human


Speed Very fast Slow
Decision Making Very poor Good
Memory Very good Normal
Accuracy Very good Not so good
Follow-up of instructions Very good Less good

Computer Hardware
The collection of electronic, electrical and mechanical components is called
“Computer Hardware “.

Block diagram of a computer:-

Arithmetic & Logic


Unit Output Unit

Control Unit Eg:Monitor,Printer,etc.

Input Unit
Secondary storage
Eg: Keyboard,Mouse.etc Memory Unit Eg: Hard Disk,CD,DVD,etc

The computer consists of ,

1)Input Unit
2)Output Unit
3)Central Processing Unit &
3)Memory Unit.
1)Input Unit:- The Unit which accepts the data from the user , convert the data into
computer acceptable form and finally submit the converted data to the computer system
for further processing, is called “Input Unit”.

Ex:- Keyboard , Mouse , Trackball , Joystick , Touch Pannels , etc.

2)Output Unit:- The Unit which accepts the results produced by the computer , convert
these results into human understandable form and finally displays the results to the user ,
is called “Output Unit”.

Prepared By K CHANDRAM Asst.Professor , Anurag University


Ex:- Monitor , Printer , Plotter , etc.

1) Storage unit:[Memory unit]


“The unit which stores the data and their corresponding results is called memory unit”
The functionalities are :
1)It stores the data for processing
2)It stores the intermediate results also
3)The results are stored and then passed to output an output device.
The memory is classified into two categories :

The data stored in the computer memory is always in the binary form. That is the data will be
in 0`s and 1`s.
4 bits =1 Nibble
8 bits= 1Byte(B)
1024 Bytes= 1 KiloBytes(KB)
1024 KB=1 MegaBytes(MB)
1024 MB= 1GigaBytes (GB)
3)Central Processing Unit(CPU):
The functionalities are,
1)Interprets the operations
2)coordinates the operations
3)supervises the instructions
4)controls all internal as well as external peripherals
5)controls all the computer`s functions
6)performs all calculations
7)process all the user-entered data
 The components of CPU are
-Arithmetic logic unit
-control unit
-Memory unit
-Registers(PC,AC,IR,MAR,etc)
Computer software
”The collection of the programs is called software. here, the program is nothing but collection
of instructions.Computer software is classified into the following ways
1)System software
2)Application software
3)Packages and
4)Utilities

->The pictorial representation of software is classified as ,

1)SYSTEM SOFTWARE:-
The system software is designed to control the operation of a computer system.It supports the
following activities:

a)Running of the other software

Prepared By K CHANDRAM Asst.Professor , Anurag University


b)communicating with peripheral devices such as printers, card readers ,disc and tape devices
etc;
c)Development of other types of software
d)Monitoring the various resources like memory, peripherals , cpu etc
The examples of system software are operating systems,compilers,interpreters,assemblers,etc.
->The Operating system(OS) is the system software which provides the solutions to system
related problems
When you switch-on the computer at that time first the OS is loaded in to memory and is
excuted ,finally it makes the computer to interact with user.
The examples for OS are MS-DOS ,OS/2, Windows and Unix ,etc
Mainly any type of OS perform the following activities :
a)job management b)Task management c)Data management d)security and e)Boot strap

ASSEMBLER:It is the system software which translate the assembly language program in to
a machine language program.

COMPILER:-It is the system software which translate the high-level language entire
program into a machine language program.

INTERPRETER:-It is the system software which translates one statement of a high-level


language program in to machine codes and execute it.

ii)APPLICATION SOFTWARE:-The software which provide solutions to the application


related problems is called application software.
(OR)
The software which provides solutions to the human related problems is called application
software. Some of the software applications are banking, hospital, insurance, etc.
Packages:

Packages is a computer applications which is designed to perform a particular type of work


These are designed to satisfy the needs of more than one organization.
Examples are MS-WORD,MS-EXCEL, Graphics, Database Management, etc.

Utilities:
Utility software is designed to perform maintenance work on the system.
Eg: Text Editor , Memory Dump Program, Debugging tool, Sort & Merge, Loader, Linker,
etc.
Binary Number System
A binary number system is a number system that is used to represent various numbers using
only two symbols “0” and “1”. The word binary is derived from the word “bi” which means
two. Hence, this number system is called the Binary Number System. Thus, the binary
number system is a system that has only two symbols.
There are generally various types of number systems and among them the four major ones
are,
 Binary Number System (Number system with Base 2)
 Octal Number System (Number system with Base 8)
 Decimal Number System (Number system with Base 10)
 Hexadecimal Number System (Number system with Base 16)

Prepared By K CHANDRAM Asst.Professor , Anurag University


Here, we are only going to learn about Binary Number System. This number system is very
useful for explaining tasks to the computer. In the Binary Number System, we have two
states “0” and “1” and these two states are represented by two states of a transistor. If the
current passes through the transistor then the computer reads “1” and if the current is absent
from the transistor then it read “0”. Thus, alternating the current the computer reads the
binary number system. Each digit in the binary number system is called a “bit”.
Binary Number System
Binary Number System is the number system in which we use two digits “0” and “1” to
perform all the necessary operations. In the Binary Number System, we have a base of 2.
The base of the Binary Number System is also called the radix of the number system.
In a binary number system, we represent the number as,
 (11001)2
In the above example, a binary number is given in which the base is 2. In a binary number
system, each digit is called the “bit”. In the above example, there are 5 digits.
Binary Number Table
Decimal Number Binary Number Decimal Number Binary Number

1 001 11 1011

2 010 12 1100

3 011 13 1101

4 100 14 1110

5 101 15 1111

6 110 16 10000

7 111 17 10001

8 1000 18 10010

9 1001 19 10011

10 1010 20 10100

Binary to Decimal Conversion


A binary number is converted into a decimal number by multiplying each digit of the binary
number by the power of either 1 or 0 to the corresponding power of 2. Let us consider that a

Prepared By K CHANDRAM Asst.Professor , Anurag University


binary number has n digits, B = a n-1…a3a2a1a0. Now, the corresponding decimal number is
given as
D = (an-1 × 2n-1) +…+(a3 × 23) + (a2 × 22) + (a1 × 21) + (a0 × 20)
et us go through an example to understand the concept better.
Example: Convert (10011) 2 to a decimal number.
Solution:
The given binary number is (10011) 2.
(10011)2 = (1 × 24) + (0 × 23) + (0 × 22) + (1 × 21) + (1 × 20)
= 16 + 0 + 0 + 2 + 1 = (19) 10
Hence, the binary number (10011) 2 is expressed as (19) 10.
Decimal to Binary Conversion
A decimal number is converted into a binary number by dividing the given decimal number
by 2 continuously until we get the quotient as 1, and we write the numbers from downwards
to upwards.
Let us go through an example to understand the concept better.
Example: Convert (28) 10 into a binary number.
Solution:

Hence, (28)10 is expressed as (11100)2.


Example 2: Convert Binary Number (1010101)2 to Decimal Number.
Solution:
Given Binary Number, (1010101) 2
= (1 × 20) + (0 × 21) + (1 × 22) + (0 × 23) + (1 × 24) + (0 × 25) + (1 ×26)
= 1 + 0 + 4 + 0 + 16 + 0 + 64
= (85)10
Thus, Binary Number (1010101) 2 is equal to (85)10 in decimal system.

Algorithm
Definition:-step-by-step representation of a problem procedure is called an algorithm.
It is used for performing a task in finite amount of time.
Criteria’s/Conditions/Properties of an algorithm:
1)Finiteness

Prepared By K CHANDRAM Asst.Professor , Anurag University


2)Definiteness
3) Effectiveness
4)Generality and
5)Input/output
1)Finiteness:-An algorithm must terminate in a finite number of steps.
2)Definiteness:-Each step of the algorithm must be clear and understandable.
3) Effectiveness:-Each step should be easily converted into programming code.
4)Generality:-The algorithm should give solutions to specific type of task for any type of
data .
5)Input/output:-Each algorithm must take zero or more quantities as input data
and produce one or more output values.
Example: write an algorithm for finding the average of three numbers.
Step 1: start
Step 2: read three numbers x,y,z
Step 3:compute the um of x,y &z
Step 4: divide the sum by 3
Step 5:store the result into variable avg
Step 6: print the value of avg
Step 7:stop

FLOW CHART

Definition:- “ Diagramatic representation of an Algorithm is called Flow Chart ”.

Follwing symbols are used for constructing the flow chart.

Oval:- or

It is the terminal symbol used at start and end position.

Parallellogram:-

It is used for input/output.

Rectangle:-

It is used for calculation/processing the data.

Diamond:-

It is used for decision purpose.

Arrow:- , , ,

It is used for flow of execution.

Circle:-

Prepared By K CHANDRAM Asst.Professor , Anurag University


It is used for connection the different parts of the flow chart.

Bracket with broken lines:- ------

It is used for writing comments.

Example:- Draw the flow chart for sum of two numbers.

start

Read x , y values

Sum=x+y

Display sum value

Flow chart Rules:- stop

1)Use common and understable words.


2)Avoid crossing of flow lines.
3)Draw the flow chart from top –to-bottom and left-to-right.
4)If flow chart exceed a page then we have to link properly from one page to another
page.

Flow chart Advantages:-

1)A flow chart can easily explain the program logic to the program development team.
2)It is useful to prepare detail program documentation.
3)It helps to detect and remove the errors in a program.

Flow chart Disadvantages(limitations):-

1)Modifications in a flow chart is very difficult and it takes more time.


2)Redrawing the flow chart is also very difficult work.
3)Standards are not followed to draw the flow chart.

COMPUTER LANGUAGES

COMPUTER LANGUAGES:- The following are the computer generation languages.

1) First Generation Language


2) Second Generation Language
3) Third Generation Language

Prepared By K CHANDRAM Asst.Professor , Anurag University


4) Fourth Generation Language
1) First Generation Language:- It is also called as Machine language or LowLevel
Language(LLL) or Binary Language. All the instructions will be written in binary
form(either 0’s and 1’s). But understanding these instructions is very difficult.
Consider the following example:

0101 0101010 01010011 1110101010

2) Second Generation Language:- It is also called as Assembly Language.


 In this language , Mnemonic codes are used for writing the instructions.
 The program which is in Mnemonic code form is called “Source Program”.
 Assembler is the compiler which translate the source program into Object
program.
The program which is binary form is called object form.It can be explained as,
Source program

Assembler

Object program

For example:-

ADD X,Y,R1

MOVE R1,SUM

ASSEMBLER

1001 010110100

11110 110101010

3)Third Generation Language:- It is also called as High Level Language(HLL).


Example languages are BASIC, PASCAL , COBOL, FORTRAN, C, C++, etc.
In this , the instructions are writing using English language , symbols and digits.
Collection of instructions is called Program.
The Compiler is used to translate the entire source program into object program.

Prepared By K CHANDRAM Asst.Professor , Anurag University


The Interpreter is used to translate the source program into object program line by
line.

Source program|

Compiler/Interpreter

Object program

4)Fourth Generation Language:- It is also called as Command Line Language.


 These languages refers to software packages
 It is useful for the user without writing the programms.
 Examples are dbase,Foxpro,oracle.sql,Ms-word, etc.

Difference between compiler and Interpreter


1) Compiler translates the entire program into object code at a time and then execute it.
Interpreter it translate the one statement at a Time and then execute it, next go for
Second statement and soon.
2) Compiler generates the error report after Translation of the entire
program .Interpreter generates the error report after it gets the first error.
3) For compiler execution time is fast. For interpreter the execution time is slow.
4) Compiler takes more time for processing.Interpreter takes less time for processing.
5)

Creating and running programs


There are four steps in this process:
1)Writing and editing the program using text editor.
2)Compile the program using any ’C’ compiler.
3)Linking the program with the required library modules.
4)Execute the program.
This concept can be explained in the following flow chart:

Prepared By K CHANDRAM Asst.Professor , Anurag University


Structure of a ‘C’ program
‘C’ is the structured programming language. So, it’s structure can be explained as:

/*comments about the program*/ -----------Documentation section .


.
#include<stdio.h>
#include<conio.h>
------------------------ ------------ Header file section

-------------------------

#define variable value


------------ Definition section
.
Data-type var1,var2,..., var n;
------------ Global variables declaration section
Void main( )
{
Local variables declaration;
--------------------------------
---------------------------------
- ------------- Main program section.
(executable stmts)
}

User-definedfunction(list of arguments)
{
----------------------
-----------------------
-------------- user-defined function section.
----------------------
}

Prepared By K CHANDRAM Asst.Professor , Anurag University


Documentation Section:-In this section the programmers can write the comments in
between ‘/*’ and ‘*/’.
Example:- /*sum of two numbers*/
Header file section:-In this section the programmer write the header files like,
#include<stdio.h>
#inlclude<conio.h>, ect.
Definition section:-
In this section the programmer define the values as:
#define PI 3.14.
Global variable declaration section:-
The variables which are declared outside of all functions in a program.
Main program section:-
The section starts with the name main( ).The program execution starts from the opening
brace, ”{“ and terminates at the closing brace, “}” occurring after the main( ).
User-defined function:-
The functions which are defined by the user is called user-defined functions. These
functions are defined outside of the main( )function. This section is not compulsory in each C
program.
Write the TOH program for this concept as an example program.

Formatted and Unformatted Input/Output functions in C with Examples

 Formatted I/O Functions.


 Unformatted I/O Functions.
 Formatted I/O Functions vs Unformatted I/O Functions.

Formatted I/O Functions


Formatted I/O functions are used to take various inputs from the user and display multiple
outputs to the user. These types of I/O functions can help to display the output to the user in
different formats using the format specifiers. These I/O supports all data types like int, float,
char, and many more.
Why they are called formatted I/O?
These functions are called formatted I/O functions because we can use format specifiers in
these functions and hence, we can format these functions according to our needs.
List of some format specifiers-

Prepared By K CHANDRAM Asst.Professor , Anurag University


S Format
Type Description
NO. Specifier

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

4 %s string Used for I/O string/group of characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

The following formatted I/O functions will be discussed in this section-


1. printf()
2. scanf()
3. sprintf()
4. sscanf()
printf():
printf() function is used in a C program to display any value like float, integer, character,
string, etc on the console screen. It is a pre-defined function that is already declared in the
stdio.h(header file).
Syntax 1:
To display any variable value.
printf(“Format Specifier”, var1, var2, …., varn);

Unformatted Input/Output functions


Unformatted I/O functions are used only for character data type or character array/string
and cannot be used for any other datatype. These functions are used to read single input
from the user at the console and it allows to display the value at the console.

Prepared By K CHANDRAM Asst.Professor , Anurag University


Why they are called unformatted I/O?
These functions are called unformatted I/O functions because we cannot use format
specifiers in these functions and hence, cannot format these functions according to our
needs.
The following unformatted I/O functions will be discussed in this section-
1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()

Formatted I/O vs Unformatted I/O

S
Formatted I/O functions Unformatted I/O functions
No.

These functions allow us to take input


These functions do not allow to take input or
1 or display output in the user’s desired
display output in user desired format.
format.

These functions support format These functions do not support format


2
specifiers. specifiers.

These are used for storing data more


3 These functions are not more user-friendly.
user friendly

Here, we can use only character and string


4 Here, we can use all data types.
data types.

printf(), scanf, sprintf() and sscanf() getch(), getche(), gets() and puts(), are some
5
are examples of these functions. examples of these functions.

IDENTIFIERS

Prepared By K CHANDRAM Asst.Professor , Anurag University


Identifiers refer to the names of variables, functions and arrays.Identifiers are the user defined
names.It is formed with
Alphabets: a----------z A-----------,Z
Numbers: 0---------9
Underscore: _
Identifier rules
1) First character must be an alphabet or underscore
2) Must consist of only letters, digits or underscore
3) Only first 31 characters are considered.
4) Cannot use a key word.
5) Should not contain white space
The examples of valid identifiers are ramesh, program , PROGRAM, rollno, etc.
the examples of invalid identifiers are 4xy, *2, roll no

Basic Data-Types and their Sizes


The following are the basic data type with their size and range of values

Data type description size(Bytes) range

1. char single character 1 -128 to 127

2. int an integer 2 -32,7682 to32,767

3. float floating point number 4 -3.4e38 to +3.4e38

4. double double point number 8 -1.7e308 to


+1.7e308

5. void no data type 0 -----------

Constants
Which are not changed during the execution of the program called constants.Constants are
classified as
1) Numeric constants:- Here, the constant values are numbers.
2) Integer constants:-Here the constant value is integer . Integer constants do not have
the decimal point. Examples are,
Valid Invalid
48597 13,436
-433127 10.235
+25 10 244
6 75-976

3)Real constants:-The real constants are also know as floating constants.These are of two
types,
1.fractional form and 2.exponential form
Examples for fractional form are,456.78, -123.50, invalid examples are 456,456 and 456
The valid examples for exponential form are 3E4, 2e-6,0.34E6 , invalid are 23,4e5 and 456
*e8

Prepared By K CHANDRAM Asst.Professor , Anurag University


3) character constants:- A character which is placed in-between the pair of single
quotes is called character constant.
Valid are---- ‘a’, ‘/’ ,’2, etc.
Invalid are ‘aa’,’k1’ , “saa’,etc.

4) String constants:- The sequence of alpha numeric characters which are in between
the pair of double quotes is called string constant.
Example:”my name is computer”
“programing with c”
“salary is 1800.00”
Invalid examples are,
‘ My name is computer”
“my name is computer”

Variables
which is changing at the time of execution of a program is called variable
variable names
variable name are identifiers used to name the variables. So variable names follows the
identifier rules are :
1) First character must be an alphabet or underscore
2) Must consist of only letters, digits or underscore
3) Only first 31 characters are considered.
4) Cannot use a key word.
5) Should not contain white space

Valid variable names: total, tva , branch , BRANCH , student_name


invalid variable names ‘bs ----------- illegal character(’)
fact gcd-------- blank or white space not allowed
avg-marks--------illegal character(-)
6_ root------------ first character should be a letter or underscore
Roll,no-------------comma not allowed

Variable decleration
Syntax:
data-type variable name 1, variable name 2,--------,variable name n;

Example:
1) int x;
iInt x, y, z;
2) float avg,sum;
3) double length,breadth;
Variable initialisation:
Syntax:
1)datatype variable name=value;
Example:
1)int x=30;
2)float y=6.5;

Prepared By K CHANDRAM Asst.Professor , Anurag University


Operators
Operators:- Operator is the symbol that tells to the compiler to perform specific kind of
operation on the given values. C Operators are classified as follows:

1)Assignment Operators(=,+=,-=,/=,%=….)
2)Arithmetic Operators ( + , - , * , / , %)
3)Comparision Operators
a)Relational Operators ( < , <= , > , >= )
b)Equality Operators ( = = , ! =)
4)Logical Operators (&& , || , ! )
5)Bitwise Operators(&,|, ^ ,~,<<,>>)
6)Unary Operators
a)Increment Operator
B)Decrement Operator
7)Ternary Operator or Conditional Operator ( ?: )
8)Other operators
1)Assignment Operator ( = ):- Assignment Operator(=) stores the right side
i)Value into the left side variable &
Ii) Expression result value into left side variable.

Synatax: - variable = value or expression;

E.g.:- 1) int x; 2) int x, y; 3) int x,y,z;

x=10; x=14; y=x; x=10;

y=20;

z=x+y;

Prepared By K CHANDRAM Asst.Professor , Anurag University


S. No. Symbol Operator Description Syntax

1 Assign the
value of the
= Simple a=b
right operand
Assignment
to the left
operand.

2 Add the right


operand and
left operand
+= Plus and a += b
and assign
assign
this value to
the left
operand.

3 Subtract the
right operand
and left
-= Minus and a -= b
operand and
assign
assign this
value to the
left operand.

4 Multiply the
right operand
and left
*= Multiply and a *= b
operand and
assign
assign this
value to the
left operand.

5 Divide the left


operand with
the right
/= Divide and a /= b
operand and
assign
assign this
value to the
left operand.

6 %= Modulus and Assign the a %= b


assign remainder in

Prepared By K CHANDRAM Asst.Professor , Anurag University


S. No. Symbol Operator Description Syntax

the division of
left operand
with the right
operand to the
left operand.

2)Arithmetic Operators ( + , - , * , / , %):- The Operators which are used to perform the
arithmetic perations are called Arithmetic Operators.Here arithmetic operations means
addition(+),substraction(-),
multiplication(*),division(/),and modulo division(%).

Syntax:-
Operand 1 operator operand 2 ;

 Consider the following table with the declarations x=2 and y=4;

Arithmetic Meaning Expression Result


operator
+ Addition x+y 6
- Substraction x-y -2
* Multiplication x*y 8
/ Division x/y 0
% Modulo Division x%y 2

2)Comparison Operators:-
a)Relational Operators ( < , <= , > , >= ):-

The Operators which are used to form the relational expressions are called Relational
Operators.

Syntax:-
Operand 1 operator operand 2 ;
 If the expression is true then the value is1 otherwise 0.
 Consider the following example , x=6 and y=7.

Relational operator Meaning Expression Result


< Greater than x<y 1
> Less than x>y 0
<= Less than or x<=y 1
equal to

Prepared By K CHANDRAM Asst.Professor , Anurag University


>= Greater than or equal x>=y 0
to

b)Equality Operators ( = = , ! =):- The Operators which are used to check whether
they are equal or not, called Equality Operators.

Syntax:-
Operand 1 operator operand 2 ;
 If the expression is true then the value is1 otherwise 0.
 Consider the following example , x=6 and y=7.

Equality operator Meaning Expression Result


== Equal to x==y 0
!= Not equal to x ! =y 1

3)Logical Operators (&& , || , ! ):- These Operators are used to combine the two
conditional expressions.
a)Logical AND(&&):-

Syntax:-
cond-exp1 operator cond-exp 2 ;
E.g.:- (x>y) && (z>t) ;

Truth table:- If both conditional expressions are true then only result is true.

Cond-exp1 Cond-exp2 Cond-exp1&&cond-exp2


1 1 1
1 0 0
0 1 0
0 0 0

b)Logical OR(||):-

Syntax:-
cond-exp1 operator cond-exp 2 ;
E.g.:- (x>y) || (z>t) ;

Truth table:- If both conditional expressions are false then only result is false.

Cond-exp1 Cond-exp2 Cond-exp1||cond-exp2


1 1 1
1 0 1
0 1 1
0 0 0

Prepared By K CHANDRAM Asst.Professor , Anurag University


c)Logical Not(!):-

Syntax:-
operator cond-exp ;
E.g.:- ! (x>y) ;

Truth table:- If both conditional expressions are true then only result is true.

Cond-exp !(Cond-exp)
1 0
0 1

Example of Logical Operators:-

int a=4,b=5;

double c=6.5,d=3.5;

char ch=’R’;

Expression Interpretation Value


(a<=4)&&(ch= =’R’) True 1
(b<7)||(ch= = ‘T’) True 1
(c+d)= =10.0||a<4 True 1
c>=7||(a*b)<15 False 0
!(c>6.0) False 0

5)Bitwise Operators
In C, the following 6 operators are bitwise operators (also known as bit operators as they
work at the bit-level). They are used to perform bitwise operations in C.

1. The & (bitwise AND) in C takes two numbers as operands and does AND on every
bit of two numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of
two numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit
of two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand,
and the second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand,
and the second operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
Let’s look at the truth table of the bitwise operators.

Prepared By K CHANDRAM Asst.Professor , Anurag University


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 0

6)Unary Operators:- The Operator which adds or substract the value by 1 is called
Unary operator.
a) Increment Operator
b) Decrement Operator
a) Increment Operator:- (++)

Increment operator(++) increases the variable value by adding one(1).

Syntax:- operand ++; Post -increment

++operand; Pre-increment

Ex:- x ++; Post -increment

++x; Pre-increment

b) Decrement Operator:- (- -)

Increment operator(- -) increases the variable value by substracting one(1).

Syntax:- operand - -; Post -decrement

- -operand; Pre-decrement

Ex:- x - -; Post -decrement

--x; Pre-decremen

Consider the follwing example ,

For x=5 then

x++; x=6

++x; x=7

Prepared By K CHANDRAM Asst.Professor , Anurag University


y=x++; y=7 x=8

y=++x; y=9 x=9

x--; x=8

--x; x=7

y=x--; y=7 x=6

y= --x; y=5 x=5

7)Conditional Operator (Ternary operator) ? :


Conditional operator is also called as ternary operator.
The symbol for conditional operator is ? :
Syntax: - exp=exp1?exp2:exp3;

Example
Finds the maximum of x and y.
max=(x>y)?x:y;
From the above syntax we can say that if exp1 is true then exp2 will be stored in exp other
wise exp3 will be stored in exp . According to example if x>y is true then the exp2 like ‘x’
will be stored in max otherwise exp3 like ‘y’ will be stored .
Eg program
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,max;
x=20;
y=10;
max=(x>y)?x:y;
printf(“%d”,max);
}
Output:-
20

8. Other Operators
Apart from the above operators, there are some other operators available in C used to
perform some specific tasks. Some of them are discussed here:

sizeof Operator

1)sizeof is much used in the C programming language.


2)It is a compile-time unary operator which can be used to compute the size of its operand.
3)The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
4)Basically, the sizeof the operator is used to compute the size of the variable or datatype.
Syntax

Prepared By K CHANDRAM Asst.Professor , Anurag University


sizeof (operand)

To know more about the topic refer to this article.

Comma Operator ( , )

 The comma operator (represented by the token) is a binary operator that evaluates its
first operand and discards the result, it then evaluates the second operand and returns
this value (and type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator.
Syntax
operand1 , operand2

To know more about the topic refer to this article.

Conditional Operator ( ? : )

 The conditional operator is the only ternary operator in C++.


 Here, Expression1 is the condition to be evaluated.
 If the condition(Expression1) is True then we will execute and return the result of
Expression2 otherwise if the condition(Expression1) is false then we will execute and
return the result of Expression3.
 We may replace the use of if..else statements with conditional operators.
Syntax
operand1 ? operand2 : operand3;

To know more about the topic refer to this article.

dot (.) and arrow (->) Operators

 Member operators are used to reference individual members of classes, structures, and
unions.
 The dot operator is applied to the actual object.
 The arrow operator is used with a pointer to an object.
Syntax
structure_variable . member;

and
structure_pointer -> member;

To know more about dot operators refer to this article and to know more about arrow(->)
operators refer to this article.

Prepared By K CHANDRAM Asst.Professor , Anurag University


Cast Operator

 Casting operators convert one data type to another. For example, int(2.2000) would
return 2.
 A cast is a special operator that forces one data type to be converted into another.
 The most general cast supported by most of the C compilers is as follows −
 [ (type) expression ].
Syntax
(new_type) operand;

addressof (&) and Dereference (*) Operators

 Pointer operator & returns the address of a variable. For example &a; will give the
actual address of the variable.
 The pointer operator * is a pointer to a variable. For example *var; will pointer to a
variable var.
To know more about the topic refer to this article.

Prepared By K CHANDRAM Asst.Professor , Anurag University

You might also like