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

Module 1

Cc

Uploaded by

bhavanabiradar5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module 1

Cc

Uploaded by

bhavanabiradar5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

C Programming for Problem Solving Notes

MODULE 1
CHAPTER 1: MANAGING INPUT AND OUTPUT OPERATIONS

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

Dept. of CSE 1
C Programming for Problem Solving 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.

 Minicomputers/Midrange computers: It was introduced by DEC (Digital Equipment


Corporation). They can serve hundreds of users and are small enough to partially occupy a
room. They are used in smaller organizations or a department of a large one. They are not
affordable to be used in home.

 Microcomputers: The microcomputer or PC is introduced by Apple and endorsed by


IBM. This is a single-user machine powered by a single-chip microprocessor. They are very
powerful machines having gigabytes of memory. They are both used in standalone mode and in
a network. A microcomputer takes the form of desktop, notebook (laptop) or a netbook (smaller
laptop). PCs today are powered by 3 types of OS – windows (7, 8 or 10), Mac OS X (Apple) and
Linux. They are used for engineering and scientific applications and for software development.

 Smartphones and Embedded Computers: The smartphone is a general purpose


computer i.e., capable of making phone calls. It has a powerful processor, with multiple cores,
supports GBs of memory, and runs developed OS (Android or iOS). It can be operated with
keyboard, touch or stylus.
Embedded Computers or micro-controllers are very small circuits containing a CPU, non-
volatile memory, input and output handling facilities. They are embedded into many machines
that we use – cars, washing machines, cameras etc. The processor here runs a single
unmodifiable program stored in memory.

Dept. of CSE 2
C Programming for Problem Solving Notes

BITS, BYTES AND WORDS


 Computer can understand only two states: 0 and 1.
 A digit can have only two states or values known as a binary digit, abbreviated as bit
(b).
 The name nibble was coined to represent four bits.
 The name byte (B) was coined to represent eight bits.
 The byte is the standard unit of measurement of computer memory, data storage and
transmission speed.
 The CPU handles memory data in larger units, called words and it is usually even
multiple of bytes (two bytes, four bytes etc.).
 When referred to a computer it has 32-bit (4 bytes) machine i.e., size of word is 32 bits.

Unit Equivalent to Remarks


1 kilobyte (KB) 1024 bytes Space used by 10 lines of text
1 megabyte (MB) 1024 kilobytes Memory of the earliest PCs
1 gigabyte (GB) 1024 megabytes Storage capacity of a CD-ROM
1 terabyte (TB) 1024 gigabytes Capacity of today’s hard disks
1 petabyte (PB) 1024 terabytes Space used for rendering of film Avatar

CPU (CENTRAL PROCESSING UNIT)

Figure 1: Functional Components of Computer


The CPU comprises of following components:
 ALU (Arithmetic and Logic Unit)
 CU (Control Unit)

Dept. of CSE 3
C Programming for Problem Solving Notes

 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.

SRAM (Static) DRAM (Dynamic)


Stores information as long as power Loses data in a very short time.
supply is on, reloads every 2ms.
Multiple transistors are used to store 1 bit. One transistor is used to store 1 bit.
It is expensive, faster, bigger. It is inexpensive, slower, smaller.
It requires more power. It requires less power.
It is not required to be refreshed. It requires refresh.

2. ROM (Read Only Memory): It is a permanent memory that can be 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.

Dept. of CSE 4
C Programming for Problem Solving 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.

 EEPROM (Electrically Erasable Programmable Read Only Memory): It can be


erased and rewritten multiple times. The electric voltage is used to erase the data. The
pen drive we use today is of EEPROM.

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-

Dept. of CSE 5
C Programming for Problem Solving 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.

 Difference between Primary memory and Secondary memory

Primary Memory Secondary Memory


The size of the primary memory is small. The size of the secondary memory is
larger.
Stores the programs and data currently It is used to store large amount of data and
needed by the CPU. programs
Expensive. Inexpensive.
Volatile in nature. Non-volatile in nature.

