0% found this document useful (0 votes)
16 views69 pages

1st Module

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

1st Module

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

Module1

Computer Fundamentals & C Programming

Module 1

➢ Introduction to computer hardware and software.


o Computer Generations.
o Computer Types.
o Bits, Bytes and Words.
o CPU.
o Primary Memory & Secondary Memory.
o Ports & Connections.
o Input & Output Devices.
o Computers in a Network.
o Network Hardware.
o Software Basics.
o Software Types.
➢ Overview of C.
o Basic Structure of C Program.
o Executing a C Program.
o Constant, Variable & Data Types.
o Operators & Expressions.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1. Introduction to computer hardware and software.


1.1The Computer Boom
➢ Computers are powerful devices capable of computing accurately at lightning speeds.
➢ Programmable
o It can process millions of data records with a single set of instructions.
o If the problem changes, only the instructions need to change and not the computer.
➢ Microprocessor
o Rapid reduction in prices enabled the computer to make inroads into practically every
domain of human and industrial activity.
➢ The personal computer moved to users home.
➢ Computers are interfaced with electronic devices.
➢ Medical science has delegated many of its functions to computers.
➢ Computer programming has moved from direct handling of 0’s and 1’s to the development of
languages.
1.2Computer Basics
➢ Computer is a device that can automatically perform a set of instructions.
➢ The computer takes as input these instructions as a single unit, uses them to manipulate data,
and outputs the results in user specified ways.
➢ The processing is fast, accurate and consistent.
➢ Central Processing Unit (CPU) - Primary task is to process these instructions.
➢ An instruction can do only simple work, like moving a constant to a register or adding one to
it.
➢ A Program containing instructions is held in a file that is stored on the computer’s hard disk.
➢ To execute this program, the contents of its file must be loaded into main memory.
➢ The data get loaded either with the program or when demanded by it.
➢ The CPU executes a single instruction at a time.

Create and edit program

