Beruflich Dokumente
Kultur Dokumente
UNIT I
1.1 What is a computer?
A computer is an electronic device that manipulates information, or data. It has the ability to store,
retrieve, and process data.
2. ACCURACY : Computer always gives accurate results. The accuracy of Computer does not go
down when they are used continuously for hours together.
It always gives accurate results.
3. STORAGE CAPACITY : Computer have a very large storage capacity. A large volume of
information can be stored in the memory of computer and information can be retrieved correctly
when desired.
4. VERSATILITY : The working of computer with different types of data is known as versatility.
That means computer can perform different types of job efficiently. Computer can works with
different type of data and information such as visuals, text, graphics & vidio etc. So, versatility is a
most important characteristic of computer.
5. DILLIGENCE : A Computer can work for long hours with the same accuracy and speed because it
is free from problems of boredom or lack of concentration.
6. NO THOUGHTS : Computers have no thoughts because they are machine and they are devoid of
emotions. They have no feelings. Since, computers have no thoughts and feelings so they can't make
judgment based on thoughts and feelings.
1
Managing employees database
Maintenance of stocks etc.
(ii) Banking
Today banking is almost totally dependent on computer.
Banks provide following facilities:
Banks provide online accounting facility, which includes current balances, deposits,
overdrafts, interest charges, shares, and trustee records.
ATM machines are making it even easier for customers to deal with banks.
(iii) Insurance
Insurance companies are keeping all records up-to-date with the help of computers. The insurance
companies, finance houses and stock broking firms are widely using computers for their concerns.
Insurance companies are maintaining a database of all clients with information showing
procedure to continue with policies
starting date of the policies
next due installment of a policy
maturity date
interests due
survival benefits
bonus
(iv) Education
The computer has provided a lot of facilities in the education system.
The computer provides a tool in the education system known as CBE (Computer Based
Education).
CBE involves control, delivery, and evaluation of learning.
The computer education is rapidly increasing the graph of number of computer students.
There are number of methods in which educational institutions can use computer to educate
the students.
It is used to prepare a database about performance of a student and analysis is carried out on
this basis.
(v) Marketing
In marketing, uses of computer are following:
Advertising - With computers, advertising professionals create art and graphics, write and
revise copy, and print and disseminate ads with the goal of selling more products.
At Home Shopping - Home shopping has been made possible through use of computerised
catalogues that provide access to product information and permit direct entry of orders to be
filled by the customers.
2
(vi) Health Care
Computers have become important part in hospitals, labs, and dispensaries. The computers are being
used in hospitals to keep the record of patients and medicines. It is also used in scanning and
diagnosing different diseases. ECG, EEG, Ultrasounds and CT Scans etc., are also done by
computerised machines. Some major fields of health care in which computers are used are:
Diagnostic System - Computers are used to collect data and identify cause of illness.
Lab-diagnostic System - All tests can be done and reports are prepared by computer.
Patient Monitoring System - These are used to check patient's signs for abnormality such as
in Cardiac Arrest, ECG etc.
Pharma Information System - Computer checks Drug-Labels, Expiry dates, harmful drug’s
side effects etc.
Surgery : Nowadays, computers are also used in performing surgery.
(viii) Military
Computers are largely used in defense. Modern tanks, missiles, weapons etc. Military also employs
computerized control systems. Some military areas where a computer has been used are:
Missile Control
Military Communication
Military Operation and Planning
Smart Weapons
(ix) Communication
Communication means to convey a message, an idea, a picture or speech that is received and
understood clearly and correctly by the person for whom it is meant for. Some main areas in this
category are:
E-mail
Chatting
Usenet
FTP
3
Telnet
Video-conferencing
(x) Government
Computers play an important role in government. Some major fields in this category are:
Budgets
Sales tax department
Income tax department
Male/Female ratio
Computerization of voters lists
Computerization of driving licensing system
Computerization of PAN card
Weather forecasting
Advantages
Vacuum tubes were the only electronic component available during those days.
Vacuum tube technology made possible to make electronic digital computers.
4
These computers could calculate data in millisecond.
Disadvantages
The computers were very large in size.
They consumed a large amount of energy.
They heated very soon due to thousands of vacuum tubes.
They were not very reliable.
Air conditioning was required.
Constant maintenance was required.
Non-portable.
Costly commercial production.
Limited commercial use.
Very slow speed.
Limited programming capabilities.
Used machine language only.
Used magnetic drums which provide very less data storage.
Used punch cards for input.
Not versatile and very faulty.
Advantages
Smaller in size as compared to the first generation computers.
The 2nd generation Computers were more reliable
Used less energy and were not heated.
Wider commercial use
Better portability as compared to the first generation computers.
Better speed and could calculate data in microseconds
Used faster peripherals like tape drives, magnetic disks, printer etc.
Used Assembly language instead of Machine language.
Accuracy improved.
5
Disadvantages
Cooling system was required
Constant maintenance was required
Commercial production was difficult
Only used for specific purposes
Costly and not versatile
Punch cards were used for input.
Advantages
Smaller in size as compared to previous generations.
More reliable.
Used less energy
Produced less heat as compared to the previous two generations of computers.
Better speed and could calculate data in nanoseconds.
Used fan for heat discharge to prevent damage.
Maintenance cost was low because hardware failure is reare.
Totally general purpose
Could be used for high-level languages.
Good storage
Versatile to an extent
Less expensive
Better accuracy
Commercial production increased.
Used mouse and keyboard for input.
Disadvantages
Air conditioning was required.
Highly sophisticated technology required for the manufacturing of IC chips.
6
Some computers of this generation were:
IBM-360 series Honeywell-6000 series
PDP(Personal Data Processor) IBM-370/168
TDC-316
Advantages
More powerful and reliable than previous generations.
Small in size
Fast processing power with less power consumption
Fan for heat discharging and thus to keep cold.
No air conditioning required.
Totally general purpose
Commercial production
Less need of repair.
Cheapest among all generations
All types of High level languages can be used in this type of computers
Disadvantages
The latest technology is required for manufacturing of Microprocessors.
8
1. Micro Computer or Personal Computer
A PC can be defined as a small, relatively inexpensive computer designed for an individual
user.
PCs are based on the microprocessor technology that enables manufacturers to put an entire
CPU on one chip.
Businesses use personal computers for word processing, accounting, desktop publishing, and
for running spreadsheet and database management applications.
At home, the most popular use for personal computers is playing games and surfing Internet.
Although personal computers are designed as single-user systems, these systems are
normally linked together to form a network. In terms of power, now-a-days High-end models
of the Macintosh and PC offer the same computing power and graphics capability as low-end
workstations by Sun Microsystems, Hewlett-Packard, and Dell.
9
(iii) Palmtop Computer/Digital Diary /Notebook /PDAs:
A small computer that literally fits in your palm. Compared to full-size computers, palmtops
are severely limited, but they are practical for certain functions such as phone books and
calendars.
Palmtops that use a pen rather than a keyboard for input are often called hand-held computers
or PDAs. Because of their small size, most palmtop computers do not include disk drives.
However, many contain PCMCIA slots in which you can insert disk drives, modems, memory,
and other devices.
Palmtops are also called PDAs, hand-held computers and pocket computers.
2. Mini Computer
A midsized computer. In size and power, minicomputers lie between workstations and
mainframes.
In the past decade, the distinction between large minicomputers and small mainframes has
blurred, however, as has the distinction between small minicomputers and workstations.
A minicomputer is a multiprocessing system capable of supporting from 4 to about 200 users
simultaneously.
3. Mainframe Computer
A very large and expensive computer capable of supporting hundreds, or even thousands, of
users simultaneously.
In the hierarchy that starts with a simple microprocessor (in watches, for example) at the
bottom and moves to supercomputers at the top, mainframes are just below supercomputers.
In some ways, mainframes are more powerful than supercomputers because they support
more simultaneous programs.
But supercomputers can execute a single program faster than a mainframe.
4. Supercomputer
A supercomputer is a computer with great speed and memory.
Supercomputers are very expensive and are employed for specialized applications that
require immense amounts of mathematical calculations.
This kind of computer can do jobs faster than any other computer of its generation.
They are usually thousands of times faster than ordinary personal computers made at that
time.
Supercomputers can do arithmetic jobs very fast, so they are used for weather forecasting,
code-breaking, genetic analysis and other jobs that need many calculations.
When new computers of all classes become more powerful, new ordinary computers are
made with powers that only supercomputers had in the past, while new supercomputers
continue to outclass them.
10
The chief difference between a supercomputer and a mainframe is that a supercomputer
channels all its power into executing a few programs as fast as possible, whereas a mainframe
uses its power to execute many programs concurrently.
Hardware
Hardware represents the physical and tangible components of a computer i.e. the components that
can be seen and touched. Examples of Hardware are following:
Input devices -- keyboard, mouse etc.
Output devices -- printer, monitor etc.
Secondary storage devices -- Hard disk, CD, DVD etc.
Internal components -- CPU, motherboard, RAM etc.
Software
Software is a set of programs, which is designed to perform a well-defined function. A program is a
sequence of instructions written to solve a particular problem. There are two types of software
System Software
Application Software
Input Unit
This unit contains devices with the help of which we enter data into computer. This unit makes link
between user and computer. The input devices translate the information into the form
understandable by computer. Following are few of the important input devices which are used in a
computer:
11
Keyboard Mouse Joy Stick
Light pen Track Ball Scanner
Graphic Tablet Microphone
Magnetic Ink Card Reader(MICR) Optical Character Reader(OCR)
Bar Code Reader Optical Mark Reader(OMR)
13
The memory from which we can only read but cannot write on it. This type of memory is non-
volatile.
The information is stored permanently in such memories during manufacture.
A ROM, stores such instructions that are required to start a computer. This operation is
referred to as bootstrap.
ROM chips are not only used in the computer but also in other electronic items like washing
machine and microwave oven.
Control Unit
This unit controls the operations of all parts of computer but does not carry out any actual data
processing operations. Functions of this unit are:
It is responsible for controlling the transfer of data and instructions among other units of a
computer.
It manages and coordinates all the units of the computer.
It obtains the instructions from the memory, interprets them, and directs the operation of the
computer.
It communicates with Input/Output devices for transfer of data or results from storage.
It does not process or store data.
Output Unit
Output unit consists of devices with the help of which we get the information from computer. This
unit is a link between computer and users. Output devices translate the computer's output into the
form understandable by users. Following are few of the important output devices which are used in a
computer.
Monitors
Graphic Plotter
Printer
14
1.7 Algorithm
An algorithm is a step-by-step procedure to solve a given problem. An algorithm is a representation
of a solution to a problem.
Example
1. Algorithm to find out number is odd or even
step 1 : start
step 2 : input number
step 3 : rem=number mod 2
step 4 : if rem=0 then
print "number even"
else
print "number odd"
endif
step 5 : stop
1.8 Flowchart
A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the
steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic
representation illustrates a solution model to a given problem. Flowcharts are used in analyzing,
designing, documenting or managing a process or program in various fields.
Flowcharting Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language programs: Terminal,
Process, input/output, Decision, Connector and Predefined Process. This is not a complete list of all
the possible flowcharting symbols, it is the ones used most often in the structure of Assembly
language programming.
15
General Rules for flowcharting
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The
exit point for all flow
chart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long
as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart.
Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more then 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
16
Example of a flowchart (Finding Factorial of a number)
1.9 Pseudocode
Pseudocode is an informal high-level description of the operating principle of a computer program or
other algorithm. It uses the structural conventions of a programming language, but is intended for
human reading rather than machine reading.
Example
Pseudocode to swap two numbers
swap(a, b)
t <- a
a <- b
b <- t
return a, b
17
UNIT –II
C is often called a "Middle Level" programming language. This is not a reflection on its lack of
programming power but more a reflection on its capability to access the system's low level functions.
Most high-level languages (e.g. Fortran) provides everything the programmer might want to do
already built into the language. A low level language (e.g. assembler) provides nothing other than
access to the machines basic instruction set.
2.1 Characteristics of C
Well suited for structured modular programming.
Robust language with rich set of built-in functions and operators.
Has minimal instruction set and programs written in are efficient and fast.
Highly portable.
Highly flexible.
Allows access to the machine at bit level (Low level (Bitwise) programming).
Supports pointer implementation -extensive use of pointers for arrays, structures, and
functions.
Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Section
Executable part
}
Subprogram section
Function 1
Function 2
..
function n
The Documentation Section consists of a set of comment lines giving the name of the program and
other details.
The Link Section provides instructions to the compiler to link functions from the system library.
18
The Definition Section defines all symbolic constants.
The Global Declaration Section: There are some variables and those variables are declared in this
section that is outside of all functions.
main() function: Every C program must have one main function section. This section contains two
parts, declaration and executable part.
Declaration Part declares all the variables used in the executable part.
There should be at least one statement in the executable part which contains instructions to
perform certain task.
The declaration and executable part must appear between the opening and closing braces. All
statements in the declaration part should end with the semicolon.
The Subprogram Section contains all the user defined functions that are called in the main function.
Example Program
/*Documentation Section: program to find the area of circle*/
#include "stdio.h" /*link section*/
#include "conio.h" /*link section*/
#define PI 3.14 /*definition section*/
float area; /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circle\n"); /*executable part starts here*/
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}
Note
C is a case sensitive programming language. It means in C printf and Printf will have different
meanings.
C has a free-form line structure. End of each C statement must be marked with a semicolon.
Multiple statements can be one the same line.
White Spaces (ie tab space and space bar ) are ignored.
Statements can continue over multiple lines.
19
(i) Preprocessor
The Preprocessor accepts source code as input and interprets special preprocessor directives
denoted by #.
It is also responsible for removing comments and empty programming lines.
(ii) Translator
A translator is a computer program that performs the translation of a program written in a given
programming language into a functionally equivalent program in a different computer language,
without losing the functional or logical structure of the original code.
Compiler
A compiler is a program that takes a input program on one programming language (source language)
and produces output in another language (object language or target language).
Interpreter
An interpreter is another common kind of language processor. Instead of producing a target program
as a translation, an interpreter appears to directly execute the operations specified in the source
program on inputs supplied by the user.
20
Assembler
Assembler which converts assembly language programs into object files. Object files contain a
combination of machine instructions, data, and information needed to place instructions properly in
memory.
2.4 Features of C
o Low level language support
o Program portability
o Powerful and Feature Rich
o Bit Manipulation
o High Level Features
o Modular Programming
o Efficient use of Pointers
21
Symbol Meaning Symbol Meaning
~ Tilde - Minus sign
! Exclamation mark = Equal to sign
# Number sign { Left brace
$ Dollar sign } Right brace
% Percent sign [ Left bracket
^ Caret ] Right bracket
& Ampersand : Colon
* Asterisk " Quotation mark
( Lest parenthesis ; Semicolon
) Right parenthesis < Opening angle
bracket
_ Underscore > Closing angle bracket
+ Plus sign ? Question mark
| Vertical bar , Comma
\ Backslash . Period
` Apostrophe / Slash
Escape Sequences
Escape Escape
Description Description
Sequence Sequence
\a Audible alert(bell) \v Vertical tab
\b Backspace \\ Backslash
Double quotation
\f Form feed \”
mark
\n New line \’ Single quotation mark
\r Carriage return \? Question mark
\t Horizontal tab \0 Null
22
2.6 Tokens
A token is a sequence of characters that is understood as a unit. Tokens are the basic building
blocks of a C program. C tokens fall roughly into the six categories listed below.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords
C keywords are the words that convey a special meaning to the c compiler. The keywords cannot be
used as variable names because by doing so, we are trying to assign a new meaning to the keyword
which is not allowed. The list of C keywords is given below:
2. Identifiers
Each program elements in a C program are given a name called identifiers. Names given to
identify Variables, functions and arrays are examples for identifiers. eg. x is a name given to integer
variable in above program.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore (_).
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only first 31 characters are significant.
23
Examples of unacceptable identifiers are:
Bas ic (blank not allowed)
H, rent (special character `, ' included)
It may be noted here that TOTAL and total are two different identifier names.
3. Constants
C Constants refers to the data items that do not change their value during the program execution.
Several types of C constants are available in C.
Types of C constant
Real Constants
1. A real constant must have at least one digit
2. It must have a decimal point
3. It could be either positive or negative
4. If no sign precedes an integer constant, it is assumed to be positive.
5. No commas or blanks are allowed within a real constant.
Character constants
1. A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas. Both the inverted commas should point to
left.
2. For example, ’C’ is a valid character constant whereas ‘C’ is not.
3. The maximum length of a character constant is 1 character
25
Carriage
\r \? Question mark
return
Octal constant (N is an octal
\t Horizontal tab \N
constant)
Hexadecimal constant (N –
\” Double quote \XN
hex.dcml cnst)
\’ Single quote \\ Backslash
4. Strings
Strings are sequence of characters enclosed within double quotes. For example,
“hello”, “abc”, “hello911″
Every string constant is automatically terminated with a special character ‘\0′ called the null
character which represents the end of the string.
For example, “hello” will represent “hello\0″ in the memory.
Thus, the size of the string is the total number of characters plus one for the null character.
5. Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be used
for some other purpose.
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and function parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These indicate single
and multidimensional subscripts.
6. Operators
The symbols which are used to perform logical and mathematical operations are called C
operators.
These C operators join individual constants and variables to form expressions. Operators,
functions, constants and variables are combined together to form expressions.
Example : A + B * 5
where,
+, * - operators
A, B - variables
5 – constant
A + B * 5 - expression
26
2.7 Data Types
Data type is nothing but the type of data that can be stored in the variables. It plays a dynamic role in C
programs. Any variables that should be declared with the corresponding data type before using it. This data
type is used to define the size of memory that is needed for the variable. For example, if any variable that
should be declared as int, and then it occupies only two bytes of memory. Based on the data type declared
for the variables, the memory is going to be allocated. Suppose, if the value which are assigned to the
variable is mismatched, then it displays an error. In C, there are four major data types are used such as
basic data type, enumerated data type derived data type and void data type.
Integer Data Character Data Floating Point Type Double Data Type
Type Type
Keyword int char float double
The integer data This data type Floating point data type is one of the basic data
Definition type which which allows a types which allows too define floating point
allows the variable to store numbers or real numbers. It may be of 2 types.
variable to store only one One is float and another one double.
numeric values. character.
4 bytes (six 4 bytes (ten
Size 2 bytes 1 byte decimal fraction) decimal fraction)
-32,768 to 1E–37 to 1E+37 with 1E–37 to 1E+37
Range +32,767 –127 to 127 six digits of precision with ten digits of
precision
C – Modifiers
The modifier which allows the amount of memory space to be allocated for the given variable. Modifiers
are prefixed with basic data types to modify (either increase or decrease) the amount of storage space
allocated to a variable. For example, storage space for int data type is 4 byte for 32 bit processor. We can
increase the range by using long int which is 8 byte. We can decrease the range by using short int which is
2 byte. There are 5 modifiers available in C language.
27
They are,
1. short
2. long
3. signed
4. unsigned
5. long long
Table gives the detail about the storage size of each C basic data type in 16 bit processor.
Data Storage
Modifiers Range
Types Size
char char 1 –127 to 127
int 2 –32,767 to 32,767
long int 4 –2,147,483,647 to 2,147,483,647
short int 2 –32,767 to 32,767
unsigned short int 2 0 to 65,535
int signed short int 2 –32,767 to 32,767
long long int 8 –(2power(63) –1) to 2(power)63 –1
signed long int 4 –2,147,483,647 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
unsigned long long int 8 2(power)64 –1
float 4 1E–37 to 1E+37 with six digits of precision
float double 8 1E–37 to 1E+37 with ten digits of precision
long double 10 1E–37 to 1E+37 with ten digits of precision
Syntax
enum identifier { enumerator-list }
Example
enum colour { green, red, blue, white }
The variables will be assigned by the values that start from 0. Green=0, red=1, blue=2 and white=3.
enum colour { green=1, red, blue, white}
The value 1 is assigned to green by default. The values for the next variables are incremented from the
default value 1. Now red=2, blue=3 and white=4.
28
3. Derived data type
The derived data type is not created; which is to be derived from the basic data types. The examples
are Array, pointer, structure and union. All these derived data types will be explained in the upcoming
chapters.
2.8 Operators
An operator is a symbol that specifies which operation to perform in a statement or expression. An
operand is one of the inputs of an operator. For example, in expression b+c, + is the operator and b
and c are the operands. Operators follow a strict precedence, which defines the evaluation order of
expressions containing these operators. Operators with the same precedence associate with either
the expression on their left or the expression on their right, depending on their associativity. C
language supports following type of operators.
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operators
Bitwise Operators
Special Operators
1. Arithmetic Operators
This operator which helps to perform the basic arithmetic or mathematic operations such as
addition, subtraction, multiplication, division and modulo operation. The arithmetic operators which
are used in the arithmetic expressions are ‘+’ (addition), ‘-‘(subtraction), ‘*’(multiplication), ‘/’
division and ‘%’ for modulo division.
To perform arithmetic operations, we need two operands. One is placed in the left side of the
operators and another one operand is placed in the right side of the operator. It is also called as the
binary operators, since it uses two operands for evaluation. After the evaluation is carried out, the
result will be stored in another variable which are placed in the left side of the expression.
29
- Subtraction 4 -2 = 2
* Multiplication 2*5 = 10
/ Division 6/2 = 3
% Modulo division 10/3= 1
Sample Program
#include <stdio.h>
#include <conio.h>
int main()
{
int a=2,b=3,c;
c=a+b; //Arithmetic operation
printf("\n Addition of 2 numbers are %d", c);
return 0;
}
Output
Addition of 2 numbers are 5
2. Relational Operators
This relational operator is used to compare the values of two or more operands. Operands that may
be variables, constants or expression. This operator is also having two operands for processing. One
is placed in the left and another one is placed in the right side of the operator. There are six relational
operators are there and the result of these operators will be either 0(FALSE) or 1(TRUE).
This relational operators can be used in the ordinary statements or branching statements.
Sample Program
#include <stdio.h>
#include <conio.h>
30
int main()
{
int a=2,b=3,c;
c=a>b;
printf("\n Result is %d", c);
return 0;
}
Output
Result is 0
3. Logical Operators
This operator is used to combine the results of two or more relational expressions. There are three
logical operators are there: and, or, not. The operators are:
The logical operators AND and OR which have the expressions on both side of the operator. For NOT
operator, the expression will be placed in the right side of the operator only. The result of the logical
operators will be either 0(FALSE) or 1(TRUE).
The logical AND operator returns TRUE if both the expressions are TRUE. Otherwise it returns
FALSE. The logical AND operator. The logical OR operator returns FALSE if both the expressions are
FALSE. Otherwise it returns TRUE. The logical NOT operator returns TREU if the expression is FALSE.
Otherwise it returns TRUE.
31
Sample Program
#include <stdio.h>
#include <conio.h>
int main()
{
int a=2,b=3,c=5,d,e,f,g;
d=a>b && b<c;
e=a>b || b<c;
f=!a>b;
g=(a>b)&&(b>c)||(a<c);
printf("\n Result of AND operator is %d", d);
printf("\n Result of OR operator is %d", e);
printf("\n Result of NOT operator is %d", f);
printf("\n Result of All operators is %d", g);
return 0;
}
Output
Result of AND operator is 0
Result of OR operator is 1
Result of NOT operator is 0
Result of All operators is 1
4. Assignment Operators
The assignment operator ‘=’ is used to assign the value of expression to the variable which is placed
in the left side. The expression may be a constant or variable or expression. The general syntax is:
Variable = Expression;
For example, a=5 // constant 5 is assigned to the variable a
a=c; // value of c is assigned to a
a= b+c*d; // The expression b+c*d is evaluated and store the result in a.
32
The increment operator which can be of two types: Pre increment operator and post increment
operator. In pre increment operator, the operator is placed before the operands. For example ++a
which increment the value of a by 1 and use its value later. In post increment operator, the operator
is placed after the operands. For example, a++ which use the value of a first and then increase its
value by 1.
The decrement operator which can be of two types: Pre decrement operator and post decrement
operator. In pre decrement operator, the operator is placed before the operands. For example --a
which decrement the value of a by 1 and use its value later. In post decrement operator, the operator
is placed after the operands. For example, a-- which use the value of a first and then decrease its
value by 1.
Sample Program
#include <stdio.h>
int main()
{
int c=2;
printf("%d\n",c++); //this statement displays c and then, incremented.
printf("%d",++c); //this statement increments c and then displayed.
printf("%d\n",c--); //this statement displays c and then, decremented.
printf("%d",--c); //this statement decrements c and then displayed.
return 0;
}
Output
2
4
4
2
6. Conditional Operators
Conditional operators or the ternary operators are used for decision making in C. The operator are
question mark (?) and the colon (: ). The general syntax is:
Variable = condition? exp1: exp2
The ‘?’ operator act as ternary operator, it first evaluate the condition, if it is true then exp1 is
evaluated or exp2 is evaluated. The result of either exp1 or exp2 is assigned to the left side variable.
33
Sample Program
#include <stdio.h>
int main()
{
int a=2,b=3,ans;
ans=a>b?a:b; //ternary operator
printf("%d",ans);
return 0;
}
Output
3
7. Bitwise Operators
A bitwise operation operates on one or more bit patterns or binary numerals at the level of their
individual bits. Bitwise operators are used in bit level programming. The bitwise operators are
shown in the table
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement
All the bitwise operators are the binary operators, since it takes two (binary) operands. The operator
is placed between left operand and the right operand. The truth table for the Bitwise AND, OR and
XOR operator is shown in table.
34
Sample Program
#include <stdio.h>
int main()
{
int a=12,b=6;
printf(“\n Result of Bitwise AND is %d”,a&b);
printf(“\n Result of Bitwise OR is %d”,a|b);
printf(“\n Result of Bitwise XOR is %d”,a^b);
printf(“\n Result of Bitwise Left Shift is %d”,a<<b);
printf(“\n Result of Bitwise Right Shift is %d”,a>>b);
return 0;
}
Output
Result of Bitwise AND is 4
Result of Bitwise OR is 14
Result of Bitwise XOR is 10
Result of Bitwise Left Shift is 768
Result of Bitwise Right Shift is 0
8. Special Operators
Some special operators are also available in C. They are
Sample Program
#include <stdio.h>
void main()
{
int a; float b; double c; char d;
printf("Size of int=%d bytes\n",sizeof(a));
35
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
}
Output
Size of int=4 bytes
Size of float=4 bytes
Size of double=8 bytes
Size of char=1 byte
36