PORTS AND CONNECTORS


Devices like scanners, printers are connected to a computer through docking points called
ports. It is impossible to use wrong connector for a port. At present systems offer only fewer
types compared to old ones.
 USB (Universal Serial Bus): This replaced serial and parallel ports in motherboard.
Most computers offer four USB ports to support scanners, printers and mice. It has four lines,
two each for data and power. The current USB 3.0 can transfer 1 GB file in 20 seconds. The
smaller variant, the micro-USB port is used in smartphones.

Dept. of CSE 6
C Programming for Problem Solving Notes

 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.

 Keyboard: Every computer supports a keyboard – either a physical or touchscreen. The


keyboard has QWERTY layout and contains large number of symbols. Each letter, numeral or
symbol is known as a character, which represents smallest piece of information. Each character
has a unique values called the ASCII (American Standard Code for Information Interchange)
value.

 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

Dept. of CSE 7
C Programming for Problem Solving 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.

Dept. of CSE 8
C Programming for Problem Solving 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.

Figure 2: Network Topologies


1. Bus Topology: It uses a single cable called as bus to which all computers are connected.
The failure of one single node doesn’t disturb other nodes.
2. Star Topology: It uses a central hub to which all nodes are connected. If the hub fails,
entire network fails and the nodes cannot be added easily.
3. Ring Topology: It is connected in the form of closed loop without hub. Data moves from
node to node. For unidirectional rings, if one node fails, the network fails.
4. Mesh Topology: Nodes are connected to one another offering multiple paths. If node
breaks down, then data passing changes its route. It is expensive.

 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.

Dept. of CSE 9
C Programming for Problem Solving 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

Dept. of CSE 10
C Programming for Problem Solving 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.

System Software Application Software


System software is used for operating Application software is used by user to
computer hardware. perform specific task.
System softwares are installed on the Application softwares are installed according
computer when operating system is installed. to user’s requirements.
In general, the user does not interact with In general, the user interacts with application
system software because it works in the softwares.
background.
System software can run independently. It Application software can’t run independently.
provides platform for running application They can’t run without the presence of system
softwares. software.
Some examples of system softwares are Some examples of application softwares are
compiler, assembler, debugger, driver, etc. word processor, web browser, media player,
etc.

Dept. of CSE 11
C Programming for Problem Solving Notes

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:

Pseudocode: To compute addition of two Pseudocode: To compute area of


numbers rectangle

Start Start
Get the values of number1 and number2 Get length and width
Calculate addition=number1+number2 Calculate area=length*breadth
Print addition Print area
Stop End

Dept. of CSE 12
C Programming for Problem Solving Notes

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

Dept. of CSE 13
C Programming for Problem Solving Notes

b) Multi line comment /*Multi line comment*/


 Link Section: It provides instruction to the compiler to link functions from
system library.
 Definition Section:

Documentation section
Link section
Definition section
Global declaration section
main() Function Section
{
Declaration
part
Executable
part

Sub program section

Function 1
Function 2
-
-
Function n

Dept. of CSE 14
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

Pseudo code solution to problem:


Most of the programming problems are too long and complex to be translated directly. As a
problem solving tool, programmers usually introduce at least one intermediate step between
English and C the one we use is called pseudo code.
Pseudo code: Pseudo code is a restatement of the problem as list of steps in an english
like statements that are used to define a solution for a given problem.
Main use of pseudo code is to help us to translate from English to C language. It is also an
outline of the basic structure or logic of the program.
The advantage of pseudo code is that it enables the programmer to focus on algorithms
without concerning about all the syntactic details of specific programming language.
1) Pseudo code to add two numbers
3) Pseudo code to print 1 to 10 and its
1. Begin
square:
2. read a and b values
1. Begin
3. sum=a+b
2. Start with num=1
4. Write sum value in output
5. end 3. Compute square=num*num
4. Display num and square
5. Repeat step 3 and 4 till num<=10
6. end