…… ……
int x = 5; 01100100010101000
printf(“x=%d\n”,x); 10010101110001100
return 0; 10000111010110110
…... ………
Compile
Source Code (Written by Executable Code (ready to
programmer run)

Run Program
on CPU 2

Figure 1.1 Program Transformations Before Execution

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ Binary devices understand only meaningful sequences of 0’s and 1’s called machine
language.
➢ The CPU doesn’t understand programming languages, every program translated to its
corresponding machine language code before execution.
➢ A separate program called the compiler, translates or compiles this source code to its
equivalent machine code in binary.
➢ As shown in figure 1.1, eventually executed by the CPU.
➢ The CPU needs adequate memory to run programs.
➢ It fetches program instructions and data from memory and writes temporary and final data to
memory.
➢ Memory can be volatile or non- volatile.
➢ The CPU uses the appropriate type depending on how long the data need to be preserved.
1.3 The Background
➢ The computer made its beginning as a simple calculator.
➢ The device called the abacus comprised a number of rings or beads that could be moved
along rods enclosed by a wooden frame.

1.3.1 Napier, Pascal and Leibniz: The Early Pioneers.


➢ Napier
o Allowed the operator to multiply, divide and calculate square and cube roots by moving
the rods around and placing them in specially constructed boards.
➢ Slide Rule
o It is based on Napier's ideas about logarithms.
o Used primarily for
▪ Multiplication
▪ Division
▪ Roots
▪ Logarithms
▪ Trigonometry
o Not normally used for addition or subtraction.
➢ Pascaline
o It was its limitation to addition and subtraction.
o It is too expensive.
➢ Leibniz
o The machines that can add, subtract, multiply and divide automatically.
o It recommended the use of the binary system.

1.3.2 The Programmable Computer.


➢ The concept of program to control a sequence of operations.
➢ The Jacquard loom is a mechanical loom, invented by Joseph-Marie Jacquard 3
➢ Textile Loom used set of punched cards to weave complex patterns in the cloth.
➢ To weave a different design one simply had to change the card set.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ Charles Babbage who used the concept in his 2 conceptual creations- the Difference engine and
Analytical engine.
➢ The holes in the cards of the Jacquard loom determined whether a thread would pass through it,
Babbage saw an opportunity to use them to encode instructions and data.
➢ The analytical engine was fully automatic and designed to run on steam power.
➢ It had a processing unit and memory – 2 essential components of any programmable device.
➢ Conditional Statement: Loops which allowed a set of statements to be repeated, the analytical
engine feature.
➢ Babbage also utilized the services of Ada Lovelace who designed a few algorithms for the
engine.
➢ Babbage is father of the computer while Lovelace is accepted as the first programmer
.
1.3.3 The Programmable Electronic Computer.
➢ Most computers used electro mechanical relays and switches to perform computation.
➢ The Z3 computer designed by Konard Zuse during the war used over 2000 relays.
➢ It was the first computer based on the binary system and program control was achieved by
punched film.
➢ ENIAC – Electronic Numerical Integrator and Computer
o It was represented by the state of its switches, so representing the machine for a different job
needed manual resetting of these switches.
o The difficulty of programming speed was an issue even with electronic computers.
➢ This problem was addressed by Alan Turing.
➢ Turing reasoned that computer speeds could be improved if both program and data were stored
in the same memory. Later reiterated by John Von Neumann in the concept of stored program
computer.
➢ A program fed through paper tape couldn’t fast enough because the computer could only load
one instruction at a time.
➢ Manchester Mark I became the first computer to implement the stored program concept.
➢ Vacuum Tube for performing computation.
o Generates lot of heat
o Consumed enormous power
o Unreliable.
➢ Transistors
o Smaller
o Generates less heat.
o Reliable.
o Made way for integrated circuits and it leads to microprocessor.
o Microprocessor which incorporated the entire CPU on a single chip.
4

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1.4 Computer Generations

➢ The computer of each generation is faster, smaller and more powerful than its counter part of
the preceding shown below.

Generation Based on Other Features


First Vacuum Tubes Magnetic Drums for memory
Second Transistors Magnetic cores, disks, punched cards and printouts
Third Integrated Circuits Keyboard, Monitor & OS
Fourth Microprocessors Networking
ULSI and nano
Fifth Mainly Unclear
technology

1.4.1 Vacuum Tubes: The First Generation

➢ It used vacuum tubes for circuitry and magnetic drums for memory, and were often enormous,
taking up entire rooms.
➢ These computers were very expensive to operate and in addition to using a great deal of
electricity, the first computers generated a lot of heat, which was often the cause of malfunctions.
➢ First generation computers relied on machine language, the lowest-level programming language
understood by computers, to perform operations, and they could only solve one problem at a
time.
➢ The UNIVAC and ENIAC computers are examples of first-generation computing devices.
➢ The UNIVAC was the first commercial computer delivered to a business client, the U.S. Census
Bureau in 1951.
➢ The ENIAC used 18000 vacuum tubes occupied 1800Sq ft and consumed 180KW of Power.

1.4.2 Transistors: The Second Generation

➢ The transistor was invented at Bell Labs in 1947 but did not see widespread use in computers
until the late 1950s.
➢ The transistor was far superior to the vacuum tube, allowing computers to become smaller, faster,
cheaper, more energy-efficient and more reliable than their first-generation predecessors.
➢ Though the transistor still generated a great deal of heat that subjected the computer to damage, it
was a vast improvement over the vacuum tube.
➢ Second-generation computers still relied on punched cards for input and printouts for output.
➢ Second-generation computers moved from cryptic binary machine language to symbolic, or
assembly, languages, which allowed programmers to specify instructions in words.
➢ High-level programming languages were also being developed at this time, such as early versions
of COBOL and FORTRAN. These were also the first computers that stored their instructions in
their memory, which moved from a magnetic drum to magnetic core technology.
5

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1.4.3 Integrated Circuits: The Third Generation

➢ The development of the integrated circuit was the hallmark of the third generation of computers.
➢ Transistors were miniaturized and placed on silicon chips, called semiconductors, which
drastically increased the speed and efficiency of computers.
➢ Instead of punched cards and printouts, users interacted with third generation computers through
keyboards and monitors and interfaced with an operating system, which allowed the device to
run many different applications at one time with a central program that monitored the memory.
➢ Computers for the first time became accessible to a mass audience because they were smaller and
cheaper than their predecessors.
➢ An integrated circuit (IC) is a small electronic device made out of a semiconductor material.

1.4.4 The Microprocessor: The Fourth Generation

➢ The microprocessor brought the fourth generation of computers, as thousands of integrated


circuits were built onto a single silicon chip.
➢ What in the first generation filled an entire room could now fit in the palm of the hand.
➢ The Intel 4004 chip, developed in 1971, located all the components of the computer—from the
central processing unit and memory to input/output controls—on a single chip.
➢ In 1981 IBM introduced its first computer for the home user, and in 1984 Apple introduced the
Macintosh.
➢ Microprocessors also moved out of the realm of desktop computers and into many areas of life as
more and more everyday products began to use microprocessors.
➢ As these small computers became more powerful, they could be linked together to form
networks, which eventually led to the development of the Internet.
➢ Fourth generation computers also saw the development of GUIs, the mouse and handheld
devices.
➢ Sharing of information became possible by connecting computers in a network.

1.4.5 Fifth Generation: Artificial Intelligence

➢ Fifth generation computing devices, based on artificial intelligence, are still in development,
though there are some applications, such as voice recognition, that are being used today.
➢ The use of parallel processing and superconductors is helping to make artificial intelligence a
reality.
➢ The goal of fifth-generation computing is to develop devices that respond to natural language
input and are capable of learning and self-organization.
➢ As complexity increases manifold the following things need to happen.
➢ Computer speed need to make an exponential jump, a feat that would be possible using
quantum computers. Quantum computation and molecular and nano technology will radically
change the face of computers in years to come. Example: Google’s D-Wave 2X
o Computers must be able to perform parallel processing so that multiple processors can
concurrently handle different aspects of a problem.
o Neural networks and expert systems have to be developed. These applications would be
able to make decisions and humans by analyzing data. 6
➢ Molecular Computing - Miniaturization to molecular levels.

1.5 Computer Types

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ Computers categorized by their size


➢ The size of a computer is often an indirect indicator of its capabilities and the application
domain

1.5.1 Supercomputers

➢ The most powerful computers in terms of performance and data processing are the
Supercomputers.
➢ These are specialized and task specific computers used by large organizations.
➢ These computers are used for research and exploration purposes, like NASA uses
supercomputers for launching space shuttles, controlling them and for space exploration
purpose.
➢ Having most powerful and fastest processors.
➢ Super Computer use multiple CPU’s for parallel data processing.
➢ The fastest supercomputer operates at a speed of 34 petaflops (1 peta = 1000 tera = 1000000
giga).
➢ It is used for transaction processing.
➢ The supercomputers are very expensive and very large in size.
➢ It can be accommodated in large air-conditioned rooms; some super computers can span an
entire building.
➢ Example:

o Space Exploration
Supercomputers are used to study the origin of the universe, the dark-matters.
o Earthquake studies
Supercomputers are used to study the Earthquakes phenomenon. Besides that
supercomputers are used for natural resources exploration, like natural gas, petroleum,
coal, etc.
o Weather Forecasting
Supercomputers are used for weather forecasting, and to study the nature and extent
of Hurricanes, Rainfalls, windstorms, etc.
o Nuclear weapons testing
Supercomputers are used to run weapon simulation that can test the Range, accuracy
& impact of Nuclear weapons.

1.5.2 Mainframes
➢ Although Mainframes are not as powerful as supercomputers, but certainly they are quite
expensive.
➢ Many large firms & government organizations uses Mainframes to run their business
operations.
➢ Multi user machines that can support hundreds of users using the feature of time sharing
supported by Linux.
➢ The Mainframe computers can be accommodated in large air-conditioned rooms because
of its size.
7
➢ Super-computers are the fastest computers with large data storage capacity, Mainframes
can also process & store large amount of data.
➢ Example: Banks educational institutions & insurance companies use mainframe
computers to store data about their customers, students & insurance policy holders.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1.5.3 Minicomputers
➢ Minicomputers are used by small businesses & firms.
➢ Minicomputers are also called as “Midrange Computers”.
➢ These are small machines and can be accommodated on a disk with not as processing and
data storage capabilities as super-computers & Mainframes.
➢ The minicomputer which Digital Equipment Corporation(DEC) introduced in the 1970’s.
➢ These computers are not designed for a single user.
➢ Individual departments of a large company or organizations use Mini-computers for
specific purposes.
➢ Example: a production department can use Mini-computers for monitoring certain
production process.

1.5.4 Microcomputers

➢ Desktop computers, laptops, personal digital assistant (PDA), tablets & Smartphone’s are
all types of microcomputers.
➢ The micro-computers are widely used & the fastest growing computers.
➢ These computers are the cheapest among the other three types of computers.
➢ The Micro-computers are specially designed for general usage like entertainment,
education and work purposes.
➢ Well known manufacturers of Micro-computer are Dell, Apple, Samsung, and Sony &
Toshiba.
➢ Desktop computers, Gaming consoles, Sound & Navigation system of a car, Netbooks,
Notebooks, PDA’s, Tablet PC’s, Smartphone’s, Calculators are all type of
Microcomputers.

1.5.5 Smartphone’s and Embedded Computers

➢ Emergence of two types of devices called Smartphone’s and embedded computers.


➢ The Smartphone’s is a general purpose computer that is capable of making phone calls.
➢ The embedded computer is a small computer like system that is part of a larger system.
➢ The Smartphone has a powerful processor with multiple cores. It supports gigabytes of
main memory but doesn’t have hard disk for secondary storage. This requirement is met
by flash memory.
➢ Smartphone has a keyboard and a high resolution display both operated by touch or a
stylus.
➢ Applications are written in a high level language- c for the iPhone and java for android
phones.
➢ Embedded computers arrived before smart phones.
➢ Embedded are very small circuits containing a CPU, non-volatile memory and input and
output handling facilities?
➢ Embedded into many of the machines – Cars, washing machines, MP3 player and
cameras.
➢ Embedded processor runs a single unmodifiable program stored in a memory. 8
➢ Embedded processor is dedicated to a specific task.

1.6 BITS, BYTES AND WORDS

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ Computer understands only two states: 0 or 1.


➢ A digit can have only 2 states or values are known as binary digit-bit.
➢ All binary numbers are represented by combining these 0’s and 1’s.
➢ Example- 13 in decimal represented as 1101 in binary form.
➢ The name byte was coined to represent eight bits.
➢ The byte is the standard unit of measurement of computer memory data storage and
transmission speed.
➢ A DVD ROM has a capacity of 4.7 gigabytes (4 X 109 bytes)
➢ The relationships between these units are expressed in the following manner.

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 PC’s.
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

➢ The speed of network expressed as 1 Mbps is the same as 1000 Kbps.


➢ The CPU handles memory data in larger units called words.
➢ Word is an even multiple of bytes.
➢ Machine instructions are one word in size because a CPU register must be able to hold an
instruction.

1.7 Inside the Computer

➢ The brain of the computer is the central Processing unit (CPU) represented by a single
chip on a PC.
➢ The CPU carries out every instruction stored in a program while interacting with other
agencies as and when necessary.
➢ Arithmetic & Logic Unit is a integral part of the CPU.
➢ RAM - Fast Memory.
➢ RAM is divided into a numbered of contiguously numbered cells.
➢ The number represents the addresses of the cells.
➢ The CPU access a memory location by sending its address to the memory unit.
➢ Primary memory is used for storing instructions and data of the currently in execution
(online storage).
➢ Secondary memory is used for storing data not required concurrently.
➢ A program is executed by loading instructions and data from secondary memory to
primary memory.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1.8 Central Processing Unit (CPU)


➢ The below figure shows the architecture of a computer with single user.
➢ The CPUs evolved from bulky vacuum tubes based units in 1940 to modern 5 Cm Sq. Chip
that is commonly called as microprocessor.
➢ It comprises it comprises the following components.
1) Arithmetic and Logic Unit (ALU)
2) Control Unit (CU)
3) Special purpose register.
4) A clock
.
Arithmetic & Logic Unit

➢ It is a “super calculator” apart from carrying out all arithmetic operations it also performs
Boolean operations (like AND OR NOT) on the numbers.

10
Control Unit
➢ Control unit does not perform any computational task. But they control the way the data
gets transferred with different part in the computer using signals.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

Special Purpose registers

➢ The CPU uses high speed registers to store the current instruction and its data.
➢ One of the register called program counter maintains the address of the next instruction to
execute in the primary memory.

CPU Clock

➢ Both ALU and CU uses the services of clock use the services of the clock for sequencing
and synchronizing their operations.
➢ All the instructions are executed based on the principle of fetch-decode-execute.
➢ An instruction is fetched from the primary memory using the address stored in the program
counter.
➢ The program counters incremented to point to the next instruction.
➢ The fetched instruction is decoded to generate the signals required for operations.
➢ The converted instruction is executed by the CPU and the result is written back to register
and then to the main memory.
➢ The next cycle of fetch-decode-execute would now begin.
➢ All these activities requires clock which generate pulses at regular intervals of time.
➢ The CPU can execute only one instruction in one cycle.
➢ The instruction may take several cycles to get executed.
➢ The faster the clock, faster the CPU.

1.9 Primary Memory.


