Rvised Module 1 PSP Notes
Rvised Module 1 PSP Notes
INTRODUCTION
COMPUTER GENERATIONS
The computer of each generation is smaller, faster and more powerful than preceding generation. There are
five computer generations.
First Generation: The vacuum tubes were used for computation. Magnetic drums were used
for memory requirements. It consumed lot of space, power and generated lot of power. ENIAC
(Electronic Numerical Integrator and Computer) used 18000 vacuum tubes, 1800 acquired sq. ft. room
space and consumed 180KW of power. The machine level language (0s and 1s) was used. Punched
cards were used for input and Paper for output. They were used for scientific work.
Second Generation: The transistors was the most important component which replaced
vacuum tubes. Magnetic cores were used for memory. It were more reliable than first generation
computer. The assembly or symbolic language was used. The input and output mechanism remained
same. The stored program concept was introduced which stores both data and program.
Third Generation: The Integrated circuits(IC) was the most important component. The
transistors, diodes, resistors, capacitors were integrated on a single chip. The high-level language
was used like BASIC, C, C++ and JAVA. Memory capacity increased and magnetic hard disk was
used for secondary generation. The third generation computers also had OS and computer could rum
programs invoked by multi users.
Fourth Generation: The Microprocessor was the most important component. With the help
of LSI (Large Scale Integration) and VLSI (Very Large Scale Integration) the entire CPU is on a
single chip. OS have moved from MSDOS to GUI (Graphical User Interface) like windows. The
networking technology has also been improved. The size was reduced and the speed was increased.
Fifth Generation: Artificial Intelligence and use of natural languages are the main features
of this generations. These systems are expected to interact with users in natural language. Speech
recognition and speech output should also be possible. Computers must be
MODULE -1 PSP NOTES
able to perform parallel processing. The quad-core and octa-core was also introduced. Neural
networks and expert systems have been developed.
COMPUTER TYPES
Apart from being classified by generations, computers can also be categorized by their size. The size
of a computer is often an indirect indication of its capabilities.
Supercomputers: These are huge machines having most powerful and fastest processors. It
uses multiple CPUs for parallel data processing. Speeds are measured in flops (floating point
operations per second). The fastest operates at 34 petaflops. They are used for weather forecasting,
analysis of geological data. They have enormous storage, uses more power and generate lot of heat.
They are used by government agencies.
Mainframes: These are multi-user machines that support many users using the feature of
time sharing. It can run multiple programs even with a single CPU. The processor speed is
measured in MIPS (Million instructions per second). It is used to handle data, applications related to
organization and online transactions in banks, financial institutions and large corporations.
Special-purpose registers
A clock
The ALU is a “super calculator” carrying out all arithmetic tasks and Boolean operations (like
AND, OR and NOT). The CU controls the way data is moved between the various components of
computer. Both ALU and CU use the service of clock for synchronizing their Operations.
The CPU uses a few high-speed registers to store the current instruction and its data. One of
the registers, program counter, stores the address of next instruction to be executed. All program
instructions are executed using the fetch-decode-execute mechanism. An instruction is first fetched
from memory, decoded and then executed by CPU. The CPU can execute one instruction in one
clock pulse. Hence, faster the clock, faster is the execution. The CPUs today are rated in GHz
(gigahertz).
PRIMARY MEMORY
Memory: Collection of chips on motherboard, where all computer processing and
program instructions are stored.
Primary Memory: It is the main memory, which stores data and programs, which are currently
needed by CPU. The size is less than the secondary memory and it is costly.
1. RAM (Random Access Memory): It is the main memory, where the user can write
information into RAM and read information from it. It is accessible to users. The RAM is
randomly accessible by user. It is a volatile memory, which means the data, or information is
retained as long as power supply is ON. There are two types of RAM: SRAM and DRAM.
2. ROM (Read Only Memory): It is a permanent memory that canbe read but not written. It is
a non volatile memory, which means the data or information is retained even power supply is
not there. It contains a startup program BIOS (Basic Input Output System) which transfers
control to OS.
PROM (Programmable Read Only Memory): It is programmed as per requirement of
customer’s choice. The programmer burns the data into PROM. The data once written
cannot be changed.
MODULE -1 PSP NOTES
EPROM (Erasable Programmable Read Only Memory): It can be rewritten (but only
once) even though it has been previously burned. It is erased by exposing it to UV-rays.
3. Cache Memory: It holds those portions of program that are frequently used by CPU. It acts
as a buffer between CPU and RAM. The CPU first looks for the instructions in cache. It
executes faster than RAM, expensive and limited in size. It has multiple levels:
L1 (Level 1) – smallest and fastest – 32 KB
L2 (Level 2) – present closer to CPU – 256 KB
L3 (Level 3) – shared by cores – 8 MB
4. Registers: The small number of ultra-fast registers integrated into the CPU represent the fastest
memory of the computer. The CPU does all its work here. Each register has the length of the
computer. The data is loaded into register before processing. Registers are numbered and a
program instruction specifies these numbers. Ex: OR1R2R3 which means multiplication
operation is performed on R1 and R2 is performed and stored in R3.
SECONDARY MEMORY
Secondary memory is not directly connected to CPU. It exists inside the machine and also
externally. It is a non-volatile, offline and long-term storage memory. It is slower, cheaper than
primary memory but the capacity is higher.
1. Hard disk/ Hard drive/ Fixed disk: It is the oldest secondary storage device. It has more
capacity but, the cost is less comparatively. It is commonly present in laptop with 500GB and
desktop with 1TB. It contains a spindle, which holds one or more platters made up of non-
magnetic material. It has two surfaces which is coated with magnetic material. Each surface
has serially numbered tracks and further broken into sectors or blocks. The disk runs with the
speed of 5400 and 7200 rpm.
2. Magnetic tape: The magnetic tape is made up of plastic film with one side coated with
magnetic material. It supports 1 TB or more, but 200 TB are also expected. The device is not
fully portable though because, a separate tape drive is required. The data is accessed
sequentially. This makes it unsuitable for backup.
3. Optical Disks (CD-ROM, DVD ROM, Blu-ray Disk): It is non-volatile read-only memory.
The CD-ROM and DVD-ROM, can hold large volumes of data (700MB to 8.5 GB). The Blu-
MODULE -1 PSP NOTES
ray disk has the capacity upto 50 GB. A laser beam in their drives controls the read and write
operations. A laser beam is used to construct pits and lands by burning selected areas along
its tracks.
CD-R, DVD-R: Data can be recorded only once.
CD-RW, DVD-RW: Data can be recorded multiple times.
4. Flash Memory: It doesn’t have any moving parts, is based on the EEPROM. It is available
in various forms- pen drive, magnetic card (SD Card), solid state disk (SSD). They are
portable, need little power and quite reliable.
The memory stick or pen drive is the most common type of flash memory used on the
computer. It is a small, removable piece of circuit and it connects to the USB port of
computer. The solid state disk is a bigger device meant to replace the traditional magnetic
hard disk.
The magnetic card is used mainly in cameras and the most popular is the micro- SD card.
5. Floppy Diskette: This is represented by a rectangular plastic case containing a thin magnetic
disk. It was available in two sizes (5.25” and 3.5”), offering capacities of 1.2 MB and 1. MB.
It is unsuitable for backup purpose
Stores the programs and data It is used to store large amount of data and
currently needed by the CPU. programs
Expensive. Inexpensive.
Volatile in nature. Non-volatile in nature.
SERIAL PORT: This port transfers one bit at a time serially. They are offered in 9-pin and
25- pin configuration. They were used for connecting keyboard, mice, and modems.
PARALLEL PORT: This port is used to transfer data parallelly 8 bits at a time. This is
implemented using 25 pins and usually for printers.
VGA (Video Graphics Array): This 15-pin port allows transfer of analog video data to the
monitor. This is replaced with DVI (Digital Video Interface) which uses digital data i.e. used by flat
LCD panels.
RJ45 port: This port is used by Ethernet network. Even though computer connects
wirelessly, the wired RJ45 remains as a useful option.
PS/2 port: This port has replaced serial port. It has 6 pins but occurs as a pair in two
different colors. The ports and connectors for keyboard are purple, while the mouse uses green port.
USB has invaded this area also.
HDMI (High Definition Multimedia Interface): This is used for transferring audio and video
between computers and HDTVs, projectors and home theaters
INPUT DEVICES
Input devices are needed to interact with the OS to perform tasks. Ex: Keyboard,
Mouse, Joystick, Stylus, Scanner etc.
Pointing Devices: GUI (Graphical User Interfaces) like windows need a pointing device to
control the movement of cursor on the screen. This is implemented as mouse in desktop and
touchpad in laptop. The earliest form has a rotating ball and two buttons. The left button is used for
selecting (by clicking once) and execute (by clicking twice). The right button is used to check and change
attributes. The optical mouse uses infrared laser/LED, the wireless mouse uses radio frequency
technology.
Scanner: A scanner is a device that creates a digital image of a document by optically scanning
it. The flatbed scanner doesn’t exceed more than A4 size. It is operated with by using special software.
The document to be scanned is placed on a glass plate covered by lid. Modern
MODULE -1 PSP NOTES
scanners have OCR (Optical Character Recognition) facility which extracts text as a stream of
characters i.e. converting image file to text file and MICR (Magnetic Ink Character Recognition)
reads the codes using hand held barcode readers.
OUTPUT DEVICES
The information produced can be heard or seen with the help of output devices. Some of the
output devices are monitor, speaker, printer, plotter etc.
Monitor: The monitor is an integral part of computer which displays both text and graphics.
The performance is measured in terms of image quality, resolution, energy consumption.
CRT (Cathode Ray Tube) Monitors: The CRT monitors have a rarefied tube containing three
electron guns. The guns emit electrons create images. They usually have resolution of 640*840
pixels. They are large, heavy, energy efficient and produces lot of heat.
LCD (Liquid Crystal Display) Monitors: The image is formed by applying voltage on crystals.
The backlight is provided by fluorescent light. They consume less power, generate less heat and
have increased life span.
Impact Printers: It produces the hardcopy of output. The impact printers are old, noisy. But,
still dot-matrix printer is in usage.
Dot-Matrix Printer: The print head of the dot-matrix printer has either 9 or 24 pins. When the pins
fire against the ribbon, an impression is created on the paper. The speed is 300 cps and doesn’t produce
high quality output. It can produce multiple copies.
Daisy-wheel Printer: It employs a wheel with separate characters distributed along its outer edge.
The wheels can be changed to obtain different set of fonts.
Line Printer: For heavy printing, the line printer is used. It uses a print chain containing the
characters. Hammers strike the paper to print and it rotates at the speed of 1200 lpm. It is also noisy
and is of low-quality.
Non-Impact Printers: They are fast, quiet and of high resolution. The most commonly used
non-impact printers are laser and ink-jet printers. The thermal printer is not discussed here because
it uses heat to print on high-sensitive paper.
Laser Printer: It works like a photocopier and uses toner i.e. black magnetic powder. The image is
created in the form of dots and passed from drums on to the paper. It has built-in RAM which acts
as buffer and RAM to store fonts. The resolution varies from 300 dpi to 1200 dpi and the speed is
about 20 ppm.
Ink-jet Printer: These are affordable printers. It sprays tiny drops of ink at high pressure as it
moves along the paper. The separate cartridges are available for different colors. The resolution is
about 300 dpi, can print 1 to 6 pages/min.
MODULE -1 PSP NOTES
Plotters: The plotter can make drawings. It uses one or more automated pens. The
commands are taken from special file called vector graphic files. Depending on type of plotter either
paper or pen moves. It can handle large paper sizes and it is used for creative drawings like
buildings and machines. They are slow and expensive.
COMPUTERS IN A NETWORK
Most organizations, large or small, no longer have standalone computers. Computers cooperate with
one another by being connected in a network. The hardware resources can also be shared. A printer
can be used by several users if it is connected to a network. Servers form the backbone of the largest
network of all – Internet. Ethernet, token ring hardware technologies are used to connect.
Network Topology: The ways used to connect the computers. The different types are: Bus,
Star, Ring, and Mesh.
Network Types: Networks are also classified on their size. The most common types
are LAN and WAN. And some other types are: MAN, CAN and PAN.
1. LAN (Local Area Network): They are used in smaller organizations usually using Ethernet.
The usual speed will be 100Mbps.
MODULE -1 PSP NOTES
2. WAN (Wide Area Network): They are used in cities and can connect larger distance. They
use optic fiber cables. Banks, Airline and Hotel reservations use WANs.
3. MAN (Metropolitan Area Network): It is sandwiched between LAN and WAN and
used for interconnecting in same cities.
4. PAN (Personal Area Network): This is the smallest network and can connect only
few meters. It connects small devices like phones, laptops through Bluetooth.
The Internet and internet: The internet (net) is the largest wide area network on planet
which runs with the help of network protocols. It grows continuously without disturbing the existing
structure. Intranet is a network of computers designed for a specific group of users and can be accessed
from Internet but with restrictions. Internet is wide network of computers and is open for all and
itself contains a large number of intranets.
Note: The Internet (uppercase-I) is the set of all networks which are interconnected and interoperate
using the IETF standard protocols. An internet (lowercase-i) is any network of devices which can
communicate with each other.
NETWORK HARDWARE
Connecting computers in a network require additional devices that are not part of the computer’s basic
configuration.
Hub and Switch: Computers in a single network is connected to a central device called hub
or switch. HUB accepts network data from computer and broadcasts to the nodes by checking
destination address. SWITCH will have a table which contains MAC addresses of connected
devices. The data is sent after looking up the table for destination.
Bridge and Router: The network supports many nodes which leads to congestion. Hence,
the network may be split into a number of segments, with a BRIDGE connecting them. It connects
two networks using the same protocol. ROUTER connects two similar or dissimilar networks
separated by long distance. It is a part of two networks and thus have two addresses. It has a routing
table to store address.
SOFTWARE BASICS
Software is a collection of code that drives a computer to perform related group of tasks.
Programs in software use a language.
The source code is created by programmer using programming languages like C, C++,
Java, Python etc.
The software is developed to operate on multiple platforms.
SOFTWARE TYPES
MODULE -1 PSP NOTES
Computer software can be broadly classified into two types: System software and Application
Software.
System Software: Software run by the computer to manage the hardware connected to it is
known as system software. System software examples:
BIOS- It checks the hardware devices and peripherals at boot time.
OS: It manages both hardware and programs running on the computer.
Application Software: Software not directly connected with hardware but related to a
specific application is known as application software. Application software examples: Office
software: This comprises of three separate applications: word processing, spread sheet and
presentations.
Database software: It allows data to have a uniform structure to be stored in a database.
MODULE 1
CHAPTER 2: OVERVIEW OF C
Pseudocode
Pseudocode is a type of structured English written in natural language, to describe set
of rules for step-by-step processes, problem solving operations or other calculations.
It is informal, high level description of a computer program intended for human
reading rather than machine reading.
The aim for writing pseudocode is to get idea quickly.
There are no structure rules for writing pseudocode and it doesn’t require program
syntax.
It is used in planning of computer program development, for sketching out the
structure of the program before the actual coding takes place.
Advantages:
1. It can be written easily
2. It can be read and understood easily
3. Modification is easy
4. It implements structured concepts
easily Disadvantages:
1. It is not visual
2. There is no standardized style or format, so one pseudocode may vary from other
for same problem statement
Examples:
HISTORY OF C
C is a general purpose, procedural, structured computer programming
language developed by Dennis Ritchie in the year 1972 at AT&T Bell Labs.
C language was developed on UNIX and was invented to write UNIX
system software.
C is a successor of B language.
There are different C standards: K&R C std, ANSI C, ISO
C. Characteristics of C:
C is easy to learn.
C is a general purpose language.
C is a structured and procedural language.
It is portable.
It can extend
itself. Examples of C:
Operating system
Language compilers
Assemblers
Text editors
Databases
C Character Set:
A C character set defines the valid characters that can be used in a
source program. The basic C character set are:
1. Letters: Uppercase: A,B,C,….,D
Lowercase: a,b,c,…..,d
2. Digits: 0,1,2,…..,9
3. Special characters: ! , . # $ ( ) } { etc
4. White spaces: Blank space, Horizontal tab space, carriage return, new
line character, form feed character.
Basic structure of C Program
C program consists of different sections. The structure of C program is as
shown below.
Documentation Section: It consists of “comments” which increases the
readability of program. The comments are not processed by the compiler. There are
two types of comments:
a) Single line comment(Only one line) //Single line comment
MODULE -1 PSP NOTES
Declaration part
Executable
} part
Sub program section
Function 1
Function 2
-
-
Function n
Module
1
Module 1: Introduction to computer hardware and software and overview of C:
Computer generations, Computer types, Bits, bytes and words, CPU, Primary memory,
secondary memory, Ports and connections, input devices, output devices Computer in a
network, network hardware Software basics, software types Basic structure of a C
program, executing a c program. Constant, variables Data types Operators and
expressions
Here is a small program that displays a sentence “Welcome to C world ” on the monitor screen:
/* C program to display welcome to C world
*/ #include<stdio.h>
void main( )
Module
1
{
printf(“Welcome to C World”);
}
This program doesn’t have all the parts of typical C program.
The first line begins with /* and ending with */ is the comment line which is used to
enhance program readability and understanding.
The second line It has preprocessor directive #include which includes a header file
stdio.h, the standard input /output headerfile . The definitions of printf and scanf
functions are defined in this headerfile. Hence this line we need to include.
The third line is main(), this is the special function used by C system to tell where the
program starts. Every program have exactly one main function. The empty pair of
parenthesis following main indicates that main has no arguments. Void indicates that
main function does not return any value to operating system. By default main returns
integer value to operating system.
The opening brace “{ “ in the 4 th line marks the beginning of the function main and
closing brace “}” at the last line indicates the end of the function.
All the statements between these braces form the function body. The function body
contains set of instruction to perform the given task.
In this program the function body contains only one executable statement printf. The
printf is a predefined function for printing output. It prints everything within the double
quote. In this it will print Welcome to C World on the monitor.
C Tokens: In C program the smallest logically meaning full individual units are known as c
tokens. C has 6 Different types of tokens. C programs are written using these tokens and syntax
of the language.
1. Identifier Example :sum ,amount
2. Keywords Example: float, while
3. Constants Example: -15.5, 100
4. Strings Example: “abc”, “hello”
5. Special symbols Example: {},[]
6. Operator Example:+,-,/
Keyword: Keyword or reserved word have predefined meanings and these meanings cannot be
changed. Keyword serves as building blocks for program statements. All keywords are in
lowercase letters. Below table shows all keywords in ANSI C.
Constants: They are data values that do not change during program execution. Main types of
constants are:
1. Integer constants
2. Real constants
3. Character constants
4. Enumeration-constant
5. Coding constants
a. Literal constants
b. Defined constants
c. Memory constants
Integer constants are numerals without decimal portions. By default all C language integers
are of signed integer type. An integer constant consisting of a sequence of digits is taken to be
octal if it begins with 0 (digit zero), decimal otherwise. Octal constants do not contain the
digits 8 or
9. A sequence of digits preceded by 0x or 0X (digit zero) is taken to be a hexadecimal integer.
The hexadecimal digits include a or A through f or F with values 10 through 15.
An integer constant may be suffixed by the letter u or U, to specify that it is unsigned. It
may also be suffixed by the letter l or L to specify that it is long. Various integer constants
examples are given in the table:
Character constants can be single character enclosed within single quotes or a ‘\’ (backslash)
followed by any character. ‘\’ is called escape character as it alters the meaning of character
following it. Following are the complete list of escape sequence.
String constants: String constants are sequences of characters enclosed in double quotes.
The character may be letters, numbers, special characters and blank space.
Following table gives some examples of character constants and string constants
Coding constants:
First let us discuss literal constants, Literal constants are unnamed constants usually used in C
expressions. Some examples are given in following table:
Example Value Type
6 6 Integer literal constant
A+7 7 Integer literal constant
7.5+c+d 7.5 Real/double constant
‘A’ + 10 ASCII value of A and 10 Character and integer
constants
Next is define constants, they are defined in the beginning of program along with
preprocessor directives like #include<stdio.h>
Examples: #define PI 3.147
#define RATE_INTEREST 10
Once we define such values, we can use names like PI, SQR throughout the C programs with
the specified values. That is wherever PI is used it is substituted with 3.147 and
RATE_INTEREST with 10.
The final member of coding constants is memory constants. Memory constants are specified
with help of a type specifier called const.
Example:
const float pi =3.147
const keyword makes memory location called ‘pi’ to have a constant value 3.147 throughout
program execution
Data Types: A data type defines the type of data that is stored in a variable. A data in a
variable can be any type for example data can be either numeric or string. A data type
determines how much storage memory should be allocated to a variable. ANSI C supports
three classes of data type
1. Primary or build in or fundamental data type (int, char, float, double, void)
2. Derived data type (arrays, structures, functions, pointers, unions)
3. User defined data type (typedef, enum)
Here we will be discussing only fundamental datatype. Other will be discussed in latter units.
All C compiler support five fundamental data types namely
1. Integer (int)
2. Floating point (float)
3. Character (char)
4. Double precision floating point (double) and
5. void
Integer type: Integers are whole numbers with range of values supported by particular
machine. Data type that can store non-decimal numbers in memory. The keyword int is used to
declare variables of integer type. For 16 bit machine the range of integer is -32768 to
+32767. In order to control over the range of numbers and storage space, C has three classes of
Module
1
integers.
Signed Numbers:
Data type Keyword Size in Size in Bits Maximum Range of value
Bytes that can be stored
Signed signed 1 8 bits(7 bits for 27 = -128 to 0-127
short short int magnitude
integer 1 bit for sign)
Integer signed int 2 16 bits (15 bits for 215=-32768 to 0-32767
magnitude 1 bit for
sign)
Long long int 4 32 231=-2147483648
integer To 0-2147483648
Sign bit=1 means negative number
Sign bit=0 means positive number
Floating point type: data type that can store decimal numbers in memory locations are called
float/real data types. The floating point numbers are defined in C by the keyword float. If the
accuracy provided by float number is not sufficient, double type can be used. It gives double
precision. Following table gives various sizes available in floating data types.
Module
1
Data type Keyword Size in Bytes Size in Bits Maximum Range
of value that can
be stored
Float float 4 32 232
Double double 8 64 264
Long long 10 80 280
double double
float
double
long double
Character type: Data type used to store single character in memory locations is called character
type. The keyword char is used for character type Each of these characters has numerical value
associated with them called ASCII values. (ASCII stands for American Standard Code for
Information Interchange.)
for example: letter ‘a’ has ASCII value 97 (binary equivalent is 0110 0001) and letter ‘b’ has
value 98 (binary equivalent is 0110 0010). In same order ASCII value of ‘x’ is 120 (0111
1000). Here are some of the important ranges within the ASCII character set:
48 – 57: the digits ‘0’ through ‘9’
65 – 90: the capital letters ‘A’ through ‘Z’
97 – 122: the lowercase letters ‘a’ through ‘z’
Void type: It is a special data type that has no value but can be used for only one operation
that is assignment. It can also be used as generic type.
Declaration of variables
There are two methods of declaration of
variables 1 . Primary type declaration
2. User defined type declaration
Module
1
Variables
Variables are named memory locations that have type such as integer or character to store data
values, these data values will change during program execution. Variables are also called
identifier, because it is used to identify value.
Rules for naming variable
1) The first character must be an alphabetic character (lower-case or capital letters) or an
underscore ‘_’.
2) All characters must be alphabetic characters, digits, or underscores.
3) The first 31 characters are significant; however length should not be more than
8 characters.
4) Cannot duplicate a reserved word. A reserved word is one which has special meaning to C.
5) Uppercase and lowercase are significant.
6) White space is not allowed
Primary Variable declaration: All variables must be declared before use, although
certain declarations can be made implicitly by content. A declaration specifies a type, and
contains a list of one or more variables of that type.
Syntax of variable
declaration data-type
v1,v2,---vn ;
Where data-type can be any basic datatype,and v1, v2 .. vn are the names of the variable.
Variables are separated by commas. A declaration ends with semicolon(;).
example
int lower, upper, step;
Variables can be distributed among declarations in any fashion; the lists above could well be
written as
int lower;
int upper;
int step;
The latter form takes more space, but is convenient for adding a comment to each declaration
for subsequent modifications.
Variable Initialization: Once you declared variable, the next step is to assign value to
variable. The process of assigning values to a variable is called initialization of variable. You
can assign values to a variable by using (= ) assignment operator.
Syntax:
Variable _name=value;
Following examples illustrates the same:
int a=25, x=55,c=77;
float p=25.5, q=30.55;
char ch=’A’;
a 25 x 55 p 25.5 ch A
Examples
1. typedef int units;
2. typedef float marks;
units symbolizes int and marks symbolizes float. i.e., units batch1,batch2; and marks n1, n2;
Another user-defined data type is enumerated data type provided by ANSI standard .
It is defined as follows(syntax).
enum identifier {value1, value2,............valuen};
The “identifier” is a user-defined enumerated data type which can be used to declare variables
that can have one of these values enclosed with in braces(known as enumeration constants).
Example
enum day {Monday, Tuesday,........Sunday};
enum day week_st, week_end;
Integer Arithmetic: It is an expression evaluation where all the operands are of integer
data type. Let us take an example:
int a=10,b=5,c;
c=a/b;
printf(“%d”, c);
c will contain quotient value 2
Real Arithmetic: It is an expression evaluation where all the operands are of float data
type. Here is an example:
float x=2.5, y=10.0,z;
z=y/x;
printf(“%f”, z);
z will contain value 4.000000
Mixed Mode Arithmetic: In an expression if some operands are of integer type and others
are of float type it is called mixed mode arithmetic expression. Here the data type of small
size gets automatically converted to data type of bigger size.
Here is an example for such expression:
int a=25;
float x=4,z;
z=a/x;
printf(“%f”,z);
Here ‘a’ is of integer data type and ‘x’ is of float type, therefore ‘a’ automatically
gets converted to float type and output is: 6.25
2. Relational operator: Relational operators are often used to compare two quantities
on their relation, take certain decision. An expression that uses relational operators are
called relational expressions. The value of relational expression is either 1 or 0. 1
means true, 0 means false. C supports 6 relational operators
3. Logical operator: Logical operators are used to test more than one condition mad
make decision. C provides 3 logical operators as shown below
Note: 1. In Logical AND operator output is TRUE only if both inputs are TRUE.
2. In Logical OR operator output is TRUE if any of the inputs are TRUE.
3. In Logical NOT operator output is TRUE if input is FALSE and vice
versa. Here are some examples on logical expressions:
Example1: int A=5, B=10, X=20, Y=5;
What is truth value of expression: ( A ) && ( B )?
(5) && (10) both are non-zero number: 1 && 1 = 1 (True)
(Note: Any non-zero number is treated as 1)
4. Assignment operator (=): Assignment operators are used to assign the result of
an expression to a variable. There are three types of assignment
1. Simple assignment. Ex a=5;
2. Shorthand assignment. Ex a+=5;
Module
1
3. Multiple assignments Ex a=b=c=100;
An expression such as
i = i + 2;
in which the variable on the left side is repeated immediately on the right, can be written in the
compressed form
i += 2;
The operator += is called a shorthand assignment operator.
Note: the left-hand side of the assignment operator should always have variable
A+b=5 is illegal
5. Increment and Decrement operators: C uses two useful operators generally not
found in other languages. These are increment and decrement operator. The operator ++ adds 1
to the operand and - - subtract 1. Both are unary operator and takes the form
++m or m++; equivalent to m=m+1
--m or m--; equivalent to m=m-1
These are extensively used in loops(while, for, do while)
Example-1:
int a=5,b;
b=a++;
Here first the current value of a (i.e. 5) is copied to b then ‘a’ is incremented
b= 5 a= 6
Example-2:
int x=7, y;
y=++x;
x= 8 y= 8
Module
1
Example-3:
int a=6, b;
b= (a++) + (a++);
Steps of evaluation:
First the current values of a is used to calculate the expression that
is 6 +6 is calculated and stored in b.
Then a gets incremented twice that is a=14
b= 12 a= 14
Example-4:
int a=6, b;
b= (++a) + (++a);
Steps of evaluation:
First the values of a is incremented to 7
Next a is again incremented to 8
Final value of expression is 8+8
This value is stored in b (i.e.16)
b= a=
16 16
Example-5:
int a=5,b;
b=a- -;
Here first the current value of a (i.e. 5) is copied to b then ‘a’ is decremented
b= 5 a= 4
Example-6:
int x=7, y;
y= - -x;
Here first the value of x is decremented to 6 and then assigned/copied to y
x= 6 y= 6
syntax Syntax:
Expression 1 ? Expression 2 : Expression 3
Where
Expression1 is Condition
Expression2 is Statement Followed if Condition is True
Expression2 is Statement Followed if Condition is False
Meaning of Syntax:
1. Expression1 is nothing but Boolean Condition i.e it results into either TRUE or FALSE
2. If result of expression1 is TRUE then expression2 is executed
3. Expression1 is said to be TRUE if its result is NON-ZERO
4. If result of expression1 is FALSE then expression3 is executed
5. Expression1 is said to be FALSE if its result is ZERO
2 : Comma as Operator
k = (a , b);
Different Typical Ways of Comma as Operator :
int a=1,b=2,c;
Way 1 :
c = (a , b);
c = Value Stores in b = 2
Way 2 :
c = a , b;
c = Value Stores in a = 1
sizeof( ) operator: It is a compile time operator and when used with an operand it returns
the number of bytes the operand occupies the operand may be variable or constant or data type
qualifier.
Module
1
Example:
int sum;
M=sizeof(sum); //M has
2 N=sizeof(long int); //N has 4
Precedence: The order in which the operators in a complex expression are evaluated is
determined by set of priorities known as precedence. If an expression contains Arithmetic
operators ‘+’ , ‘*’ and ‘/ ‘operators as shown below:
A=B+C*D/F
In this expression RHS of expression contains B+C*D/F, here first preference is given to ‘*’
and ‘/ ‘and then to ‘+’. This is decided by operator precedence given in C Language.
Let us say: B=5, C=7, D=9 and F=3, then value of A is:
A= 5+7*9/3
This expression is evaluated in following steps:
A = 5 + (7*9)/3
A= 5+(63/3)
A=5+21
A=26
Associativity: If two operators with same precedence accur in a complex expression, another
attribute of an operator called associativity takes control. Associativity is the parsing direction
used to evaluate an expression. It can be either left to right or right to left .
For example: X= Y/Z*P%Q
Here ‘/’, ‘*’, and ‘%’ are operators at same level. But we evaluate this expression from LEFT
to RIGHT (i.e. Associativity is from Left to Right).
2
X=(12)%3
X=0 3
Following table provides the Precedence and Associativity of operators discussed in this unit.
Operator Description Associativity Precedence(Rank)
() Function call Left to right 1
[] Array element reference
+ Unary plus Right to left 2
Module
1
- Unary minus
++ Increment
-- Decrement
! Logical negation
~ Ones complement
* Pointer to reference
& Address
Sizeof Size of an object
(type) Type cast (conversion)
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
- Subtraction
<< Left shift Left to right 5
>> Right Shift
< Less than Left to right 6
<= Less than or equal
> to Greater than
>= Greater than or equal to
== Equality Left to right 7
|= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional expression Right to left 13
= Assignment operators Right to left 14
*= /= %=
+= -= &=
^= |=
<<= >>=
, Comma operator Left to right 15
Evaluation of Expressions
Based on the Precedence and Associativity of operators here we discuss evaluating various
types of expressions.
int a=10, b=7, c=8, d=2;
– a+ b / c - d
2 1 3
10 + (7/8) – 2
(10+ 0) - 2
(10 – 2)
Module
1
8
Note: In this example 7/8 gives 0 as answer as it is integer division the decimal portion is
truncated.
Example-2:
int a=10, b=7, c=8, d=2;
– a + b && c - d
1 3 2
Example-3:
int a=10, b=7, c=8, d=2;
(a+b)* (c-d)
1 2
3
(10+7 ) 8-2)
1 2
(17*6)
=102
Example-4:
int a=10, b=7, c=8, d=2;
– ++a * c - d--
2 1
Module
1
(11)*8 – (2) =86
Note: Here d - - is post decrement so its initial value (2) is used in the expression.
Types of Conversions: Whenever mixed data occurs ‘type conversion’ comes into picture.
Two types of data type conversions are:
1. Automatic type conversions (Implicit conversions)
2. Manual type conversions (Explicit conversions)
In automatic conversion the operand/variable of smaller data type is automatically converted to
data type of larger size.
That is: charint long intfloatdouble-long double
Example:
int a=25;
float x=5,z;
z=x/a;
printf(“%f”,z);
In this example ‘x’ is float and ‘a’ is integer, a gets automatically converted to float and answer
is: z= (5.0/25.0) 0.2
Another example
Note: This type ofofexplicit
side effects in typeisconversions
conversion is to
also referred here:
as TYPE CASTING in ‘C’
Example:
float a=25, b=4;
Module
1
int x;
x=a/b;
The problem here is though 25.0/4.0 will result in 6.25, it is stored in an integer
variable ‘x’. As a result 6.25 is truncated to 6! Therefore we have to be careful when mixed
data types are used.
#include<stdio.h>
void main()
{
int a , b, temp;
printf("Enter the values of a and b:\n");
scanf("%d%d", &a,&b);
printf(“ a=%d and b=%d\n” , a ,b);
printf(“Exchanging Using a temporary variable\n”);
temp = a;
a = b;
b = temp;
printf(“a=%d and b=%d\n”,a,b);
printf(“Without using a temporary variable\n”);
a=a+b;
b=a-b;
a=a-b;
printf(“a=%d and b=%d\n”,a,b);
}
Output:
Enter the values of a and b:
5
10
a = 5 and b = 10
Exchanging Using a temporary variable\n”);
a = 10 and b = 5
Without using a temporary variable
a = 5 and b = 10
#include<stdio.h>
void main()
{
float ct,ft;
printf(“Enter the temperature in Fahrenheit\n”);
scanf(“%f”,&ft);
ct=(ft-32.0)/1.8;
printf(“Fahrenheit temperature = 6.2%f\n”, ft);
Module
1
printf(“Celsius temperature = 6.2%f\n”, ct);
}
Output:
Enter the temperature in Fahrenheit
50
Fahrenheit temperature = 50.00
Celsius temperature = 10.00
#include<stdio.h>
void main()
{
float p,t,r,si;
printf(“Enter the values of p,t,r\n”);
scanf(“%f%f%f”,&p,&t,&r);
si=(p*t*r)/100;
printf(“simple interst si=%f”,si);
}
Output:
enter the values of p,t,r
1500
6
10
simple interst si=900
void main( )
{
int i=5, j=-2, k=0, a,b,c,d;
a=i | | j | | k;
b=i && j && k;
c= i | | j && k;
d=i && j && k;
printf(“\n a=%d b=%d c=%d d=%d”, a,b,c,d);
}
Results:
a=5 | | -2 | | 0
(Meaning: True | | True | | False which is True or 1)
c=5 | | -2 && 0
(Meaning: True | | True && False which is False or 0)
d= 5 && -2 && 0
(Meaning: True && True && False which is False or 0)
2. void main( )
{
int a=5, b;
b=(a++);
printf(“b=%d”, b);
}
Results: b=5
3. void main( )
{
int a=5; a=(+
+a)+(a++);
printf(“%d”, a);
}
Results:
Step1: a=(++a) + (5)
Step2: a=(6) +(6)
Step3: a= ((6) +(6)) +1 13
4. void main( )
{
int a=5, b; b=(+
+a)+(a++);
printf(“%d”, b);
}
Results:
Step1: b=(++a) + (5)
Step2: b=(6) +(6) 12
5. void main( )
{
Module
1
int i=5;
printf(“%d”, ++i);
}
Result: 6
6. void main( )
{
int i=5;
printf(“%d”, i++);
}
Results: 5
7. void main( )
{
int i=5;
printf(“%d\t %d ”, i++, i);
}
Results: 5 6
8. void main( )
{
int i=5;
printf(“%d \t%d”, ++i, i);
}
Results: 6 6
9. void main( )
{
int i=5;
printf(“%d \t%d\t %d ”, ++i, i++, i);
}
Results: 7 5 7