2) Pseudo code to find biggest of two 4) Pseudo code to find smallest of two nos:
nos: 1. Begin
1. Begin 2. read two nos a,b
2. read two nos a,b 3. compare a and b, a<b?
3. compare a and b, a>b? 4. if result of statement 3 is true
4. if result of statement 3 is true go to step-5 otherwise to step-6
go to step-5 otherwise to step-6 5. display “a is small”
5. display “a is big” 6. display “b is small”
6. display “b is big” 7. end
7. end

Praveen.N , Dept. of CSE, CiTech. Page 1


Module 1

Basic concepts in C program:


This section will introduce a number of features of the C language which must be included in
every program, even though they do not appear in the pseudo code. The basic
Structure of C program is shown below

Documentation section
Link section
Definition section
Global declaration section
main() section
{
Declaration part
Executable part
}

Sub program section


Function 1
Function 2
-
-
Function n
Every c program is made up of one or more preprocessor commands, global declarations, and
one or more functions.
* Documentation section consists of a set of comment line giving the name of the program,
the author, and other details. Compiler ignores these comments when it translates the program
into executable code. C uses 2 different formats
1. Block comments /*this is multi line comments*/
2. Line comments //this is single line comments
* The Link section provides instruction to the compiler to link functions from system library
* The definition section defines all symbolic constants
* Global Declaration section: there are some variables that are used in more than one
function, such a variable are called global variable and are declared in the global declaration
section that is outside of all functions.
* Every C program must have one main ( ) function section. This section contains two parts
declaration part and executable part
* Declaration part declares all the variables used in the executable part
* There is at least one statement in an executable part. These two part must appear at the
beginning of the brace and ends at the closing brace. All statement in the declaration and
executable part ends with semicolon.
* The sub program section contains all the user defined functions that are called in the main
function

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( )

Praveen.N , Dept. of CSE, CiTech. Page 2


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 4th 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:+,-,/

Let us discuss each one of them in detail:


Identifiers: Identifier are name given by programmers to data objects and other objects such as
variables, functions, and arrays in C. These are user defined names and consist of sequence
letters, digits or underscore. To frame identifiers we have to follow certain rules.
Here are the important rules:
1. Identifier should contain only alphabets (A-Z), (a-z), numerals(0-9) and underscore (_)
2. Identifier should start with alphabet or underscore, but not numeric character
3. First 31 characters in an identifier are significant, rest of characters are neglected
4. No reserve words (keywords) of C language can be used as identifiers
5. Identifiers are case sensitive

Examples of valid identifier


food, counter_7, max_1, min_1
Examples of Invalid identifier
$num //$ is special character

Praveen.N , Dept. of CSE, CiTech. Page 3


Module 1

int //keyword
name 1 //space not allowed
Identifiers can be further classified as:
1. Keywords
2. Standard identifiers Ex: printf, scanf
3. programmer defined identifier Ex: sum, avg

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.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
The keywords const, signed, and volatile are new with the ANSI standard; enum and void
are new since the first edition, but in common use.

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:

Example Value Type


+564 564 signed int/ just int
789U 789 unsigned int
037 Octal 37 int

Praveen.N , Dept. of CSE, CiTech. Page 4


Module 1

Real constants A floating constant consists of an integer part, a decimal part, a fraction part,
an e or E, an optionally signed integer exponent and an optional type suffix, one of f, F, l, or
L. The integer and fraction parts both consist of a sequence of digits. Either the integer part, or
the fraction part (not both) may be missing; either the decimal point or the e and the exponent
(not both) may be missing. The type is determined by the suffix; F or f makes it float, L or
l makes it long double. By default all C language real numbers are of double type.
Following table describes various examples of real constants:

Example Value Type


564.35 564.35 double
789.555f 789.555 float
0.65e5 65000 double

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

Example Value Type