➢ Memory is the essential resource of computer and its users.
➢ The computer’s memory is divided in to two types. Primary and secondary.
➢ The primary memory of a computer includes,
1. Random Access Memory (RAM, SRAM and DRAM)
2. Read Only Memory(ROM, EROM, PROM, EEPROM)
3. Cache memory (L1, L2 and L3)
4. CPU registers

1.9.1 Random Access Memory (RAM)


➢ RAM stores the data and the code of the currently running program.
➢ On multi-user system RAM contains several programs that run in time sharing mode.
➢ RAM is densely packed transistors, fabricated on the integrated circuit (IC).
➢ The motherboard has slots where these ICs can be inserted.
➢ RAM is fast, volatile and expensive than secondary memory.
➢ When the program starts to execute, the CPU picks up the program instructions from
the RAM. And it also writes back the temporary data and results back to RAM.
➢ Each cell of the RAM has an address. When CPU wants to fetch a data from RAM it
11
sends the address of the location via address bus and retrieves the data on the data bus.
➢ Unlike ROM, RAM is both read and written.
➢ RAM can be further divided in to two types.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1) Static
2) Dynamic
➢ A Static RAM (SRAM) uses multiple transistors in each cell to store one bit of data.
Hence it takes more space.
➢ A Dynamic RAM (DRAM) uses one transistor and a leaky capacitor for each cell.
Capacitors hold the charge but due to inherent leakage, they have to get refreshed often.
➢ SRAM is faster, bigger and expensive than DRAM.
➢ RAM is slowest all primary memory types.

1.9.2 Read only memory

➢ Read only memory is a permanent memory that can be read but cannot be written.
➢ The contents of ROM are written during its manufacturing.
➢ Memory access is faster in ROM compared to RAM.
➢ ROM’s are non-volatile that is their contents are retained after the loss of power.
➢ ROM’s store special programs called BIOS (Basic Input Output Systems) this is a small
program who take care of the computer before control is handed over to OS.
o Programmable Read Only Memory (PROM)
• Left blank at the time of manufacturing.
• The device called the PROM programmer burns customer data in to the PROM.
But once written the contents of the ROM cannot be changed.
o Erasable Programmable Read only memory (EPROM)
• Can be rewritten even though it was previously burned. It can be erased by
exposing it to ultra-violet radiations.
o Electrically Erasable Programmable Read only memory (EPROM)
• Erased and rewritten multiple times.
• Flash drive and Pen drive are type of EEPROM.

1.9.3 Cache Memory

➢ Cache memory stores those parts of the program that are frequently used by CPUs
➢ This is a small but a fast memory used as a buffer between RAM and CPU.
➢ CPU itself contains a Level 1 (L1) cache which is very fast.
➢ L2 cache is located out of CPU but close to it slower than L1 cache.
➢ L3 cache is smaller than the L2 and L1 cache.
➢ Cache memories are limited in size, expensive.

1.9.4 Registers

➢ Registers are the fastest form of memory in the computers.


➢ CPU uses registers for its entire task.
➢ The computer loads the instructions and its data from main memory to register before
processing them.
12
1.10 Secondary memory
➢ Secondary memory is also called as auxiliary memory.
➢ These memories can exist in both in and out of the machine.
Prof Kavya M S & Prof Shridevi Desai
Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ The following are the forms of secondary memories and their sizes.
1. Hard disk including the portable disk (500 GB to 4 TB)
2. Magnetic tape(20 TB)
3. CD-ROM (700 MB-less than 1 GB)
4. DVD-ROM(4.7 GB and 8.5 GB)
5. Blu-ray disk(27 GB and 50GB)
6. Flash memory based on the EEPROM(1 GB to 128 GB)
7. The obsoleted floppy disk(1.2 MB and 1.44MB)

1.10.1 Hard disk

➢ Every disk contains spindle that holds one or more platters made of nonmagnetic materials
like glass or aluminium as shown in the below figure.
➢ Information is written on to or read from the platters using the read-write heads.
➢ Eight surfaces require eight heads and are mounted on a single arm & cannot be controlled
individually.
➢ Each surface has concentric or serially numbered tracks.
➢ Each track is further broken in to sectors or blocks.
➢ The disk spins constantly at speed of 5400 to 7200 rpm (rotation per minutes) the disk head
moves radially from track to track and when the head is positioned above a particular track,
all of its block passes through the head in a very short time.
➢ Access time is larger than RAM.
➢ The heads are not meant to touch the plotter surface, and if that happens, then the disk crash
results and data become unrecoverable.

1.10.2 Magnetic Tapes 13


➢ A tape is made of plastic film with one side coated with magnetic material.
➢ The mechanism consisted of 2 spools and a tape encapsulated in the cassette or cartridge.
➢ Data access is sequential and not random.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1.10.3 Optical Disks – CD-ROM, DVD-ROM, and BLU RAY disk

➢ Non-volatile ROMs can also be available in optical storage disks.


➢ The CD and DVD ROMs can hold the data up to 700 MB to 8.5GB.
➢ BLU RAY disk has the capacity of 50GB in which the laser beam controls the read and
writes operations.
➢ Optical disks are made carbonate material with thin reflective film.
➢ The pits and lands are used to read and write the data land signifies bit 1 and pit signifies
bit 0.
➢ The pits and lands are constructed using laser beam.
➢ CD-R DVD-R- Data can be recorded only once.
➢ CD-RW DVD-RW-Data can be recorded multiple times.

1.10.4 Flash Memory

➢ These devices have no moving parts and are based on EEPROM.


➢ Examples, Pen drives (memory stick), Solid state disk (SSD) and magnetic card (SD
card).
➢ They are portable, reliable and need less power.
➢ Even though pen drive is a read-write device, the number of whites is limited to 10,000.
➢ The SSD is a larger device meant to replace the traditional magnetic hard disk.
➢ Magnetic cards are used in cameras but by using adopters they can be connected to USB
port as well

1.10.5 Floppy diskette


➢ Represented by a small rectangular plastic case containing a thin magnetic disk.
➢ They offer the capacity of 1.2 MB to 1.44MB.
➢ They were soon replaced by the CDs and DVDs.

1.11 Ports and Connectors


➢ Devices like scanners and printers are connected through the points called as ports.
➢ All ports are connected to the mother board of the computer but are visible from outside.
➢ The following are the ports that are commonly used.

Universal Serial Bus (USB)


o They have replaced serial and parallel ports in the motherboard. Computers are
provided with at least 4.
o USB ports to support scanner, printer and mouse. Current USB ports are capable of
transferring 1 GB file in 20 Seconds
Serial Port
o A serial port is an interface through which peripherals can be connected using a serial
protocol which involves the transmission of data one bit at a time over a single 14
communication line.
o Serial ports are offered in 9 and 25 pin configuration.
Parallel Port

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

o A parallel port, on the other hand, is an interface through which the communication
between a computer and its peripheral device is in a parallel manner i.e. data is
transferred in or out in parallel using more than one communication line or wire.
o Printer port is an example of parallel port.

Video Graphics Array


o VGA port is found in many computers, projectors, video cards and High Definition
TVs.
o It is a D-sub connector consisting of 15 pins in 3 rows. The connector is called as DE-
15.
o VGA port is the main interface between computers and older CRT monitors.
o Even the modern LCD and LED monitors support VGA ports but the picture quality is
reduced.
o VGA carries analogue video signals up to a resolution of 648X480.

RJ-45

o Ethernet is a networking technology that is used to connect your computer to Internet and
communicate with other computers or networking devices.
o The interface that is used for computer networking and telecommunications is known as
Registered Jack (RJ) and RJ – 45 ports in particular is used for Ethernet over cable.
o RJ-45 connector is an 8 pin – 8 contact (8P – 8C) type modular connector.
o The latest Ethernet technology is called Gigabit Ethernet and supports a data transfer rate of
over 10Gigabits per second.
PS/2
o PS/2 connector is developed by IBM for connecting mouse and keyboard.
o It was introduced with IBM’s Personal Systems/2 series of computers and hence the
name PS/2 connector.
o PS/2 connectors are color coded as purple for keyboard and green for mouse.

HDMI

o HDMI is an abbreviation of High Definition Media Interface.


o HDMI is a digital interface to connect High Definition and Ultra High Definition devices
like Computer monitors, HDTVs, Blu-Ray players, gaming consoles, High Definition
Cameras etc.

15

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1.12 Input Devices


Input devices are peripherals used to provide data and control signals to a computer.
Input devices allow us to enter raw data for processing.

1.12.1The Keyboard

➢ Keyboard is the most common and very popular input device which helps to input data to the
computer.
➢ The layout of the keyboard is like that of traditional typewriter, although there are some
additional keys provided for performing additional functions.
➢ Keyboards are of two sizes 84 keys or 101/102 keys, but now keyboards with 104 keys or
108 keys are also available for Windows and Internet.

SL.No Keys & Description

Typing Keys

1 These keys include the letter keys (A-Z) and digit keys (09) which generally give the same
layout as that of typewriters.

Numeric Keypad
It is used to enter the numeric data or cursor movement. Generally, it consists of a set of
2
17 keys that are laid out in the same configuration used by most adding machines and
calculators.

Function Keys
The twelve function keys are present on the keyboard which is arranged in a row at the top
3
of the keyboard. Each function key has a unique meaning and is used for some specific
16
purpose.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

Control keys
These keys provide cursor and screen control. It includes four directional arrow keys.
4
Control keys also include Home, End, Insert, Delete, Page Up, Page Down, Control(Ctrl),
Alternate(Alt), Escape(Esc).

Special Purpose Keys


5 Keyboard also contains some special purpose keys such as Enter, Shift, Caps Lock, Num
Lock, Space bar, Tab, and Print Screen.

1.12.2 Scanner

➢ Scanner is an input device, which works more like a photocopy machine.


➢ It is used when some information is available on paper and it is to be transferred to the
hard disk of the computer for further manipulation.
➢ Scanner captures images from the source which are then converted into a digital form that
can be stored on the disk.
➢ These images can be edited before they are printed.
➢ The document to be scanned is placed on a glass plate that is covered by a lid before
scanning.
➢ A shining light is beamed at the document and reflected light is captured by a
photosensitive array of charged coupled (CCD).
➢ The differing levels of brightness are converted into electronic signals.

1.12.3 Pointing Device

➢ Graphical user interfaces (GUI) like windows need a pointing device to control the
movement of the cursor on the screen.
➢ Mouse in the desktop.
➢ Touchpad in the laptop.
➢ The earliest form of the mouse that is connected to a computer port has a rotating ball at
the bottom and 2 buttons at the top.
➢ The buttons are generally used in the following ways:
o Double clicking of the same button activates a program. A text section can be
selected by dragging the mouse with left button pressed (no clicking here). Left
click on a text segment is also required to commence text entry.
17
o Right Clicking button activates a context sensitive menu used to change the
attributes of the selected object. Supports options for copying and pasting text and
change the properties of the selected object.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ Optical mouse use an infrared laser or LED to track movement.


➢ Wireless mouse uses radio frequency technology to communicate with the computer.

1.13 Output Devices


1.13.1 Monitors.

➢ Visual Display Unit (VDU), are the main output device of a computer.
➢ It forms images from tiny dots, called pixels that are arranged in a rectangular form. The
sharpness of the image depends upon the number of pixels.
➢ There are two kinds of viewing screen used for monitors.
• Cathode-Ray Tube (CRT)
• LCD Monitors.
➢ Cathode-Ray Tube (CRT) Monitor
• The CRT display is made up of small picture elements called pixels. The smaller the
pixels, the better the image clarity or resolution.
• It takes more than one illuminated pixel to form a whole character, such as the letter
‘e’ in the word help.
➢ LCD Monitors
• LCD screen comprises thousands of liquid crystals, don’t generate light but generate
light allow or block the passage of light through them.
• An image is formed by selectively applying a voltage to these crystals and using a
separate light source for light to pass through them.
1.13.2 Impact Printer
➢ Impact printers print the characters by striking them on the ribbon, which is then pressed
on the paper.
➢ Characteristics of Impact Printers are the following

• Very low consumable costs


• Very noisy
• Useful for bulk printing due to low cost
• There is physical contact with the paper to produce an image.
➢ Dot Matrix Printer
18
• In the market, one of the most popular printers is Dot Matrix Printer.
• These printers are popular because of their ease of printing and economical price.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

• Each character printed is in the form of pattern of dots and head consists of a
Matrix of Pins of size (5*7, 7*9, 9*7 or 9*9) which comes out to form a character
which is why it is called Dot Matrix Printer.
• Advantages
▪ Inexpensive
▪ Widely Used
▪ Other language characters can be printed
• Disadvantages
▪ Slow Speed.
▪ Poor Quality.
➢ Daisy Wheel
• Head is lying on a wheel and pins corresponding to characters are like petals of
Daisy (flower) which is why it is called Daisy Wheel Printer.
• These printers are generally used for word-processing in offices that require a few
letters to be sent here and there with very nice quality.
• Advantages

▪ More reliable than DMP


▪ Better quality
▪ Fonts of character can be easily changed
• Disadvantages

▪ Slower than DMP.


▪ Noisy
▪ More expensive than DMP
➢ Line printers
• The printers which print one line at a time.
• This printer is like a drum in shape hence it is called drum printer. The surface of
the drum is divided into a number of tracks.
• Total tracks are equal to the size of the paper, i.e. for a paper width of 132
characters, drum will have 132 tracks.
• A character set is embossed on the track. Different character sets available in the
market are 48 character set, 64 and 96 characters set. 19

• One rotation of drum prints one line.


• Drum printers are fast in speed and can print 300 to 2000 lines per minute.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

• Advantages

▪ Very high speed

• Disadvantages
▪ Very expensive.
▪ Characters fonts cannot be changed.

1.13.3 Non-Impact Printers


➢ Non-impact printers print the characters without using the ribbon. These printers print a
complete page at a time, thus they are also called as Page Printers.
➢ These printers are of two types −

o Laser Printers
o Inkjet Printers
➢ Characteristics of Non-impact Printers
o Faster than impact printers
o They are not noisy
o High quality
o Supports many fonts and different character size
➢ Laser Printers
o They use laser lights to produce the dots needed to form the characters to be printed
on a page.
o It works like a photocopier.
o A laser beam creates an image of the page to be printed on a light sensitive drum.
o The Charged area attracts black magnetic powder, called the toner.
o The image is created in the form of dots then transferred from the drum to the paper
by actual contact.
o A separate roller heats up the paper to melt the toner which then gets fused on to the
paper.
o Laser printers have built in RAM for storing documents.
o The RAM acts as a buffer which can free up the computer after a job has been
submitting for printing.
o The resolution varies from 300dpi to 1200dpi (dots per inch).
o Speeds of 20ppm while fastest printers operate at 200ppm (pages per minute). 20
o Advantages

▪ Very high speed

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

▪ Very high quality output


▪ Good graphics quality
▪ Supports many fonts and different character size
o Disadvantages

▪ Expensive
▪ Cannot be used to produce multiple copies of a document in a single printing.

➢ Ink -jet Printer

o They print characters by spraying small drops of ink onto paper.


o Inkjet printers produce high quality output with presentable features.
o They make less noise because no hammering is done and these have many styles of
printing modes available.
o Color printing is also possible. Some models of Inkjet printers can produce multiple
copies of printing also.
o Resolution of 300dpi.
o Prints 1 to 6 pages per minute.
o Advantages

▪ High quality printing.


▪ More reliable.

o Disadvantages
▪ Expensive as the cost per page is high.
▪ Slow as compared to laser printer.

1.13.4 Plotters

➢ A plotter is a printer that interprets commands from a computer to make line drawings on
paper with one or more automated pens.
➢ The plotter can draw continuous point-to-point lines directly from vector graphics files or
commands.
➢ There are a number of different types of plotters: a drum plotter draws on paper wrapped
around a drum which turns to produce one direction of the plot, while the pens move to
provide the other direction; a flatbed plotter draws on paper placed on a flat surface; and 21
an electrostatic plotter draws on negatively charged paper with positively charged toner.
➢ They are also slow and expensive.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ Plotters can handle large paper sizes, and thus suitable for creating drawings of buildings
and machines.

1.14 Computers in a Network.

➢ A computer network is a system in which multiple computers are connected to each other
to share information and resources.
➢ Share resources from one computer to another.

➢ Create files and store them in one computer, access those files from the other computer(s)
connected over the network.

➢ Connect a printer, scanner, or a fax machine to one computer within the network and let
other computers of the network use the machines available over the network.

➢ All networked nodes need a common addressing scheme that would ensure delivery of
data to the right node.

➢ Ethernet- a hardware standard that defines the addressing, cabling and signaling
requirements of the network.

➢ Ethernet having replaced the token ring and FDDI technologies.

1.14.1 Network Topology

➢ A network topology is the arrangement of a network, including its nodes and connecting
lines.
➢ There are a number of ways or topologies of connecting computers, each having its own
merits and demerits.
➢ Bus Topology
o Every workstation is connected to a main cable called the bus. Therefore, in
effect, each workstation is directly connected to every other workstation in the
network.
o The failure of a single node doesn’t disrupt the communication between the
remaining nodes.
➢ Star Topology
o There is a central computer or server to which all the workstations are directly
connected.
o Every workstation is indirectly connected to every other through the central 22
computer.
o If hub fails entire network fails.
o New node can be added without disrupting the service.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ Ring Topology
o The workstations are connected in a closed loop configuration.
o Adjacent pairs of workstations are directly connected.
o Other pairs of workstations are indirectly connected, the data passing through one
or more intermediate nodes.
o In Uni-directional rings, failure of on node causes the network to shut down.
➢ Mesh Topology
o Employs either of two schemes, called full mesh and partial mesh.
o In the full mesh topology, each workstation is connected directly to each of the
others.
o In the partial mesh topology, some workstations are connected to all the others,
and some are connected only to those other nodes with which they exchange the
most data.
o When a node breaks down the packet simply changes its route.
o Expensive of all the topologies.