‘C’ Character constant with char
ASCII value 67
‘\n’ New line character (control char
skips to next line)
ASCII value=10
‘\t’ Leaves a tab space char
ASCII value=9
“hello” String constant char

Enumeration constant: An enumeration is a list of constant integer values. Example


enum boolean { NO, YES };
The first name in an enum has value 0, the next 1, and so on, unless explicit values are
specified. If not all values are specified, unspecified values continue the progression from the
last specified value. Names in different enumerations must be distinct. Values need not be
distinct in the same enumeration.

Praveen.N , Dept. of CSE, CiTech. Page 5


Module 1

Enumerations provide a convenient way to associate constant values with names, an alternative
to #define with the advantage that the values can be generated for you.

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

Praveen.N , Dept. of CSE, CiTech. Page 6


Module 1

integers.

Data type Keyword Size in Bytes Size in Bits Maximum Range


of value that can
be stored
Short short int 1 8 28 =0-255
integer
integer int 2 16 216= 0-65535

Long long int 4 32 232= 4294967295


integer
Note: All these values are for unsigned category of integers. Sign of
integer is represented by most significant bit.

Sign bit=1 means negative number


Sign bit=0 means positive number

Short Integer

Integer

Long Integer

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.

Praveen.N , Dept. of CSE, CiTech. Page 7


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’

Following table represents the size of character type and its keyword.
Some important range s within ASCII character set
Data type Keyword Size in Bytes Size in Bits Maximum Range
of value that can
be stored
Character char 1 8 28=256

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

Praveen.N , Dept. of CSE, CiTech. Page 8


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

User defined type declaration


C supports a feature known as “type definition” that allows user to define an identifier that

Praveen.N , Dept. of CSE, CiTech. Page 9


Module 1

would represent an existing data type. The user-defined data type identifier can later be used to
declare variables.
Syntax
typedef type identifier;
Where
typedef is a keyword
type refers to an existing data type
identifier refers to new name given to the datatype

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;

Operators and expressions


Expressions: An expression is a sequence of Operands and Operators that reduces to single
value. An expression can be simple or complex.
 An operator is a syntactical token that requires an action to be taken
 An operand is an object on which an operation is performed. It receives an operation
action.
 Simple expression contains only one operator. Ex 1+6
 A complex expression contains more than one operator. Ex 3*5+7
In C language we can formulate different types of expressions based on operators used. Various
important operators available in C language are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment / Decrement operators
6. Bitwise Operators
7. Conditional operator
8. Special operator

1. Arithmetic operator: C provides all basic arithmetic operators. Here is a brief


summary of different operators.

Arithmetic Name Example


Operators

Praveen.N , Dept. of CSE, CiTech. Page 10


Module 1

+ Addition or unary plus C=A+B


- Subtraction or unary minus Z=X-Y
* Multiplication R=P*Q
/ Division (The result given is Quotient) S=P/Q
% Modular division (The result given is remainder) D=A%B
Note: modular operation is possible only on integer Here A and B
data types should be integers

Arithmetic expressions are of three types:


1. Integer Arithmetic
2. Real Arithmetic
3. Mixed mode Arithmetic

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

Relational Name Example


Operators
> Greater Than A >B
< Less Than X<Y
Praveen.N , Dept. of CSE, CiTech. Page 11
Module 1

>= Greater Than or Equal to (A+B) > =(X-Y)


<= Less Than or Equal to (P+Q) < =(R-S)
== Equal to (X+Y) = = Z
!= Not Equal to Z != A

Here are some Examples on Relational operators:


Example-1:
int A=5, B=10, X=20, Y=5;
What is the truth value of expression: (A+B) = = (X-Y)?
(5+10) = = (20-5) answer is TRUE
Example-2:
int A=5, B=10, X=20, Y=10;
What is the truth value of expression: (A+B) >= (X-Y)?
(5+10)> = (20-10) answer is FALSE

3. Logical operator: Logical operators are used to test more than one condition mad make
decision. C provides 3 logical operators as shown below

Logical Operators Name Example