1.14.2 Network Types

➢ Networks are also classified based on their size.


➢ The Network allows computers to connect and communicate with different computers via
any medium. LAN, MAN and WAN are the three major types of the network designed to
operate over the area they cover.
➢ LAN covers the smallest area;
➢ MAN covers an area larger than LAN and
➢ WAN comprises the largest of all.
➢ Metropolitan Area Network(MAN)
o Sandwiched between a LAN and WAN.
o A MAN is employed for interconnecting computers in the same city.
➢ Campus Area Network (CAN)
o Smaller than MAN and it is used to connect an entire university campus.
➢ Personal Area Network (PAN)
o Smallest network of all and has only recently come of age.
o It operates within a range of a few meters.
o It connects small devices like cell phones and laptops with infrared or Bluetooth
technology. 23

1.14.3 The Internet and internet

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ Largest wide area network on the planet.


➢ It is collection of over 50000 networks that run a special set of network protocols called
TCP/IP.
➢ The internet is different from other network; it grows continuously without the existing
structure.
➢ Network that runs the same set of network protocols is called an internet.

1.15 Network Hardware

➢ Connecting computer in a network require additional devices.


➢ The essential devices and components of a network.
o Network Interface Card.
o Hub and Switch
o Bridge & Router

1.15.1 Network Interface Card.

➢ Network transmission begins from Network Interface Card that is housed inside the
computer.
➢ It is referred as Ethernet Card.
➢ The Functionality is implemented in the following ways:
1. Built into the motherboard of laptops and current desktops.
2. As a separate card inserted into a slot on the motherboard.
3. As a wireless card inserted needs no cable to connect to the network.
4. As a USB adapter that runs on the USB port.
➢ Ethernet card has an address hard- coded into the board by the card manufacturer
➢ This address known as MAC (Machine Access Control) address unique to the card.
➢ Ethernet cards can have the same MAC address. The card is connected to a hub or switch
via a cable

1.15.2 Hub and Switch

➢ Single network and using star topology need a central device to connect to a and this
device is either a hub or a switch.
➢ A hub accepts network data from a computer and simply broadcasts the data to all nodes.
➢ Since the data contain the MAC address of the destination, only the node having that 24
address will accept the data.
➢ The technology is wasteful because data have to travel to all nodes even though only one
among them will accept it.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ A Switch is intelligent because it has a table of all MAC addresses of the connected
devices.
➢ The switch extracts the MAC address from the data and then looks up the table to
determine the node the packet is meant for.
➢ The packet is then sent only to that node.
➢ A switch is efficient and is able to maintain the speed of a network.

1.15.3 Bridge and Router

➢ Bridge- As electrical signals travel along a cable, they weaken, so Ethernet sets a limit on
the maximum size of the cable (100 meters).
➢ Generally only one device is able to transmit at a time, too many nodes can lead to
network congestion.
➢ A network supporting many nodes spilt into a number of segments with a bridge
connecting them.
➢ A bridge maintains a table of all MAC addresses machines in the segments connected to
it.
➢ It connects 2 networks using the same protocol (Ethernet).
➢ Functionality has been over by the switch.
➢ Router- It connects 2 similar or dissimilar networks which may be separated by long
distance.
➢ Routing looks up its routing table to determine the path a packet has to travel to reach its
destination.
➢ If the destination node is on the same network then the router sends the packet directly to
the node otherwise it sends it to another router that takes it closer to its destination.
➢ A router is smarter than a bridge because it can choose the best route for guiding the
packet.

2.1 Software Basics

➢ Software is a collection of code that drives a computer to perform a related group of


tasks.
➢ It comprises one or more programs supported by libraries and configuration files that
programs need to access.
➢ Software may need in a ROM, RAM, and secondary storage or may be loaded from a
25
network.
➢ Software’s are modifiable or removable, but software embedded in a ROM or PROM is
usually permanent.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

2.2 Software Types


➢ There are two types of software’s.
1. System soft ware – Software run by the computer to manage the hardware
connect to it.
2. Application software – Relates to specific application.
➢ System software’s are the set of codes that sits between the application and the hardware.
➢ Some of the examples of system software’s are,
1. Basic Input Output Systems (BIOS): this program checks the hardware device
and the peripherals at the boot time and then loads the OS.
2. Operating Systems (OS): manages the hardware programs running on the
computer.
3. Device driver: these are the software’s which helps the external devices to get
connected to the system.
4. Compilers and associated programs: user uses this software’s to convert the
high level languages to machine level languages.
➢ Application software’s are the software’s that are not directly connected with
hardware but related to a specific real-life situation is known as application
software’s.
➢ The following are the examples of application software’s.
1. Office software’s – Comprises 3 separate application, word processing,
spreadsheet and presentation.
2. Data base software’s – Database management systems allows data having a
uniform structure to be stored in a database
3. Communication software’s –Allow users to communicate with one another.
Examples are Email, Skype and Whatsapp.
4. Entertainment software’s – Related to gaming and multimedia. Examples are
VideoLAN.
5. Anti-virus software’s – A virus can cause your program to misbehave or not
work at all.
6. Special purpose software’s like CAD/CAM – Available for desktop publishing,
computer aided design and manufacturing (CAD/CAM).

BASIC STRUCTURE OF C PROGRAMS:


➢ A C program may contain one or more sections as shown in the below figure.
➢ The documentation section consists of set of comment lines giving the name of the
program, author and other details.
➢ The comments can be single line comment or multi line comment. The single line
comment can be started with //. The multi-line comment can start with /* and end with */. 26
➢ The link section provides instructions to link function from system library.
➢ The definition section defines the symbolic constants.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

➢ The variables that are used in more than one function are called global variables and are
declared in global declaration section.
➢ The global declaration section is out of all user defined functions.
➢ The global declaration section also declares the user defined functions.
➢ Every C program must have one main ( ) function section.
➢ The main function has two parts.
1. The declaration section and the executable section.
2. The declaration part declares all the variables used in the executable part. There
should be at least one statement in the executable part.
➢ Declaration and executable parts should be within the opening and closing braces of the
main function.
➢ The execution of the program starts at opening braces and ends at the closing braces.
Closing braces is the logical end of the C program.
➢ All statements other than conditional branching and looping statements should end with
semi colon.
➢ The sub program section contains all the user defined functions that are called in the main
function.
➢ All sections, except main function section can be absent when they are not required.

Programming Style

An example considers the C program for addition of two numbers and the value of π.
#include<stdio.h> //includes functions for input and output operations. 27
/* definition section*/
#define PI 3.14 //defined the symbolic constant
/*global declaration section*/

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

int a=5; // Global variable declaration


void printoutput(float); // function declaration
/* main function section*/
void main()
{
float sum;
int b=10;
//Declaration Section
sum= a+b+PI;
//Executable Section
printoutput (sum);
}
/* sub program section*/
void printoutput(float sum)
{
Printf(“the sum of 2 numbers and PI is %f”, sum);
}

OUTPUT:

The sum of 2 numbers and PI is 18.

Executing a Program.
➢ Executing a C program involves the following steps.
1. Creating the program.
2. Compiling the program.
3. Linking the program with the functions that are needed from the C library.
4. Executing the program.
➢ Figure 1.2 shows the steps involved in compiling and running a program.

Creating the program in Unix OS


➢ The program to be executed should be entered in the file. The file name can consist of
letters, digits and special characters followed by a dot and a letter c.
➢ Examples of valid names include hello.c program.c
➢ The file can be created using text editor or vi editor
1. vi filename (vi hello.c)
2. The command for calling the editor and creating the file is ed ( or) vi ed filename
(ed hello.c)
➢ If the file with same name exists the already existing file gets open.
➢ When the editing is over the file is saved using: wq command.
28
➢ The program that is entered is known as source program.

Compiling and linking in Unix OS


➢ The source program may be compiled using the command cc filename.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

1. cc hello.c
➢ Each instruction is examined for its correctness and translated to the form suitable for
execution.
➢ The translated source program is stored under file with name filename.o (hello.o). This
program is known as object file/code.
➢ Linking is the process of putting together other required program files and functions to
our program. For , when we use mathematical functions like sine( ), cos( ), expo( ) in our
program, we use the extension –lm with cc command as below,
1. cc hello.c –lm

Executing the program in Unix OS


➢ The command used for executing a c program is. /a.out.
➢ This loads the executable object code in to computer memory and executes the
instructions.
o If there are any logical errors it would not provide the desired result.
Then it would be necessary to correct the source program.
o If the source program is changed the entire process of compiling, linking
and executing the program should be repeated.

Creating Your Own Executable file

➢ The linker always assigns the same name a.out.


➢ When we compile another program this file will be overwritten by the executable object
code of the new program.
➢ If we want to prevent from happening we should rename the file immediately by using
the command
▪ mv a.out name
➢ We can achieve this by specifying an option in the cc command as follows:
▪ Cc –o name source-file
➢ It will store the executable object code in the file name and prevent the old file a.out
from being destroyed.

Multiple Source Files

➢ To compile and link multiple source program files we must append all the files names to
the cc command.
▪ cc filename- 1.c …. filename- n.c
➢ These files will be separately compiled into object files called
▪ filename- i.o
➢ And then linked to produce an executable program file a.out as shown in figure 1.11
29

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

.C .C .C

Compiler and preprocessor

.O .O Library
.O

a.out

Figure 1.11 Compilation of multiple files

➢ It is possible to compile each file separately and link them later.


➢ Example, the commands are
▪ cc –c mod1.c
▪ cc –c mod2.c
➢ It will compile the source files mod1.c and mod2.c into objects files mod1.o and mod2.o
▪ cc –c mod1.o mod2.o

30

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

31

Figure 1.2 Process of compiling & running C Program

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming

32

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Module1
Computer Fundamentals & C Programming
1

2.2.3 Single character constants

 A single character constant contains a single character enclosed with in a pair of single quote
marks.
 Examples are as follows, ‘5’ ‘X’ ‘;’ ‘’
 Character constant ‘5’ is not same as the digit 5.
 ‘’ is a blank space constant.
 Every character constant is associated with a integer value called as ASCII value. For example
o printf (“%d”,a); would print the number 97, the ASCII value of a.
o Since each character is associated with a integer value, it is possible to perform
arithmetic operations on character constants.

2.2.4 String constants

 A string constant is a sequence of characters enclosed in the double quotes.


 The characters may be letters, digits, special characters and blank spaces.
 Example, “Hello!” “1987” “well done” “?...!” “5+3” “X”
 A character constant ‘X’ is not same as string constant “X”

2.2.5 Backslash character constants

 Backslash constants are used in the output functions.


o Each of the backslash character constants represents one character even though they
have two characters in them.
 Backslash constants are also known as escape sequences.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1

2.3 VARIABLES
 A variable is a data name that may be used to store a data value.

 A variable is a name given to the memory location.

 A variable may take different values at different times during the execution of the program.

Rules for writing a variable name


 They must begin with a letter or an underscore.

 The variable names should be of 31 characters. Some compilers consider only 8 characters out
of 31.

 Variables are case sensitive. That is, Total and total are not same.

 It should not be a keyword.

 White space is not allowed. For example hello word is invalid.

 No two consecutive underscores can be used.

 Table 1.6 shows the example of valid and invalid variables.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1

2.4 DATA TYPES


 The type of data stored in the computer memory is called as the data type.
 ANSCI C supports 3 classes of data types
 Primary or fundamental data types.
 Derived data types
 User-defined data types.
 All C compilers supports 5 fundamental data types, namely integer (int), character (char),
floating point
 (float) double-precision floating point (double) and void.
 The various data types and the terminology used to describe them is shown in figure 1.4
 The range of basic 4 types is shown in table 1.7.
 The size and range of extended data types on 16-bit machines are shown in table 1.8.
 The data types and their key words are shown in table 1.9.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1

2.4.1 Integer types


Prof Kavya M S & Prof Shridevi Desai
Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
 Integers are whole numbers with a range of 1 values supported by particular machines.
 Integer has a size of word that is 8 bits (2 bytes).
 The range of integer in 16 bit machine is -2n-1 to +2n-1-1. Where n is 16,32 or 64 bit
machine.
 A signed integer uses one bit for sign and 15 bits for the magnitude of the number.
o To provide control over the range of numbers and storage space, there are three
classes of integer storage namely short int, int and long int in both signed and
unsigned forms and are as shown in figure 1.5
o Short int represents fairly small integer values and requires half the amount of
storage as regular int number uses.

 Unsigned integers use all the bits for magnitude of the numbers and are always positive.

 Table 1.8 shows the range of int, short int and long int.

2.4.2 Floating Point Types


 Floating point numbers are stored in 32 bits (4 bytes), with 6 digits of precision.

 Floating point numbers in C are represented by float keyword.

 To increase the accuracy of the floating point number, double data type can be used.

 Double uses 64 bits giving a precision of 14 digits.

 Long double uses 80 bits.

 The figure 1.6 shows the floating point types.

Figure 1.5: Float Types.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
2.4.3Void types 1

 Void types has no values


 Void types are used to specify the type of functions.

2.4.5 Character types

 A single character is defined as a char type data.


 Char type uses a size of 8 bits(1 byte).
 Unsigned char has the value between 0 to 255 and signed chars have -128 to 127.

2.5 DECLARATION OF VARIABLES

 Declaration of variable must be done before they are used in the program.
 It tells the compiler what the variable name is
 It specifies what type of data the variable will hold.

2.5.1 Primary type declaration


 The syntax for declaring a variable is as follows.
 Data type v1,v2,v3…vn;
 v1,v2..vn are the names of the variables and are separated by commas.
 Declaration statement should end with semicolon (;).
 Example, int count; int number, total; double ratio;

Data type Keyword equivalent


Character Char
Unsigned char
Unsigned Character Signed char
Signed character Signed int or int
Signed short int (or short int or short)
Signed integer Signed long int(or long int or long)
Unsigned int (or unsigned)
Signed short integer unsigned
Short int(or unsigned short)
Signed long integer Unsigned
Long int(or unsigned long) float
Unsigned integer Double long
Double
Prof Kavya M S & Prof Shridevi Desai
Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
Unsigned short integer 1 Long double
Unsigned long integer

Floating point
Double-precision floating point
Extended double precision floating point

Table 1.9 data types and their keyword

2.5.2 User-defined type declaration

 Type definition is a feature that that allows user to define an identifier that would represent
an existing data type.
 The user defined data type identifier can later be used to declare variables.
 The syntax of type definition is as follows,
o typedef type identifier;

 Example,

o typedef int units;

o typedef float marks;

 In the above example, unit symbolizes int and marks symbolizes float. They can be
used to declare variables as follows,

o units batch1, batch2;

o marks name1[50], name2[50];

 The main advantage of typedef is to create meaningful data type names for increasing the
readability of the program.
 Enumerated data type is another form of user defined data type which is defined as
follows,
o enum identifier {value1,value2,…valuen};
 The identifier in the above syntax is an user defined enumerated data type which can be
used to declare variables that can have one of the values enclosed in the braces known as
enumeration constants.
 After the definition, enumeration variables can be declared as
o enum identifier v1,v2,v3,…vn;

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1 of the values of enumeration constants. i.e,
 Where v1,v2,v3…vn can have only one

o v1=value3;

o v5=value1; are valid.

 As an example,

o enum day{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

o enum day week_st, week_end; week_st=Monday; week_end=Sunday;

 The compiler automatically assigns integer digits beginning with 0 to all the enumeration
constants. i.e, 1st enumeration constant has the value 0 and the counting follows.
 The automatic assignments of values to the enumeration constant can be overridden
assigning values explicitly.
 enum day { Monday=1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };

 With this definition by default Tuesday will have the value 2.

 Definition and declaration of enumeration can be done in a single line as follows.

 enum day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}


week_st, week_end;

2.6 Declaration of storage class


 Storage class provides information about the location and visibility of a variable.

 The storage class decides the portion of program with in which the variables are
recognized.

 Consider the following example,

int m;  In the program the variable m is a


global variable and can be used in all
Main( ) the functions in the program.

{
int i;  Global variables are also called as
float balance;
external variables.
……..
….....
Function1( );  The variables i, balance and sum are
} local variables declared with in main
Function1( ) and function1.
{

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
int i; 1
float sum;
……..
 Even though the variable i is declared
……..
in both main and function1 they are
}
independent on each other.

There are 4 storage class specifiers in the below table

Storage class Meaning


1. auto Local variable known only to the function in which it is declared.
2. static Local variable that exists and retains its values even after the control is
transferred to calling function
3. extern Global variable known to all functions in the file
4. register Local variable stored in the register.
Table 1.10: Storage Classifiers

Examples shown below

auto int count;


register char ch;
static int x;
extern long total;

2.7Assigning values to variables


 Values can be assigned to variables in three ways, simple assignment, multiple assignment
and shorthand assignment.
 Values can be assigned to the variables using the assignment operator = as follows,