&& Logical AND A && B
|| Logical OR (X +A) | | (Y+B)
! Logical NOT !A

The truth table of Logical operators is as follows:

&&( Logical AND | |( Logical OR operator) !( Logical NOT


operator ) operator)
A B A&&B A B A| |B A B
0 0 0(False) 0 0 0(False) 0(False) 1(True)
0 1 0(False) 0 1 1(True) 1(True) 0(False)
1 0 0(False) 1 0 1(True)
1 1 1(True) 1 1 1(True)

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;

Praveen.N , Dept. of CSE, CiTech. Page 12


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)

Increment/Decrement Names Examples


operators
(++) Increment A++ (Post increment)
meaning A=A+1
(- -) Decrement B - - (Post decrement)
meaning B=B-1
(++) Increment ++A (Pre increment)
(- -) Decrement -- B (Pre decrement)

The following example illustrates the working principle behind post-increment/decrement and
pre-increment/decrement operators:

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;

Here first the value of x is incremented to 8 and then assigned/copied to y

x= 8 y= 8

Praveen.N , Dept. of CSE, CiTech. Page 13


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= 16 a= 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

6. Bitwise operators:C has a distinction of supporting special operator known as bitwise


operators for manipulation of data at bit levels. These operators are used for testing the bits, or
shifting them right or left. Bitwise operators may not be applied to float or double. Table below
shows bitwise operators and their meaning.

Bitwise Operators Meaning Examples


& Bitwise AND A&B
| Bitwise OR X|Y
>> Bitwise Right Shift P>>2

Praveen.N , Dept. of CSE, CiTech. Page 14


Module 1

<< Bitwise Left Shift Q<<2


^ Bitwise Ex-OR X^Y
~ Bitwise ones complement ~5

Examples for bitwise AND, OR and XOR:


A B A&B A|B A^B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Example for Bitwise Left shift:


A 0 1 0 0 0 1 1 0
A<<2 0 0 0 1 1 0 0 0

Note: Meaning is to left shift bits by 2 positions


Example for Bitwise Right shift:
A 0 1 0 0 0 1 1 0
A>>2 0 0 0 1 0 0 0 1

Note: Meaning is to right shift bits by 2 positions

7. Conditional Operators [ ?: ] Or Ternary Operator


1. They are also called as Ternary Operator.
2. It takes 3 Arguments as shown in the 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

Example : Check whether Number is Odd or Even


#include<stdio.h>
void main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);

Praveen.N , Dept. of CSE, CiTech. Page 15


Module 1

flag = ((num%2==0)?1:0);
if(flag==0)
printf("\nEven");
else
printf("\nOdd");
}

8 Special operator: a) Comma Operator b) sizeof operator


Comma operator:
1. Comma operator has lowest precedence. [Priority] i.e., evaluated at last.
2. Comma operator returns the value of the rightmost operand.
3. Comma operator can acts as
- Operator: In the Expression
- Separator: Declaring Variable, In Function Call
Parameter List
#include<stdio.h>
void main()
{
int a=1,b=2;
int k;
k = (a,b);
printf("%d",k);
}
Output: 2

In the Above Example - 1 : Comma as Seperator


It can acts as Separator in -

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.

Praveen.N , Dept. of CSE, CiTech. Page 16


Module 1

Example:
int sum;
M=sizeof(sum); //M has 2
N=sizeof(long int); //N has 4

Operator Precedence and Associativity:


In previous section we came across expressions and various operators used in an expression.
For instance if an expression consists of different category of operators such expression is
evaluated using Precedence (priority) of operators and Associativity of operators.

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).

Let Y=10, Z=5, P=6 and Q=3


X=10/5*6%3
X=((10/5)*6)%3
1
X=(2*6)%3

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
Praveen.N , Dept. of CSE, CiTech. Page 17
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)

Praveen.N , Dept. of CSE, CiTech. Page 18


Module 1

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

3
1 2

(10+7) && 8-2