Variable_name=constant;
 Example, sum=100; this type of assignment is called simple assignment.
 C allows several assignment statements in one line as follows;
 Variabl1=value1; variable2=value2;……variablen=valuen
 Example, initial value=100; final value=200;
 Multiple assignment of same value can be done to the variables of same data type as
follows,Variable1=variable2=variable3=….variablen=value
 Example, a=b=c=100;
 We can assign a value to the variable at the time of variable declaration as follows,
o data_type Variable_name=constant;
o int final_value=100;
o float average=10.5;
o char x=’x’;

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
 Short hand assignment operation can have 1 the following syntax, Variable+=value; (note we
can have + - * / %)
 Example; let us assume the initial value of a=10; a+=5; is same as a=a+5; a=10+5=15

2.8 Defining symbolic constants


 A constant is an entity whose value do not change during the execution of C program.
 Example of constant is “pi” which has the value 3.142.
 The problem in the program with such constant is as follows,
1. Problem in modification of the program and
2. Problem in understanding the program.
 Assignment of constants to symbolic names helps us to overcome these problems.
 Constant values are assigned to these names at the beginning of the program.
 Subsequent use of the names in the program has the effect of causing their defined values to
be automatically substituted at the appropriate points in the program.
 A constant is defined as follows
o #define symbolic_name value_of_constant
o Examples of symbol constants are as follows:
o #define STRENGTH 100
o #define PI 3.14159
 Symbolic names are sometimes referred as symbolic identifiers.
 The following are the rules for symbolic constants.
1. Symbolic names have the same form as variable names. Usually in capital letters.
2. No blank space between the pound sign ‘#’ and the word define is permitted.
3. ‘#’ must be the first character in the word.
4. A blank space is required between #define and symbolic name.
5. A blank space is required between symbolic name and a constant.
6. After definition, the symbolic name should not be assigned any other value within the
program by using an assignment statement. For example, STRENGTH=20 is illegal.
7. Symbolic names are not declared for data types. It data type depends on the type of
constant.
8. # define statement should not end with the semicolon.
9. #define statements may appear anywhere in the program but before it is referenced in the
program. Usual practice is to place them in the beginning of the program).
 We can make a variable as a constant by using ‘const’ keyword/qualifier at the time of
declaration of a variable.
 Example, const int class_size=40;
 The above declaration says the variable class_size has the value 40 and it is declared as a
constant and its value should not be changed during the execution of the program.
Statement Validity Remark
#define X= 2.5 Invalid = sign is not allowed
# define MAX 10 Invalid No White space b/w # & define
#define N 25; Invalid No semicolon at the end
Prof Kavya M S & Prof Shridevi Desai
Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
#define N 5, M 10 Invalid 1 A statement can define only one name
#Define ARRAY 11 Invalid Define should be in lowercase
#define PRICE$ 100 Invalid $ symbol is not permitted in name

2.9 Declaring a variable as constant


 Certain variables to remain constant during the execution of a program.
 Achieve this by declaring with the qualifier const at the time of initialization.
 Example: const int class_size = 40;
 Const is a new data type qualifier defined by ANSI standard.
 This tells the compiler that the value of the int variable class_size must not be modified.

2.10 Declaring a variable as volatile


 Volatile is a keyword/qualifier that could be used to explicitly tell the compiler that variables
may be changed at any time by some external sources (from outside the program). For
example volatile int date;

 When a variable is declared as volatile, the compiler will examine the value of the variable
each time it is encountered to see if any alterations had been made to the value.

 The variable declared as volatile can also be changed by its own program.

 If we do not want a variable to be changed by its own program but wants to get changed by
external programs then we need to declare the variable both as constant and volatile as
shown below.

 volatile const int location=100;

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1

OPERATORS AND EXPRESSIONS


 An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
 Operators are used to manipulate data and variables. They usually form the part of
mathematical or logical expressions.
 C operators can be classified in to number of categories, some of them are as follows,
o Arithmetic operators
o Relational operators
o Logical operators
o Assignment operators
o Increment and decrement operators
o Conditional operators
o Bitwise operators
o Special operators.
 An expression is a sequence of operands and operators that reduces to a single value. For
example,
 10+5 is an expression whose value is 25. The value can be any type other than void.

3.1Arithmetic Operators
Prof Kavya M S & Prof Shridevi Desai
Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1
 Table 1.11 show the list of arithmetic operators

 The unary minus operator multiplies its single operand by -1. Therefore, a number preceded by
minus sign changes its sign.
 The integer division truncates any fractional part.
 The modulo division operator produces the remainder of an integer division.
o Examples of usage of arithmetic operators are as follows,
a-b a*b a%b
a+b a/b -a*b
 Note that a and b are variables and are called as operands.
 The modulo division operators cannot be used on floating point data.

3.1.1 Integer arithmetic

 When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression. And the operation is called integer arithmetic.
 Integer arithmetic always yields an integer value. If a and b are integers, then a=14 and b=4 we
have the following results.
 During modulo division, the sign of the result is always the sign of the first operand(the
dividend).
 Example, -14%3=-2

 Example program to show the implementation of integer arithmetic to convert a given


number of days into months and days.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1

3.1.2 Real arithmetic

 An arithmetic operation involving only real operands is called real arithmetic.


 The real operand may assume values either in decimal or exponential notation.
o Floating point values are rounded to the number of significant digits permissible;
the final value is the approximation of correct result.
 If x, y and z are floats then we have
 x=6.0/7.0=0.857143 y=1.0/3.0=0.333333 z=-2.0/3.0=-0.666667.
 The operator % cannot be used with real operands.

3.1.3 Mixed mode arithmetic

 When one of the operands is real and the other is integer, the expression is called Mixed
mode arithmetic expression.
 If either operand is of real type, then only the real operation is performed and the result is
always a real number. Thus 15/10.0=1.5.
Precedence of operator
 The order in which different operators are used to evaluate an expression is called
precedence/hierarchy of operators.
 The operators are evaluated from higher precedence to lower precedence.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
Arithmetic expressions 1

 An arithmetic expression is a combination of variables, constants and operators arranged as per


the syntax of the language. The table 1.12 shows different arithmetic expressions and their C
equivalents.

Associativity of operator

 Associativity determines how operators with the same precedence are evaluated in an expression.
o Precedence is applied before Associativity and Associativity is applied if
operators have same precedence.
 Associativity has two types.
o Left Associativity: In an expression if two or more operators have same priority and are
evaluated from left to right then operators are called left to right associative. Example ,
4/2*3
o Right Associativity: In an expression, if two or more operators have same priority and are
evaluated from right to left then operators are called right to left associative. Example,
assignment operator.

Precedence of arithmetic operators


 An arithmetic expression without parentheses will be evaluated from left to right using the
rules of precedence.
 There are two distinct priority levels of arithmetic operators in c.

o High priority * / %

o Low priority + -

 The evaluation of arithmetic expressions involve two left to right passes through the expression.
 In the first pass, the high priority operators are applied as they are encountered.
 In the second pass the low priority are applied as they are encountered.
 Example, x=a-b/3+c*2-1 where a=9, b=12 and c=3 the statements become
o X=9-12/3+3*2-1
o And it is evaluated as follows,
o First pass
o Step 1:x=9-4+382-1
o Step 2:x=9-4+6-1
o Second pass
o Step 3: x=5+6-1
o Step 4: x=11-1
o Step 5: x=10
 Problem: evaluate the expression 2*((a%5)*(4+(b-3)/(c+2))) Assuming a=8,b=15 and c=4,
 Solution:

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
o 2*((8%5)*(4+(15-3)/(4+2))) 1
o 2*(3*(4+(15-3)/(4+2)))
o 2*(3*4+12/(4+2)))
o 2*(3*4+12/6)
o 2*(3*4+2)
o 2*(3*6)
o 2*18
o 36

Rules for evaluation of expressions

 First parenthesized sub expressions from left to right are evaluated.


 If parentheses are nested, the evaluation begins with innermost sub expression.
 The precedence rule is applied in determining the order of application of operators in
evaluating sub expressions.
 The associativity rule is applied when two or more operators of the same precedence level
appear in the sub expression.
 Arithmetic expressions are evaluated from left to right using rule of precedence.
 When parentheses are used, the expression with in parenthesis assumes highest priority.

Relational operators
 Relational operators are the operators used to compare two operands.
 A simple relational expression takes contains only one relational operator and takes the following
form.
o ae-1 relational operator ae-2
 Where, ae-1 and ae-2 are arithmetic expressions, which may be simple constants,
variables or combination of them. The table 1.13 shows the list of relational operators.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
 Some examples of relational expressions and1 their values are as follows,
o 4.5<=10 TRUE
o 4.5<-10 FALSE
o -35>=0 FALSE
o 10<7+5 TRUE
 When arithmetic expressions are used on either side of relational operator, the arithmetic