(17) && (8-2)

(17) && (6)


Answer: TRUE (1)
Note: Any non-zero number is treated as 1 (TRUE) whenever Logical operators are used.

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

3 4
Praveen , Dept. of CSE, Citech Page 19
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: charint long intfloatdouble-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

Side effects of automatic conversion:


int a=7, b;
float x;
b=a%x
In the example given above we are using modulus or remainder (%) operator.
Here ‘a’ is integer type and ‘x’ is float. But the catch is % can be used only with integers. So ‘x’
has to be automatically converted to float. But it is impossible as float is bigger than integer. As
a result Complier gives syntax error.
If we have to convert a variable of bigger size to smaller type we have to use manual
conversion (explicit conversion).
Here is how we can use explicit conversion and overcome the syntax error in previous
example:
Example:
int a=7, b;
float x=4.0;
b=a%(int) x

‘x’ gets converted to


integer type manually
Output is: b=7%4  3

Note: This type of explicit conversion is also referred to as TYPE CASTING in ‘C’
Another example of side effects in type conversions is here:
Example:
float a=25, b=4;

Praveen , Dept. of CSE, Citech, Page 20


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.

Programming Examples and exercise:

Program 1. Write a C program to exchange the values of two variables using


a temporary variable and without using a temporary variable.

#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

Program 2. Write a C program to accept the temperature in Fahrenheit and


convert it into Celsius.

#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);

Praveen , Dept. of CSE, Citech, Page 21


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

Program 3. Write a C program to accept p, t, r and compute simple interest.

#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

Program 4. Write a C program to to find area and perimeter of rectangle


#include<stdio.h>
void main()
{
int length,breadth,area,peri;
printf(“Enter the length and breadth of a rectangle\n”);
scanf(“%d%d”,&length,&breadth);
area=length*breadth;
peri=2*(length+breadth);
printf(“Area=%f\n Perimeter=%f\n”,area,peri);
}
Output:
enter the length and breadth of a rectangle
5
6
Area=30
Perimeter=22

Praveen , Dept. of CSE, Citech, Page 22


Module 1

Simple Programs and their Outputs:


Question: If A =0 and B=1
1. A || B = ?
2. A && B = ?
3. !(A && B) =?
4. !A && B =?
5. X >= Y is a expression
6. Z= X +Y is a expression
Results:
1. 0 || 1  1 (True)
2. 0 && 1  0 (False)
3. !(0 &&1) !(0)  1 (True)
4. !0 && 1 1 && 1 1 (True)

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)

b=5 && -2 && 0


(Meaning: True && True && False which is False or 0)

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)

So the output of printf statement is:


a=1 b=0 c=0 d=0

if x=12, y=7, z=11


Find the values of following expressions:
1. x>10 && y!=3
2. x==5 || y!=3
3. !(x >14)
4. !(x >9 && y!=24)
5. 6 && y !=8 || 0

Praveen , Dept. of CSE, Citech, Page 23


Module 1

Results:
1. 12>10 && 7 != 3  ( meaning True && True = True or 1)
2. 12==5 || 7 !=3 (meaning False | | True = True or 1)
3. !(12 >14) (meaning !(False) = True or 1)
4. !( 12>9 && 7!=24) (meaning !(True && True) !(True) =False or 0)
So final answer is: 1 1 1 and 0

Program examples on increment operators:


1. void main( )
{
int a=5;
a=(a++);
printf(“a=%d”, a);
}
Results: a=6

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( )
{

Praveen , Dept. of CSE, Citech, Page 24


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

Tips for Programming Errors

1. Avoid division by zero errors whenever arithmetic expressions are evaluated


2. Use parentheses whenever complex expressions with operators of various Precedence and
Associativity are used
3. Be careful while using increment decrement operators
4. Never give space between relational operators < = , > = , ! = etc.
5. Increment/ decrement operators do not work with floating point numbers.

Praveen , Dept. of CSE, Citech, Page 25

You might also like