expression will be evaluated first and then the results compared. i.e., arithmetic operators
have higher priority than relational operator.
 Relational expressions are used in decision statements such as if and while.
 Among the 6 relational operators, each one is a complement of another operator as follows.
o > Is a complement of <=
o < is a complement of >=
o == is complement of !=
 We can simplify an expression involving not and the less than operators using the
complements as,

Precedence rule for evaluating relational operators


 Evaluate braces
 Evaluate unary operator
 Evaluate arithmetic operators
 Evaluate relational operator
Evaluation of relational expression
o 100/20<=10-5+100%10-20==5>=1!=20
o 5<=10-5+10%10-20==5>=1!=20
o 5<=10-5+0-20==5>=1!=20
o 5<=5+0-20==5>=1!=20
o 5<=5-20==5>=1!=20
o 5<=-15==5>=1!=20
o 0==5>=1!=20
o 0==1!=20

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
o 0!=20 1
o 1

Logical operator
 The logical operators are the operators that combine two or more relational expressions.
o An expression which combines two or more relational expressions using logical
operators is called as logical expressions or compound relational expressions.
o The following table 1.14 shows the available relational operators and their
meaning, priority and associativity in C.

 Logical expressions also yield a value of one or zero according to the truth table 1.15.

Precedence rule for evaluating logical operators

o Evaluate braces

o Evaluate unary operator

o Evaluate arithmetic operators

o Evaluate relational operator

o Evaluate logical operator

Evaluation of logical expression

a+2>b&&!c||a!=d&&a-2<=e where, a=11,b=6,c=0,d=7 and e=5

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
o 11+2>6&&!0||11!=7&&11-2<=5 1

o 11+2>6&&1||11!=7&&11-2<=5

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1
o 13>6&&1||11!=7&&11-2<=5

o 13>6&&1||11!=7&&9<=5

o 1&&1||11!=7&&9<=5

o 1&&1||11!=7&&0

o 1&&1||1&&0

o 1||1&&0

o 1||0

o 1

Assignment operators
 Assignment operators are used to assign the result of an expression to a variable.

 There are three types of assignment operators.

o Simple assignment

o Shorthand assignment or compound assignment

o Multiple assignments.

 Simple assignment statements


Syntax: variable=expression;

 Example, a=10;// variable is assigned to a constant a=10+20;// variable is assigned to a result of


an expression a=b+c;// variable is assigned to a result of an expression a+b=c; //invalid

Multiple assignment statements

 A statement using which a value or a set of values are assigned to different variables is called
multiple assignment statement.

 For example, int a,b,c;

 a=b=c=10;

Shorthand assignment statements

 The operators such as +=, -=, *=,/=,%= are called as shorthand assignment statements.
Prof Kavya M S & Prof Shridevi Desai
Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1 associative.
 Short hand assignment operators are right to left

 Syntax: v op=exp;

o Where, v is a variable, exp is an expression and op is a c binary Airthematic operator.

 v op=exp; is equivalent to v = v op (exp);

o Example, x+=y+1; x = x
+ (y+1) X+=3; x=x+3

 Advantages of shorthand assignment are as follows

o What appears on the left-hand need not be repeated and therefore it becomes easier to write.

o The statement is more concise and easier to read

o The statement is more efficient.

Precedence rule for evaluating assignment operators

o Evaluate braces
o Evaluate unary operator

o Evaluate arithmetic operators

o Evaluate relational operator

o Evaluate bitwise operator

o Evaluate logical operator

 Evaluate ternary operator

 Evaluate assignment operator

Evaluation of assignment expression

 a+=b*=c-=5 where a=1,b=3 and c=7

 c=c-5 c=2

o a+=b*=2
a+=6
b=b*2
a=a+6
b=3*2
Prof Kavya M S & Prof Shridevi Desai
Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
a=1+6 b=6 1
a=7

Increment or Decrement Operator


 Increment operator (++) increases the value of the variable by 1 and decrement operator (--)
decreases the value of variable by 1. And they are unary operators.

 Increment operators can be pre-increment or post-


increment.

Post increment

 Increment operator is placed after (post) the variable.

 Operand value is used first and then the operand value is incremented by 1.

o Example, int a,b;


o a=1;
o b=a++; //b=1, a=2

Pre increment
 Increment operator is placed before (pre) the variable.

 Operand value is incremented by 1 and then used.

o Example, int a,b;

o a=1;

o b=++a; //b=2, a=2

Pre decrement

 Decrement operator is placed before (pre) the variable.

 Operand value is decremented by 1 first and then the Operand value is used.

o Example, int a,b;

o a=3;

o b=--a; //b=2, a=2


Post decrement

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1
 Decrement operator is placed after (post) the variable.

 Operand value is used first and then the operand value is decremented by 1.

o Example, int a,b;

o a=3;

o b=a--; //b=3, a=2

Rules for ++ and – operators

 Increment and decrement operators are unary operators and they require variables as their operands.

 When postfix ++ or -- is used with a variable in an expression, the expression is evaluated first
using original value of the variable and the variable is incremented or decremented by 1.

 When prefix ++ or -- is used with a variable in an expression, the variable is incremented


or decremented by 1 first and the expression is evaluated using new value of the variable.

 The precedence and associativity of ++ and – operator are the same as those of unary + and unary -

Conditional Operator / Ternary operator


 Conditional operators are used to construct the conditional expressions in C.

 As the name imply it operates on 3 operands. It is also called as ternary operator.

 Syntax: (exp1)?exp2:exp3;

 If exp1 is evaluated to true, exp2 is executed.

 If exp1 is evaluated to true, exp3 is executed.

 Example, int a, b, big; a=10;


b=15; big=(a>b)?a:b; // big=15

Bitwise operator
 Bitwise operators are used to manipulate data at the bit level.

 They can be operated on float or double.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1

Special operators
 C supports some special operators such as,

o Comma operator

o Sizeof operator

o Pointer operators (& and *)

o Member selection operator (. And )

 Comma operator is used to link the related expressions together.

 Combines two or more statements in to a single statement.

 Comma has the least precedence.

 Comma is left to right associative operator.

 Example, printf(“%d”,”%d”,a,b);

o Sizeof is a compile time operator when used with an operand it returns the number of bytes
of memory occupied by the operands. Operands may be a variable, a constant or a data type.

o Example
m=sizeof(sum);
n=sizeof(long
int);
k=sizeof(235L);

Type Conversion or Type Casting in C


 The process of instructing the compiler to convert data from one data type to another data type is
called as type casting or type conversion.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
 There are two forms in type conversion. 1

o Implicit conversion

o Explicit conversion

Implicit conversion
 The process of conversion of data from lower rank data type to higher rank data type automatically by
the C
o compiler is called as implicit conversion.

o If both the operands are of same rank no conversion takes place and the results is same as the
operands.

 If one operand is of low rank and the other is of higher rank then the low rank operand is converted in
to high rank and the result is high ranked.

Figure 1.6 conversion hierarchy

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
1

Rules that are applied while evaluating expressions.


1. If one of the operands is long double, the other will be converted to long double and the result will be
long double.
2. Else, if one of the operands is double, the other will be converted to double and the result will be
double.
3. Else, if one of the operands is float, the other will be converted to float and the result will be float.
4. Else, if one of the operands is unsigned long int, the other will be converted to unsigned long int and
the result will be unsigned long int.
5. Else, if one of the operands is long int, the other is long int and then
a) if unsigned int can be converted to long int, the unsigned int operand will be converted as
such and the result will be long int.
b) else, both operands will be converted to unsigned long int and the result will be unsigned
long int
6. Else, if one of the operands is long int, the other will be converted to long int and the result will be
long int.
7. Else, if one of the operands is unsigned int, the other will be converted to unsigned int and the result
will be unsigned int.

Explicit conversion

 The process of forcible conversion of data from one data type to another is called as explicit type
conversion.
 Syntax: (type_name) expression;
 Type can be any required data type and expression may be operand such as variable or
a constant. int p=7;
o int q=2; float r; r=p/q;
o Without explicit conversion r=7/2=3.00
o With explicit conversion r=(float)7/2=3.500000
Example Action
x= (int) 7.5 7.5 is converted to integer by truncation
a= (int) 21.3/(int) 4.5 Evaluated as 21/4 and the result would be 5
b= (double)sum/n Division is done in floating point mode
y= (int) (a+b) The result of a+b is converted to integer
Prof Kavya M S & Prof Shridevi Desai
Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
z= (int)a+b 1 a is converted to integer and then added to b
p= cos((double)x) Converts x to double before using it.

Operator Precedence and associativity.

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT
Module1
Computer Fundamentals & C Programming
25

Prof Kavya M S & Prof Shridevi Desai


Dept of CSE, TJIT

You might also like