Pps Notes
Pps Notes
Dinarpur, (Ambala)
INTRODUCTION:
CONTENTS:
1.1 INTRODUCTION
1.1.1 Advantages of computers
1.1.2 Limitations of computers
1.1 INTRODUCTION
Definition : A Computer is an electronic device that can perform activities that involve
Mathematical, Logical and graphical manipulations. Generally, the term is used to describe a
collection of devices that function together as a system.
It performs the following three operations in sequence.
1. It receives data & instructions from the input device.
2. Processes the data as per instructions.
3. Provides the result (output) in a desired form.
Data : It is the collection of raw facts, figures & symbols. Ex : Names of students and their
marks in different subjects listed in random order.
Information : It is the data that is processed & presented in an organized manner.
Ex : When the names of students are arranged in alphabetical order, total and average marks are
calculated & presented in a tabular form, it is information.
Program : Set of instructions that enables a computer to perform a given task.
1. Input device
2. Central Processing Unit (CPU)
3. Output device
Unit Function
[Link] device : Reads information from input media and enters to the
computer in a coded form
[Link]
(a) Memory unit : Stores program and data
(b) Arithmetic Logic unit : Performs arithmetic and logical functions
(c) Control Unit : Interprets program instructions and controls the input and
output devices
3. Output device : decodes information and presents it to the user
(a). Memory Unit: It is also known as the primary storage or main memory. It stores data,
program instructions, internal results and final output temporarily before it is sent to an
appropriate output device. It consists of thousands of cells called storage locations. These cells
activate with off-on or binary digits (0,1) mechanism. Thus a character either a letter or
numerical digit is stored as a string of (0,1) Binary digits ( BITS). These bits are used to store
instructions and data by their combinations.
(b) Arithmetic and Logical Unit(ALU): It is the unit where all Arithmetic operations (addition,
subtraction etc.) and logical functions such as true or false, male or female are performed. Once
data are fed into the main memory from input devices, they are held and transferred as needed to
ALU where processing takes place. No process occurs in primary storage. Intermediate
generated results in ALU are temporarily placed in memory until needed at later time. Data may
move from primary memory to ALU and back again to storage many times before the process is
finalized.
(c).Control Unit : It acts as a central nervous system and ensures that the information is stored
correctly and the program instructions are followed in proper sequence as well as the data are
selected from the memory as necessary. It also coordinates all the input and output devices of a
system .
Conversion :
ASCII – American Standard Code for Information Interchange. This code has given alphabets
like some numbers which can be converted to Binary form.
RAM:
RAM is also known as read/write memory as information can be read from and written
onto it. RAM is a place in a computer that holds instructions for the computer, its
programs and the data. The CPU can directly access the data from RAM almost
immediately. However, the storage of data and instructions in RAM is temporary, till the
time the computer is running. It disappears from RAM as soon as the power to the
computer is switched off. i.e it is volatile memory.
ROM:
It is called Read-only memory as information can only be read from and not written or
changed onto ROM. ROM is the ‗built-in‘ memory of a computer. It stores some basic
input – output instructions put by the manufacturer to operate the computer. The storage
of data and instructions in ROM is permanent. It does not depend on the power supply.
i.e it is non-volatile memory.
Secondary memory: The primary memory which is faster (and hence expensive) is
generally not sufficient for large storage of data. As a result, additional memory, called the
―auxiliary or ―secondary memory is used. It is also referred as ―backup storage as it is
used to store large volume of data on a permanent basis which can be transferred to the primary
memory whenever required for processing. Data are stored in secondary storage in the same
binary codes as in the main (primary memory) storage.
Some of the devices of secondary storages are Floppy Disk, Hard Disk, CD-ROM, DVD and
Flash drive.
FLOPPY DISK:
It is also referred as ―Diskette: and is made of flexible Vinyl material. It has a small hole
on one side called ―Right protect notch, Which protects accidental writing/deleting the
information from the disk. There is a hole in the centre through which the spindle of drive
unit rotates the disk. The disks are available in two sizes of 5.25 and 3.5 inches and these
could be either low density or high-density floppies. Storage capacity of floppies are
measured in kilobytes (KB) and megabytes (MB). The details about the storage capacities
of the floppies are presented below:
HARD DISK:
The hard disk can hold more information than the floppy disk and the retrieval of
information from hard disk is faster when compared to floppies or tapes. A hard disk is
fixed inside the CPU and its capacity ranges from 20 MB onwards. The hard disk is made
up of a collection of discs (one below the other) known as platters on which the data is
recorded. These platters are coated with magnetic material. It is less sensitive to external
environmental disorders and hence the storage in hard disk is safe. A small hard disk
might be as much as 25 times larger than a floppy disk. Storage Capacity of hard disks
varies from 20 MB to several Gega bytes like 80GB, 160GB.
CD-ROM:
CD-ROM stands for Compact Disk–Read Only Memory. It is used to store a wide variety
of information. Its main advantage is that it is portable and can hold a large amount of
data.. The storage capacity of most CD-ROMs is approximately 650 MB or 700 MB.
DVD:
DVD stands for Digital Versatile Disc. It is similar to a CD-ROM, except that it can store
larger amounts of data. The storage capacity of a DVD is at least 4.7MB. DVDs that can
store up to 17GBs are also available. Because of their capacity, DVDs are generally used
to store a very large multimedia presentations and movies that combine high quality
sound and graphics.
FLASH DRIVE:
It is a small, portable device that can be used to store, access and transfer data. Due to its
small size, it is commonly called Pen drive. It is also called USB drive. We can read,
write, copy, delete, and move data from computer to pen drive or pen drive to computer.
It comes in various storage capacities of 2GB, 4GB, 8GB etc. It is popular because it is
easy to use and small enough to be carried in a pocket. This device is plugged into the
USB port of the computer and the computer automatically detects this device.
SUMMARY
In this lesson, we studied about the basic concept of computer system. Also studied about
advantages, characteristics and limitations of computer system.
The basic structure of CPU has been explained in this lesson. It is the part of the
computer that carries out the instructions of a computer program. It is the unit that reads
and executes program instructions. Hence it is known as the brain of the computer.
Memory or storage capacity is one of the important components of a computer.
A computer memory is of two types:
Primary Memory (Internal storage) and Secondary Memory ( External storage)
REVIEW QUESTIONS
Q.1Define Computer System? What is the working and functions of computer system?
Q.3What is the memory units and explain the memory architecture with diagram?
REFERENCES
Topic: Main and Auxiliary Storage Devices, Input Devices, Output Devices Lecture
required
INTRODUCTION:
Storage is devices that hold instructions and data. Computers have two different
types of storage: primary and [Link]/ Output devices are required for
users to communicate with the computer. In simple terms, input devices bring
information INTO the computer and output devices bring information OUT of a
2
computer system. These input/output devices are also known as peripherals since
they surround the CPU and memory of a computer system.
CONTENTS:
Storage is devices that hold instructions and data. Computers have two different types of
storage: primary and auxiliary.
There are different types of ROM, including PROM EPROM and EEPROM.
PROM – Programmable Read Only Memory – In this type of ROM, data or program can be
stored once in PROM but never changed.
EPROM – Erasable Programmable Read Only Memory – In this type of ROM, data or program
can be erased by removing the device and exposed it to ultraviolet light.
EEPROM – Electrically Erasable Programmable Read Only Memory – data or program can be
completely erased using a special device and new programs or new data can be stored in it.
The Use of Primary Storage (RAM)
Main Memory has several uses:
- Input area – where the data is stored when it is read into CPU, awaiting processing.
- Operating system – controls the operation of the computer.
- Working storage – where calculations are performed and data is stored temporarily.
- Output area where the information is stored prior to output. Both the input and output areas are
buffer.
- Application program area – where the user program is held.
The Use of Main Memory (RAM)
Operating System
Input Area Application area (Program) Output Area
Working storage area
Difference between ROM and RAM
ROM RAM
ROM is nonvolatile RAM is volatile
ROM is cheaper than RAM RAM is very expensive
The contents of ROM are always known The contents are not known
and can be verified
ROM cannot be updated or corrected RAM can be updated and corrected
ROM serves as permanent data storage RAM can serve as temporary data
storage
HARD DISKS
Most PC's have an internal hard disk, but external disks may be used too. External disks
sit alongside the computer in an extra 'box' with its own power supplies and plug socket.
An average PC may have 2Gb (230x 2 bytes = 1073741824 x 2 bytes, i.e 2147483648
bytes). 1 Gb = 230 bytes. The standard size has increased dramatically over recent years
as ever more.
IDE (Integrated Drive Electronics) and Extended IDE (EIDE) are hard disk technologies
common on PC's.
More powerful and flexible are SCSI (Small Computer System Interface, pronounced
'SCUZZY') and 'firewire' (1394). The difference between these system lies in the way
that data in transmitted between the hard disk and the processor.
FLOPPY DISKS
Modern PCs will also have one or two floppy disk drives. The floppy disk provides a cost
effective means of on-line storage for small business computer systems.
Floppy disk are used in the smallest microcomputer system as well as with
minicomputers and are particularly useful in providing a means of decentralized
processing.
A 'floppy' disk can be 3.5" in diameter or 5.25". A 3.5" disk can hold up to 1.44Mb of
data.
TAPE STORAGE
Like an audio or videocassette, data has to be recorded along the length of a computer
tape.
In using tapes, it is not practical to read from and then write on to a single piece of tape at
the same time.
Reading and writing are separate operations, using separate heads, and so two drives are
necessary for the two operations.
Magnetic tape as a file storage medium is only practical when every record on the file
will be processed in turn.
Tape cartridges have a larger capacity than floppy disks and they are still widely used as
a backing storage medium.
They are generally measured in terms of tape width and length for instance, an 8mm tape
that is 112m long can store up to 5Gb of data, a 4mm tape of 125m can store up to 12Gb.
Fast tape, which can be used to create a back-up file very quickly, are known as TAPE
STREAMERS. Since tapes can only be updated by producing a completely new carried
forward tape this provides an automatic means of data security.
It uses similar technology to the based laser based compact disc audio system for data
storage.
The capacity of optical disk is very compared with other media and they are more
difficult to damage.
The latest PCs are now automatically with a CD-ROM drive and some software packages
are now only available on CD-ROM. CD-ROM stands for Compact Disc Read-Only
Memory.
This means that data is implanted onto the disc when it is made, and subsequent users can
only retrieve information, they cannot alter or overwrite or delete what is already on the
disk.
The speed of CD-ROM drive is relevant to how data can be retrieved; an eight speed
drive is quicker than four speed drive. CD recorders are now available for general
business use with blank CDs (CD-R). A CD-R can hold up to 650Mb. Once made, CD-
ROMs are not reusable in the way that floppy disk are.
However, a reusable disk (CD-RW) has recently become available.
Difference between Primary and Secondary Storage
Primary Secondary
Primary storage/memory is also called Secondary storage or memory is also
Internal or main storage. called External or auxiliary storage.
High speed Low speed
It is very expensive It is not expensive as primary storage
It holds data or programs temporary It holds data or programs permanently
It holds programs and data in current It holds program or data that will still
use in CPU be used in primary storage
It is faster than secondary It is not fast as primary
It holds less data It holds large volume of data or files
Input/ Output devices are required for users to communicate with the computer. In simple terms,
input devices bring information INTO the computer and output devices bring information OUT
of a computer system. These input/output devices are also known as peripherals since they
surround the CPU and memory of a computer system.
Some commonly used Input/ Output devices are listed in table below:
Alphanumeric Keypad consists of keys for English alphabets, 0 to 9 numbers, and special
characters like +−/*( ) etc.
Function Keys are twelve keys labeled F1, F2, F3… F12. The functions assigned to these keys
differ from one software package to another. These keys are also user programmable keys.
Special-function Keys have special functions assigned to them and can be used only for those
specific purposes. Functions of some of the important keys are defined below.
Enter is similar to the ‘return’ key of the typewriter and is used to execute a command or
program.
Spacebar is used to enter a space at the current cursor location.
Backspace key is used to move the cursor one position to the left and also delete the character in
that position.
Delete is used to delete the character at the cursor position.
Insert key is used to toggle between insert and overwrite mode during data entry.
Shift key is used to type capital letters when pressed along with an alphabet key. Also used to
type the special characters located on the upper-side of a key that has two characters defined on
the same key.
Caps Lock is used to toggle between the capital lock features. When ‘on’, it locks the
alphanumeric keypad for capital letters input only.
Tab is used to move the cursor to the next tab position defined in the document. Also, it is used
to insert indentation into a document.
Ctrl key is used in conjunction with other keys to provide additional functionality on the
keyboard.
Alt also like the control key, Alt key is always used in combination with other keys to perform
specific tasks.
Esc key is usually used to negate a command. Also used to cancel or abort executing programs.
Numeric Keypad is located on the right side of the keyboard and consists of keys having
numbers (0 to 9) and mathematical operators (+ − * /) defined on them. This keypad is provided
to support quick entry for numeric data.
Cursor Movement Keys are arrow keys and are used to move the cursor in the direction
indicated by the arrow (up, down, left, right).
[2] MOUSE
The mouse is a small device used to point to a particular place on the screen and select in
order to perform one or more actions.
It can be used to select menu commands, size windows, start programs etc.
The most conventional kind of mouse has two buttons on top: the left one being used
most frequently.
Mouse Actions
Left Click : Used to select an item.
Double Click : Used to start a program or open a file.
Right Click : Usually used to display a set of commands.
Drag and Drop : It allows you to select and move an item from one location to another. To
achieve this place the cursor over an item on the screen, click the left mouse button and while
holding the button down move the cursor to where you want to place the item, and then release
it.
[3] JOYSTICK
The joystick is a vertical stick which moves the graphic cursor in a direction the stick is
moved. It typically has a button on top that is used to select the option pointed by the
cursor. Joystick is used as an input device primarily used with video games, training
simulators and controlling robots
[4] SCANNER
Scanner is an input device used for direct data entry from the source document into the
computer system. It converts the document image into digital form so that it can be fed
into the computer. Capturing information like this reduces the possibility of errors
typically experienced during large data entry.
Hand-held scanners are commonly seen in big stores to scan codes and price information for
each of the items. They are also termed the bar code readers.
[3] PRINTER
Printers are used to produce paper (commonly known as hardcopy) output. Based on the
technology used, they can be classified as Impact or Non-impact printers.
Impact printers use the typewriting printing mechanism wherein a hammer strikes the
paper through a ribbon in order to produce output.
Dot-matrix and Character printers fall under this category.
Non-impact printers do not touch the paper while printing. They use chemical, heat or
electrical signals to etch the symbols on paper.
Inkjet, Deskjet, Laser, Thermal printers fall under this category of printers.
When we talk about printers we refer to two basic qualities associated with printers: resolution,
and speed. Print resolution is measured in terms of number of dots per inch (dpi). Print speed is
measured in terms of number of characters printed in a unit of time and is represented as
characters-per-second (cps), lines-per-minute (lpm), or pages-per-minute (ppm).
[4] PLOTTER
Plotters are used to print graphical output on paper.
It interprets computer commands and makes line drawings on paper using multicolored
automated pens.
It is capable of producing graphs, drawings, charts, maps etc.
Computer Aided Engineering (CAE) applications like CAD (Computer Aided Design)
and CAM (Computer Aided Manufacturing) are typical usage areas for plotters.
REVIEW QUESTIONS:
Q.2What are main advantages and limitations of using peripheral devices with computer?
Q.3Write down the five input and five output devices and also explain working of these
devices?
Q.4 How data are stored in the computer? Explain the devices and memory which is used to
store the data in computer?
REFERENCES:
INTRODUCTION:
CONTENTS:
Special Purpose Computer: This aspect of computer is designed to perform one or specific
task. The program of this aspect of computer is in-built into the machine permanently. For
instance, special purpose computers are used for solving navigation problems in aircraft and
ships.
General Purpose Computer: These computers have the ability to handle a wide variety of
different programs and to solve many different problems.
3.5.2 MINICOMPUTER
Is a computer whose size, speed and capabilities lie between those of a mainframe
and PC.
The advent of more powerful chips now means that some 'Super Minis' and even PCs
linked in a network can run more powerfully than small mainframe.
FILE SERVER is more powerful than the average desktop PC and it is dedicated to providing
additional services for users of network PCs. A very large network is likely to use a 'Mainframe'
computer as its server and indeed mainframes are beginning to be referred to as 'enterprise
server'.
PORTABLES The original portable computers were heavy, weighing around five kilograms
and could only be run from the main electricity supply. Subsequent developments allow the true
portability.
a) Laptop is powered either from the electricity supply or using a rechargeable battery. It uses
31/2 disks and CD-ROMs, a liquid crystal or gas plasma screen and is fully compatible with
desktop PCs.
b) The Notebook is about the size of an A4 pad of paper. Some portables are now marketed as
'sub-notebooks'.
c) The Palm Or Handheld Computer, may or may not be compatible with the PCs. They range
from machines, which are little more relatively powerful processors with DOS compatibility and
communications features.
WORKSTATION was originally a computer used by one person, particularly for graphics and
design applications and was used primarily in engineering. It had a fast and powerful central
processor, a high - resolution monitor and large memory. This enabled complex designs to be
easily manipulated. These characteristics however are no longer unique to Workstations. High
performance personal computer can offer very similar services, so the distinction is a historical
one. Personal computers are generally fitted with some kind of graphics expansion card - a
circuit board containing the necessary electronics.
Super Computer is used to process very large amount of data quickly. They are particularly
useful for occasions where high volumes of calculations need to be performed.
SUMMARY:
In this lesson, we studied about the classification of computer.
How many types of computer used today.
We studied that Computer can be classified into three aspects: i.e based on
Representation of numbers, Degree of specialization and Types of application.
Other business computers are also used such as File server, Portables system and
Workstations.
REVIEW QUESTIONS:
Q.2What are the main categories of digital computer and where it is used? Explain.
REFERENCES:
Topic: Radix number system: Decimal, Binary, Octal, Hexadecimal numbers Lecture
and their inter-conversions; Representation of information inside the computers. required
INTRODUCTION-
CONTENTS-
Number system is used to represent information in quantitative form. Some of the common
number systems are binary, octal, decimal and hexadecimal.
A number system of base (also called radix) r is a system, which has r distinct symbols for r
digits. A string of these symbolic digits represents a number. To determine the value that a
number represents, we multiply the number by its place value that is an integer power of r
depending on the place it is located and then find the sum of weighted digits.
Decimal Numbers: Decimal number system has ten digits represented by 0,1,2,3,4,5,6,7,8 and
9. Any decimal number can be represented as a string of these digits and since there are ten
decimal digits, therefore, the base or radix of this system is 10.
Binary Numbers: In binary numbers we have two digits 0 and 1 and they can also be
represented, as a string of these two-digits called bits. The base of binary number system is 2.
Octal Numbers: An octal system has eight digits represented as 0,1,2,3,4,5,6,7. For finding
equivalent decimal number of an octal number one has to find the quantity of the octal number
which is again calculated as:
(23.4)8
= 2×8+3×1+4×1/8
=16+3+0.5
= (19.5)10
Hexadecimal Numbers: The hexadecimal system has 16 digits, which are represented as
0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F.
A number (F2)H is equivalent to
F×161 +2×160
= (15×16) + 2
= 240 + 2
= (242)10
4.2 CONVERSION
= 16+0+4+2+0 =22
The answer is read from bottom to top , same as with the binary case.
= 3840 + 64 + 12 + 0
= (3916)10
SUMMARY:
In this lesson, we studied about the radix number system.
Number system is used to represent information in quantitative form. Some of the
common number systems are binary, octal, decimal and hexadecimal.
Decimal Numbers: Decimal number system has ten digits represented by 0,1,2,3,4,5,6,7,8
and 9.
Binary Numbers: In binary numbers we have two digits 0 and 1 and they can also be
represented, as a string of these two-digits called bits.
Octal Numbers: An octal system has eight digits represented as 0,1,2,3,4,5,6,7.
Hexadecimal Numbers: The hexadecimal system has 16 digits, which are represented as
0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F.
REVIEW QUESTIONS:
Q.1What do you mean by Number System? Explain all type of number system.
REFERENCES:
INTRODUCTION:
CONTENTS:
The below diagram gives a graphical depiction of the interfaces between the operating system
and the computer component.
System crashes and instabilities - These can happen due to a software bug typically in
the operating system, although computer programs being run on the operating system can
make the system more unstable or may even crash the system by themselves. This varies
depending on the type of operating system. A system crash is the act of a system freezing
and becoming unresponsive which would cause the user to need to reboot.
Security flaws - Some software errors leave a door open for the system to be broken into
by unauthorized intruders. As these flaws are discovered, unauthorized intruders may try
to use these to gain illegal access to your system. Patching these flaws often will help
keep your computer system secure.
Sometimes errors in the operating system will cause the computer not to work correctly
with some peripheral devices such as printers.
Files
ls --- lists your files
ls -l --- lists your files in 'long format', which contains lots of useful information, e.g. the
exact size of the file, who owns the file and who has the right to look at it, and when it
was last modified.
ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do
not always want to see. There are many more options, for example to list files by size, by
date, recursively etc.
more filename --- shows the first part of a file, just as much as will fit on one screen.
Just hit the space bar to see more or q to quit. You can use /pattern to search for a
pattern.
emacs filename --- is an editor that lets you create and edit a file.
mv filename1 filename2 --- moves a file (i.e. gives it a different name, or moves it into
a different directory.
cp filename1 filename2 --- copies a file
rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for
confirmation before actually deleting anything. You can make this your default by
making an alias in your .cshrc file.
diff filename1 filename2 --- compares files, and shows where they differ .
wc filename --- tells you how many lines, words, and characters there are in a file.
chmod options filename --- lets you change the read, write, and execute permissions on
your files. The default is that only you can look at them and change them, but you may
sometimes want to change these permissions. For example, chmod o+r filename will
make the file readable for everyone, and chmod o-r filename will make it unreadable for
others again.
Windows XP is an operating system that was produced by Microsoft for use on personal
computers, including home and business desktops, laptops, and media centers. It was first
released in August 2001, and is the most popular version of Windows, based on installed user
base. The name "XP" is short for "eXPerience”. Windows XP was the successor to both
Windows 2000 and Windows Me, and was the first consumer-oriented operating system
produced by Microsoft to be built on the Windows NT kernel and architecture. Windows XP was
released for retail sale on October 25, 2001, and over 400 million copies were in use in January
2006, according to an estimate in that month by an IDC analyst. It was succeeded by Windows
Vista, which was released to volume license customers on November 8, 2006, and worldwide to
the general public on January 30, 2007. XP may continue to be available as these sources run
through their inventory or by purchasing Windows 7 Ultimate, Windows 7 Pro, Windows Vista
Ultimate or Windows Vista Business, and then downgrading to Windows XP. The most common
editions of the operating system were Windows XP Home Edition, which was targeted at home
users, and Windows XP Professional, which offered additional features such as support for
Windows Server domains and two physical processors, and was targeted at power users, business
and enterprise clients. Windows XP Media Center Edition has additional multimedia features
enhancing the ability to record and watch TV shows, view DVD movies, and listen to music.
Windows XP presented a significantly redesigned graphical user interface, a change Microsoft
promoted as more user-friendly than previous versions of Windows. Windows XP had also been
criticized by some users for security vulnerabilities, tight integration of applications such as
Internet Explorer 6 and Windows Media Player, and for aspects of its default user interface.
SUMMARY:
In this lesson, we studied about the concept of operating system. Its working, types and
functions of operating system is also discussed in this lesson.
The operating system provides for several other functions including:
System tools (programs) used to monitor computer performance, debug problems, or
maintain parts of the system.
A set of libraries or functions which programs may use to perform specific tasks
especially relating to interfacing with computer system components.
The operating system makes these interfacing functions along with its other functions
operate smoothly and these functions are mostly transparent to the user.
There are different types of operating systems such as window XP, UNIX, LINUX etc.
REVIEW QUESTIONS:
Q.2 Describe the two general roles of an operating system, and elaborate why these roles are
important.
REFERENCES:
Topic: Machine level language, Assembly level language and High Level- Lecture
Language required
INTRODUCTION:
The choice of which language to use depends on the type of computer the
program is to run on, what sort of program it is, and the expertise of the
programmer.
CONTENTS:
The term programming language usually refers to high-level languages, such as BASIC,
C, C++, COBOL, FORTRAN, Ada, and Pascal. Each language has a unique set of
keywords (words that it understands) and a special syntax for organizing program
instructions.
High-level programming languages, while simple compared to human languages, are
more complex than the languages the computer actually understands, called machine
languages.
Each different type of CPU has its own unique machine language.
Lying between machine languages and high-level languages are languages called
assembly languages. Assembly languages are similar to machine languages, but they are
much easier to program in because they allow a programmer to substitute names for
numbers. Machine languages consist of numbers only.
Regardless of what language we use, we eventually need to convert your program into
machine language so that the computer can understand it.
There are two ways to do this:
compile the program
interpret the program
The choice of which language to use depends on the type of computer the program is to run on,
what sort of program it is, and the expertise of the programmer.
1. Clarity of source code – the extent to which inherent language features support source code
that is readable and understandable and that clearly reflects the underlying logical structure of the
program.
4. Distributed system support – the extent to which inherent language features support the
construction of code to be distributed across multiple platforms on a network.
5. Maintainability – the extent to which inherent language features support the construction of
code that can be readily modified to satisfy new requirements or to correct deficiencies.
6. Mixed language support – the extent to which inherent language features support interfacing
to other languages.
8. Portability – the extent to which inherent language features support the transfer of a program
from one hardware and/or software platform to another.
9. Real-time support – the extent to which inherent language features support the construction
of real-time systems.
10. Reliability – the extent to which inherent language features support the construction of
components that can be expected to perform their intended functions in a satisfactory manner
throughout the expected lifetime of the product.
11. Reusability – the extent to which inherent language features support the adaptation of code
for use in another application.
12. Safety – the extent to which inherent language features support the construction of safety-
critical systems, yielding systems that are fault-tolerant, fail-safe, or robust in the face of
systemic failures.
13. Standardization – the extent to which the language definition has been formally
standardized (by recognized bodies such as ANSI and ISO) and the extent to which it can be
reasonably expected that this standard will be followed in a language translator.
14. Support for modern engineering methods – the extent to which inherent language features
support the expression of source code that enforces good software engineering principles.
Machine languages are the only languages understood by computers. While easily understood by
computers, machine languages are almost impossible for humans to use because they consist
entirely of numbers. Programmers, therefore, use either a high-level programming language or
an assembly language. An assembly language contains the same instructions as a machine
language, but the instructions and variables have names instead of being just numbers.
Machine languages consist entirely of numbers and are almost impossible for humans to read and
write. Assembly languages have the same structure and set of commands as machine languages,
but they enable a programmer to use names instead of numbers. Each type of CPU has its own
machine language and assembly language, so an assembly language program written for one type
of CPU won't run on another. In the early days of programming, all programs were written in
assembly language. Now, most programs are written in a high-level language such as
FORTRAN or C. Programmers still use assembly language when speed is essential or when they
need to perform an operation that isn't possible in a highlevel language.
Programs written in high-level languages are translated into assembly language or machine
language by a compiler. Assembly language programs are translated into machine language by a
program called an assembler. Every CPU has its own unique machine language. Programs must
be rewritten or recompiled, therefore, to run on different types of computers. A programming
language such as C, FORTRAN, or Pascal that enables a programmer to write programs that is
more or less independent of a particular type of computer. Such languages are considered high-
level because they are closer to human languages and further from machine languages. In
contrast, assembly languages are considered low-level because they are very close to machine
languages. The main advantage of high-level languages over low-level languages is that they are
easier to read, write, and maintain. Ultimately, programs written in a high-level language must be
translated into machine language by a compiler or interpreter. The first high-level programming
languages were designed in the 1950s. Now there are dozens of different languages, including
Ada, Algol, BASIC, COBOL, C, C++, FORTRAN, LISP, Pascal, and Prolog.
SUMMARY:
In this lesson, we studied about the introduction of programming languages and the
characteristics of the programming language.
Machine languages are the only languages understood by computers. While easily
understood by computers, machine languages are almost impossible for humans to use
because they consist entirely of numbers.
Assembly languages have the same structure and set of commands as machine languages,
but they enable a programmer to use names instead of numbers. Each type of CPU has its
own machine language and assembly language, so an assembly language program written
for one type of CPU won't run on another.
A programming language such as C, FORTRAN, or Pascal that enables a programmer to
write programs that are more or less independent of a particular type of computer. Such
languages are considered high-level because they are closer to human languages and
further from machine languages.
REVIEW QUESTIONS:
Q.1What is Relationship between assembly language and machine language and high level
language?
Q.2 Explain the difference between machine code, assembly language and high level
language.?
Q.3 What are the advantages of assembly language over high level language?
REFERENCES:
INTRODUCTION:
CONTENTS:
7.1 COMPILER
7.2 INTERPRETER
7.3 ASSEMBLER
7.4 DEBUGGERS
7.5 LOADER
7.6 LINKER
7.1 COMPILER
A program that translate source code into object code. The compiler derives its name
from the way it works, looking at the entire piece of source code and collecting and
reorganizing the instructions. Thus, a compiler differs from an interpreter, which analyzes
and executes each line of source code in succession, without looking at the entire
program. The advantage of interpreters is that they can execute a program immediately.
Compilers require some time before an executable program emerges. However, programs
produced by compilers run much faster than the same programs executed by an
interpreter.
Every high-level programming language (except strictly interpretive languages) comes
with a compiler. In effect, the compiler is the language, because it defines which
instructions are acceptable.
Because compilers translate source code into object code, which is unique for each type
of computer, many compilers are available for the same language. For example, there is a
FORTRAN compiler for PCs and another for Apple Macintosh computers. In addition,
the compiler industry is quite competitive, so there are actually many compilers for each
language on each type of computer. More than a dozen companies develop and sell C
compilers for the PC.
7.2 INTERPRETER
A program that executes instructions written in a high-level language. There are two
ways to run programs written in a high-level language. The most common is to compile
the program; the other method is to pass the program through an interpreter.
Both interpreters and compilers are available for most high-level languages.
However, BASIC and LISP are especially designed to be executed by an interpreter. In
addition, page description languages, such as PostScript, use an interpreter. Every
PostScript printer, for example, has a built-in interpreter that executes PostScript
instructions.
7.3 ASSEMBLER
A program that translate programs from assembly language to machine language. A tool
called an assembler translates assembly language into binary instructions. Assemblers
provide a friendlier representation than a computer’s 0s and 1s that simplifies writing and
reading programs. Symbolic names for operations and locations are one facet of this
representation. Another facet is programming facilities that increase a program’s clarity.
An assembler reads a single assembly language source file and produces an object file
containing machine instructions and bookkeeping information that helps combine several
object files into a program. Most programs consist of several files also called modules
that are written, compiled, and assembled independently. A program may also use
prewritten routines supplied in a program library.
7.4 DEBUGGERS
A debugger or debugging tool is a computer program that is used to test and debug
other programs (the "target" program).
7.5 LOADER
An operating system utility that copies programs from a storage device to main memory,
where they can be executed. In addition to copying a program into main memory, the loader
can also replace virtual addresses with physical addresses. Most loaders are transparent, i.e.,
you cannot directly execute them, but the operating system uses them when necessary.
Loading – brings the object program into memory for execution. A loader is a system
program that performs the loading function. Many loaders also support relocation and
linking. Some systems have a linker to perform the linking operations and a separate loader
to handle relocation and loading.
7.6 LINKER
Also called link editor and binder, a linker is a program that combines object modules to
form an executable program. Many programming languages allow you to write different
pieces of code, called modules, separately. This simplifies the programming task because
you can break a large program into small, more manageable pieces. Eventually, though, you
need to put all the modules together. This is the job of the linker.
In addition to combining modules, a linker also replaces symbolic addresses with real
addresses. Therefore, you may need to link a program even if it contains only one module.
Linking – combines two or more separate object programs and supplies the information
needed to allow references between them.
SUMMARY:
In this lesson we learnt about the different kind of translator which is used to translate
the any language program to equivalent machine language program.
Assembler is a translator program that translates an assembly language program into
its equivalent machine language program.
Compiler is a translator program that translates a high level language program into its
equivalent machine language program,
Linker is a software tool that takes multiple object program files of any software and
fits them together to assemble them into the program’s final executable form.
REVIEW QUESTIONS:
Q.3 What are the advantages and disadvantages of compiler, assembler and interpreter?
REFERENCES:
CONTENTS:
11.1 C-FUNDAMENTALS:
11.1.1 AN INTRODUCTION OF C
11.2 Types, Operators & Expressions
11.2.1 THE C CHARACTER SET
11.2.2 IDENTIFIERS AND KEYWORDS
11.2.3 CONSTANTS
11.2.4 DATA TYPES
11.2.5 VARIABLES AND ARRAYS
11.2.6 DECLARATIONS
11.2.7 PREPARING TO PROGRAM
11.2.8 OPERATORS
11.1.1An Introduction of C
C was created by Dennis Ritchie at the Bell Telephone Laboratories in 1972. Because C
is such a powerful and flexible language, its use quickly spread beyond Bell Labs. The American
National Standards Institute (ANSI) formed a committee in 1983 to establish a standard
definition of C, which became known as ANSI Standard C. With few exceptions, every modern
C compiler has the ability to adhere to this standard.
Why Use C?
C also uses some combinations of these characters such as \t, \n to represent special conditions
such as horizontal tab and newline respectively. These character combinations are called escape
sequences.
11.2.3 CONSTANTS
Constant in C refers to fixed values that do not change during the execution of a program. C
supports four types of constants. They are integer, character, string & floating-point constants.
As the name suggests integer & Floating point constants represent numbers. They are often
referred to collectively as numeric-type constants The numeric-type constants must follow the
following rules:
Commas and blank spaces cannot be included within the constant.
The constant can be preceded by a minus(-) sign if desired.
The value of a constant cannot exceed specified minimum and maximum bounds.
There are three types of integers, namely, decimal, octal and hexadecimal. A decimal integer
constant can consist of any combination of digits taken from the set 0 through 9, proceded by an
optional - or + sign. Various examples of decimal integer constants are:
123, – 345, 0, 5324, +62
An octal integer constant can consist of any combination of digits taken from the set 0 through 7,
with a leading 0. Some examples of octal integers are:
0, 01, 0456, 05555,
A hexadecimal integer constant must begin with either 0x or 0x. It can then be followed by any
combination of digits taken from the sets 0 through 9 and a through 7 (either upper or
lowercase). Note that the letters A through F represent the numbers 10 through 15 respectively.
Some examples of hexadecimal integers are:
0x2, 0xgf, 0xbc5, 0x
The largest integer value that can be stored is machine dependent. It is 32767 on 16-bit machines
and 2147483647 on 32-bit machines. It is also possible to store larger integer constants on these
machines by appending qualifiers such as U, L and UL to the constants. For
Example 56789U (unsigned integer), 876543217UL (unsigned long integer), 9765467L (Long
integer) Floating point constants is a base-10 number that contains either a decimal point or an
exponent (or both). Some of the valid floating point constants are
0. 1. 0.3. 1.555E+8 .121265e18
If an exponent is present, its effect is to shift the location of the decimal point to the right if the
exponent is positive or to the left if the exponent is negative. Floating point constants have a
much greater range than integer constants. Each floating point constant will typically occupy 2
words (8 bytes) of memory. Character constant is a single character, enclosed in apostrophes
(single quotation marks). Some of the valid character constants are
C compilers that are written for personal computers represent a word as 4 bytes.
Some of the differences are listed below between floating point numbers and integer.
1. Integer include only whole numbers, but floating point numbers can be either whole or
fractional.
2. Integers are always exact, whereas floating point numbers sometimes can lead to loss of
mathematical precision.
3. Floating point operations are slower in execution and often occupy more memory than
integer operations.
The following list contains some examples of legal and illegal C variable names:
Variable Name Legality
Percent Legal Legal
y2x5__fg7h Legal
annual_profit Legal but not advised
_1990_taxsavings#account Illegal:Contains the illegal character #
double Illegal: Is a C keyword
9winter Illegal: First character is a digit
C's numeric variables fall into the following two main categories:
1. Integer variables hold values that have no fractional part (that is, whole numbers only).
2. Integer variables come in two flavors: signed integer variables can hold positive or
negative values, whereas unsigned integer variables can hold only positive values.
3. Floating-point variables hold values that have a fractional part (that is, real numbers).
4. Within each of these categories are two or more specific variable types.
11.2.6 DECLARATIONS
A declaration associates a group of variables with a specific data type. In ‘C’ language all
variables must be declared before they appear in executable statements. A declaration has
following format to declare a variable
<data type> <variable name>;
Each array variable must be followed by a pair of square brackets containing a positive integer
which specifies the size of the array.
e.g
int x,y, z;
float sq_root, sq_root1;
char student_name[10];
Thus x,y,z are declared to be integer type variables, sq_root & sq_root1 are floating point
variables & student_name is character type array whose size is 10 elements. The programmer
can write above declarations in the following manner:
int x;
int y;
int Z;
float sq_root;
float sq_root1;
char student_name[10];
When creating a program in C (or for that matter, a computer program in any language), you
should follow a similar sequence of steps:
Compilation Process
The Program Development Cycle has its own steps. In the first step, you use an editor to create a
disk file containing your source code. In the second step, you compile the source code to create
an object file. In the third step, you link the compiled code to create an executable file. The
fourth step is to run the program to see whether it works as originally planned.
Source code is a series of statements or commands that are used to instruct the computer to
perform your desired tasks. As mentioned, the first step in the Program Development Cycle is to
enter source code into an editor. For example, here is a line of C source code:
printf("Hello, Mom!");
This statement instructs the computer to display the message Hello, Mom! on-screen. (For now,
don't worry about how this statement works.)
First C Program
1: #include <stdio.h>
2:
3: main()
4: {
5: printf("Hello, World!\n");
6: return 0;
7: }
11.2.8 OPERATORS
An operator is a symbol that instructs C to perform some operation, or action, on one or more
operands. An operand is something that an operator acts on. In C, all operands are expressions. C
operators fall into several categories:
The assignment operator
Mathematical operators
Relational operators
Logical operators
The increment and decrement operators can be used only with variables, not with constants. The
operation performed is to add one to or subtract one from the operand. In other words, the
statements
++x;
--y;
are the equivalent of these statements:
x = x + 1;
y = y - 1;
OR exp1 || exp2 True (1) if either exp1 or exp2 is true; false (0) only if both are false
NOT exp1 False (0) if exp1 is true; true (1) if exp1 is false.
Syntax :
scanf("control string",&var1,&var2,...&varn);
where, control string gives the format of data to the variables. The general form is
% w data type
where % - Conversion specification indicator
Example :
scanf("%d",&x);
scanf("%c",&sex);
scanf("%s",name);
To read a string variable we cannot use & in front of the string variable.
scanf("%4d",&a);
This statement is used to read an integer data of width 4. If the number exceeds 4 digits the
first 4 digits will be assigned to the variable a.
11.3.2 printf() : ( Output function )
Format Output
printf("%d",x); 2000 // Rule 1
printf("%3d",x); 2000 // Rule 2
printf("%5d",x) 2000 // Rule 4
printf("%-5d",x); 2000 // Rule 3
printf("%07d",x); 0002000 // Rule 5
printf("%4d",-x); -2000 // Rule 6
Printing real numbers :
The general format of control string to output a real number is
%w.p f or e
where w - width of output data(optional)
p - number of digits after decimal point
f - conversion character for floating point without exponent
e - conversion character for floating point with exponent
Example :
Assume x=123.4678;
Format Output
printf("%8.4f",x); 123.4678
printf("%f",x); 123.467800
printf("%e",x); 1.234678e+02
printf("%-8.2f",x); 123.47 (left justified)
Printing strings :
The general format of control string to output a string is
%[Link]
where w - width of the string(optional)
p - number of characters to be printed from the beginning
s - conversion character for string
Example :
Assume college="mspvl";
Format Output
printf("%s",college); mspvl
printf("%10s",college); mspvl
printf("%3s",college); mspvl
printf("%5.2s",college); ms
SUMMARY:
After this lesson, you should feel confident that selecting C as your programming
language is a wise choice.
C offers an unparalleled combination of power, popularity, and portability. These factors,
together with C's close relationship to the C++ object-oriented language as well as Java,
make C unbeatable.
This lesson explained the various steps involved in writing a C program--the process
known as program development. You should have a clear grasp of the edit-compile-link-
test cycle, as well as the tools to use for each step.
C offers different kind of input and output functions and every function have unique
characteristics.
This lesson explained the various steps involved in writing a C program—where
formatted input and output is used.
And how input and output function is necessary for programming.
REVIEW QUESTIONS:
Q.1 Why C is one of the most popular programming language?
Q.2 What is a variable and operators? List the all operators in explain.
REFERENCES:
Let us C by Yashwant Kanetkar.
Fundamental of Computer and programming in C by [Link].
Brian W. Kernighan and Dennis M. Ritchie
12.1 EXPRESSIONS
12.2 STATEMENTS
12.2.1 Statement Blocks
12.2.2 Selection Statements:
12.2.3 Switch Statement
12.3 LOOP CONCEPT IN C
12.3.1 The for loop
12.3.2 The while Loop
12.3.3 The do-while Loop
12.4 BREAK AND CONTINUE
12.1 EXPRESSIONS:
An expression is a combination of constants, variables, and operators that are used to denote
computations.
For instance, the following:
(2 + 3) * 10
is an expression that adds 2 and 3 first, and then multiplies the result of the addition by 10. (The
final result of the expression is 50.)
Similarly, the expression 10 * (4 + 5) yields 90. The 80/4 expression results in 20.
Here are some other examples of expressions:
Expression Description
6 An expression of a constant.
i An expression of a variable.
6+i An expression of a constant plus a variable.
exit(0) An expression of a function call.
Arithmetic Operators
We know, an expression can contain symbols such as +, *, and /. In the C language, these
symbols are called arithmetic operators.
C arithmetic operators.
Symbol Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder (or modulus)
12.2 STATEMENTS
In the C language, a statement is a complete instruction, ending with a semicolon. In many cases,
you can turn an expression into a statement by simply adding a semicolon at the end of the
expression.
For instance, the following
i = 1;
is a statement. You may have already figured out that the statement consists of an expression of i
= 1 and a semicolon (;).
Here are some other examples of statements:
i = (2 + 3) * 10;
i = 2 + 3 * 10;
j = 6 % 4;
k = i + j;
For example:
Display the leap Years between 1000 and 2000
#include <stdio.h>
#include <conio.h>
int main()
{
int loop;
printf("the leap year or not between 1000 to 2000\n");
for(loop=1000;loop<=2000;loop++)
{
if(loop%4==0)
printf("%d leap year\n",loop);
else
printf("%d not\n",loop);
}
getch();
}
For example:
#include <stdio.h>
int main(void)
{
int j;
j = -5;
// while loop
while(j <= 0)
{
printf("%d ", j);
j = j + 1;
}
return 0;
}
For example:
#include <stdio.h>
int main()
{
int j = -5; // initialization
do
{
printf("%d\n", j);
j = j + 1;
}
while(j <= 0); // condition
return 0;
}
References:
Programming in C by Dennis M Ritchie
Let us C by Yashwant Kanetkar.
Fundamental of Computer and programming in C by [Link]
GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-13
INTRODUCTION:
CONTENTS:
An array in C language is a collection of similar data-type, means an array can hold value of a
particular data type for which it has been declared. Arrays can be created from any of the C data-
types int, float, and char. So an integer array can only hold integer values and cannot hold values
other than integer. When we declare array, it allocates contiguous memory location for storing
values whereas 2 or 3 variables of same data-type can have random locations. So this is the most
important difference between a variable and an array.
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
} getch();
}
13.2 Functions
C also allows programmers to define their own functions for carrying out various individual
tasks. In this lesson we will cover the creation and utilization of such user defined functions.
For example:
#include <stdio.h>
main()
{
int x,y;
maxi(int, int); /*function declaration*/
printf(“Enter two integer values”);
scanf(“%d %d”’ &x,&y);
maxi(x,y); /*call to function*/
}
maxi(x,y) /*function definition*/
int x,y;
{
int z;
z=(x>=y)?x:y;
print(“\n\n Maximum value %d”,z);
return;
}
This ‘maxi’ function do not return any value to the calling program, it simply returns the control
to the calling programs, so if it is even not present, then also program will work efficiently.
Most C compilers permit the keyword void to appear as a type specifies when defining a function
that does not return anything. So the function definition will look like this if void is add to it
void maxi (int, int);
13.2.2 Passing Argument to a Function
Arguments can be passed to a function by two methods, they are called passing by value and
passing by reference. When a single value is passed to a function via an actual argument, the
value of the actual argument is copied into the function. Therefore, the value of the
corresponding formal argument can be altered within the function, but the value of the actual
argument within the calling routine will not change. This procedure for passing the value of an
argument to a function is known as passing by value.
Let us consider an example:
#include <stdio.h>
main()
{
int x=3;
printf(“\n x=%d(from main, before calling the
function”),x);
change(x);
printf(“\n\nx=%d(from main, after calling the
function)”,x);
}
change(x)
int x;
{
x=x+3;
printf(“\nx=%d(from the function, after being
modified)”,x);
return;
}
The original value of x (i.e. x=3) is displayed when main begins execution. This value is then
passed to the function change, where it is sum up by 3 and the new value displayed. This new
value is the altered value of the formal argument that is displayed within the function. Finally,
the value of x within main is again displayed, after control is transferred back to main from
change.
x=3 (from main, before calling the function)
x=6 (from the function, after being modified)
x=3 (from main, after calling the function)
Passing an argument by value allows a single-valued actual argument to be written as an
expression rather than being restricted to a single variable. But it prevents information from
being transferred back to the calling portion of the program via arguments. Thus, passing by
value is restricted to a one-way transfer of information. Arrays are passed differently than single-
valued entities. If an array name is specified as an actual argument, the individual array elements
are not copied to the function. Instead the location of the array is passed to the function. If an
element of the array is accessed within the function, the access will refer to the location of that
array element relative to the location of the first element. Thus, any alteration to an array element
within the function will carry over to the calling routine.
The names of the arguments within the function declaration need not be declared elsewhere in
the program, since these are “dummy” argument names recognized only within the declaration.
“C” language also permits the useful feature of ‘Recursion’.
Recursion is a process by which a function calls itself repeatedly, until some
specified condition has been satisfied. The process is used for repetitive computations in which
each action is stated in terms of a precious result. In order to solve a problem recursively, two
conditions must be satisfied. The problem must be written in a recursive form, and the problem
statement must include a stopping condition. The best example of recursion is calculation of
factorial of a integer quantity, in which the same procedure is repeating itself.
Let us consider the example of factorial:
#include <stdio.h>
main()
{
int number;
long int fact(int number);
printf(“Enter number”);
scanf(“%d”, & number);
printf(“Factorial of number is % d\n”, fact(number));
}
long int fact(int number)
{
if(number <=1)
return(1);
else
return(number *fact(number-1));
}
The point to be noted here is that the function ‘fact’ calls itself recursively, with an actual
argument (n-1) that decrease in value for each successive call. The recursive calls terminate the
value of the actual argument becomes equal to 1. When a recursive program is executed, the
recursive function calls are not executed immediately. Instead of it, they are placed on a stack
until the condition that terminates the recursion is encountered. The function calls are then
executed in reverse order, as they are popped off the stack. The use of recursion is not
necessarily the best way to approach a problem, even though the problem definition may be
recursive in nature.
Summary
In this lesson we've learned the following:
What is array and types of array.
Array is a collection of similar type of data known as homogeneous data.
How array is implement in the c program.
Array elements are stored in contiguous memory locations and so they can be accessed.
Compiler doesn’t perform bounds checking on an array.
An array is similar to an ordinary variable except that it can store multiple elements of
similar type.
Function declaration specifies the return type of the function and the type of parameters it
accepts
Function definition defines the body of the function
Adding too many functions and calling them frequently may shown the program
execution.
A function can be called either by value or by reference.
Recursion is difficult to understand, but in some cases offers a better solution then loops.
Review Questions
Ques 1 What is an array? Discuss all type of array with example?
Sol: See page
Ques 2 Explain functions with the suitable example. (KUK)
Sol: See page
Ques 3 How you can pass the argument to a function? (KUK)
Sol: See page
Ques 4. Write a function in C to swap the values of two variables. (KUK 2013)
Sol: See page
References
Programming in C by Dennis M Ritchie
Let us C by Yashwant Kanetkar.
Fundamental of Computer and programming in C by [Link].
GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-14
INTRODUCTION:
Variables declared in a function are called local variables. The term local
means that the variables are private to that particular function and are distinct
from other variables of the same name declared elsewhere in the program.
In the C programming language, an external variable is a variable 1
defined outside any function block. An external variable must be defined,
exactly once, outside of any function; this sets aside storage for it. The variable
must also be declared in each function that wants to access it; this states the
type of the variable.
An external variable can be accessed by all the functions in all the
modules of a program. It is a global variable. For a function to be able to use
the variable, a declaration or the definition of the external variable must lie
before the function definition in the source code.
CONTENTS:
To use a variable in a function, you must declare it in the function header or the
function body (except for global variables. In order for a function to obtain a value from the
calling program, the value must be passed as an argument. In order for a calling program to
obtain a value from a function, the value must be explicitly returned from the function.
An external variable must be defined, exactly once, outside of any function; this sets aside
storage for it. The variable must also be declared in each function that wants to access it; this
states the type of the variable. The declaration may be an explicit extern statement or may be
implicit from context. ... You should note that we are using the words definition and declaration
carefully when we refer to external variables in this section. Definition refers to the place where
the variable is created or assigned storage; declaration refers to places where the nature of the
variable is stated but no storage is allocated.
For Example:
#include <stdio.h>
void print_count(void)
int main(void)
{
for (i = 10; i > 0; --i)
print_count();
return 0;
The static keyword (static and extern are mutually exclusive), applied to the definition of an
external variable, changes this a bit: the variable can only be accessed by the functions in the
same module where it was defined. But it is possible for a function in the same module to pass a
reference (pointer) of the variable to another function in another module. In this case, even
though the function is in another module, it can read and modify the contents of the variable—it
just cannot refer to it by name.
It is also possible to use the static keyword on the definition of a local variable. Without the
static keyword, the variable is automatically allocated when the function is called and released
when the function exits (thus the name "automatic variable"). Its value is not retained between
function calls. With the static keyword, the variable is allocated when the program starts and
released when the program ends. Its value is not lost between function calls. The variable is still
local, since it can only be accessed by name inside the function that defined it. But a reference
(pointer) to it can be passed to another function, allowing it to read and modify the contents of
the variable (again without referring to it by name).
External variables are allocated and initialized when the program starts, and the memory is only
released when the program ends. Their lifetime is the same as the program's.
If the initialization is not done explicitly, external (static or not) and local static variables are
initialized to zero. Local automatic variables are uninitialized, i.e. contain "trash" values.
The static keyword applied to a function definition prevents the function from being called by
name from outside its module (it remains possible to pass a function pointer out of the module
and use that to invoke the function).
Example
File-1:
int GlobalVariable; // implicit definition
void SomeFunction(); // function prototype (declaration)
int main() {
GlobalVariable = 1;
SomeFunction();
return 0;
}
File-2:
extern int GlobalVariable; // explicit declaration
void SomeFunction() { // function header (definition)
++GlobalVariable;
}
In this example, the variable GlobalVariable is defined in File 1. In order to utilize the same
variable in File 2, it must be declared. Regardless of the number of files, a global variable is only
defined once, however, it must be declared in any file outside of the one containing the
definition.
If the program is in several source files, and a variable is defined in file1 and used in file2 and
file3, then extern declarations are needed in file2 and file3 to connect the occurrences of the
variable. The usual practice is to collect extern declarations of variables and functions in a
separate file, historically called a header, that is included by #include at the front of each source
file. The suffix .h is conventional for header names.
Summary
Variables declared in a function are called local variables. The term local means that the
variables are private to that particular function and are distinct from other variables of the same
name declared elsewhere in the program. A local variable is declared like any other variable,
using the same variable types and rules for names. Local variables can also be initialized when
they are declared.
In the C programming language, an external variable is a variable defined outside
any function block. On the other hand, a local (automatic) variable is a variable defined inside a
function block. When a variable is defined, the compiler allocates memory for that variable and
possibly also initializes its contents to some value. When a variable is declared, the compiler
requires that the variable be defined elsewhere.
An external variable can be accessed by all the functions in all the modules of a
program. It is a global variable. For a function to be able to use the variable, a declaration or the
definition of the external variable must lie before the function definition in the source code. Or
there must be a declaration of the variable, with the keyword extern, inside the function.
Review Questions:
Q.1 Explain the local and external variables with suitable example. (KUK)
Sol: See page
Q.2 What is the scope of variable in the C programming? (KUK)
Sol: See page
References:
Programming in C by Dennis M Ritchie.
Let us C by Yashwant Kanetkar.
Fundamental of Computer and programming in C by [Link].
GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-15
Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]
Course Code: CSE 101 E Subject: FCPC Unit: IV
Topic: Strings: strings literals, string variables, I/O of strings Lecture
required
INTRODUCTION:
An Array of character is called a string. String in C are handled differently than
most other language. String in simplest term is a one dimensional array of
characters terminated by a null character ( '\n' ).
Strings are used to store string constant. String constant in C is a
series of characters enclosed within a pair of double quotes. String in C is
equivalent to a real world sentence made by combination of various characters
2
including spaces.
String literals can be enclosed in matching single quotes ( ') or
double quotes ("). The backslash (\) character is used to escape characters that
otherwise have a special meaning, such as newline, backslash itself, or the
quote character. String literals may optionally be prefixed with a letter "r" or
"R"; such strings are called raw strings
CONTENTS:
15.1 Strings
15.1.1 The General Form Of Declaration Of String Variable
15.1.2 General Form Of Declaration Of Array Of String
15.2 String Literals
15.3 String Variables
UNIT-IV LESSON-15
15.1 Strings
An Array of character is called a string. String in C are handled differently than most other
language. String in simplest term is a one dimensional array of characters terminated by a null
character ( '\n' ). For safe use size of this string should be one greater than the maximum size
string going to be stored in this character array. String in C is equivalent to a real world sentence
made by combination of various characters including spaces.
String literals can be enclosed in matching single quotes ( ') or double quotes (").
The backslash (\) character is used to escape characters that otherwise have a special meaning,
such as newline, backslash itself, or the quote character. String literals may optionally be
prefixed with a letter " r" or "R"; such strings are called raw strings and use different rules for
interpreting backslash escape sequences. A prefix of " u" or "U" makes the string a Unicode
string. Unicode strings use the Unicode character set as defined by the Unicode Consortium and
ISO 10646. Some additional escape sequences, described below, are available in Unicode
strings. The two prefix characters may be combined; in this case, " u" must appear before "r". In
triple-quoted strings, unescaped newlines and quotes are allowed (and are retained), except that
three unescaped quotes in a row terminate the string. (A ``quote'' is the character used to open the
string, i.e. either ' or ".)
Unless an "r" or "R" prefix is present, escape sequences in strings are interpreted according to
rules similar to those used by Standard C. The recognized escape sequences are:
(1) Individual code units which form parts of a surrogate pair can be encoded using this
escape sequence.
(2) Any Unicode character can be encoded this way, but characters outside the Basic
Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is compiled
to use 16-bit code units (the default). Individual code units which form parts of a
surrogate pair can be encoded using this escape sequence.
(3) As in Standard C, up to three octal digits are accepted.
(4) Unlike in Standard C, exactly two hex digits are required.
(5) In a string literal, hexadecimal and octal escapes denote the byte with the given value; it
is not necessary that the byte encodes a character in the source character set. In a Unicode
literal, these escapes denote a Unicode character with the given value.
Like other variables, we must declare chars before using them, and we can initialize them at the
time of declaration.
Here are some examples:
char a, b, c; /* Declare three uninitialized char variables */
char code = `x'; /* Declare the char variable named code */
/* and store the character x there */
code = `!'; /* Store ! in the variable named code */
To create literal character constants, we enclose a single character in single quotation marks. The
compiler automatically translates literal character constants into the corresponding ASCII codes,
and the numeric code value is assigned to the variable.
We can create symbolic character constants by using either the #define directive or the const
keyword:
#define EX `x'
char code = EX; /* Sets code equal to `x' */
const char A = `Z';
Summary
An Array of character is called a string. String in C are handled differently than most other
language. String in simplest term is a one dimensional array of characters terminated by a null
character ( '\n' ). Strings are used to store string constant. String constant in C is a series of
characters enclosed within a pair of double quotes.
Example of a string constant - “FUNDAMENTAL OF C !!!!! ".
Strings like other arrays can be initialized in both normal and unsized way.
The general form of string initalization is -
char name [size] = "value";
The general form of unsized string initalization is -
char name [ ] = "value";
String literals can be enclosed in matching single quotes (') or double quotes ("). The backslash
(\) character is used to escape characters that otherwise have a special meaning, such as newline,
backslash itself, or the quote character. String literals may optionally be prefixed with a letter " r"
or "R"; such strings are called raw strings and use different rules for interpreting backslash
escape sequences.
Review Questions
Ques .1 How string is useful for C language? Explain with the suitable example. (KUK)
Sol: See page
Ques .2 How string is declared and initialized in C program? Write down the syntax of string
initialization and declaration.
Sol: See page
References
Programming in C by Dennis M Ritchie.
Let us C by Yashwant Kanetkar.
Fundamental of Computer and programming in C by [Link].
GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-16
Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]
Course Code: CSE 101 E Subject: FCPC Unit: IV
Lecture
Topic: Arrays of strings, applications required
INTRODUCTION:
A string is an array of characters; so, an array of strings is an array of arrays of
characters. Of course, the maximum size is the same for all the strings stored in
a two dimensional array."Storing Similar Data Items," a string is a character
array terminated by a null character (\0). A character array can be declared and
initialized like this:
char arr_str[6] = {`H', `e', `l', `l', `o', `!'};
2
The compiler can automatically append a null character (\0) to the end of the
array, and treat the character array as a character string.
We can also declare a char pointer and then initialize the pointer with a string
constant. The following statement is an example:
char *ptr_str = "I teach myself C.";
In C, there are several functions we can use to deal with string reading or
writing. To copy a string from one array to another, we can copy each item of
the first array to the corresponding element in the second array, or we can
simply call the C function strcpy().
CONTENTS:
16.1 Arrays of Strings
16.1.1 Input/ Output Of String:
16.1.2 Initializing Strings
char names[MAX][SIZE];
Since names is an array of character arrays, names[i] is the character array, i.e. it points to the
character array or string, and may be used as a string of maximum size SIZE - 1. As usual with
strings, a NULL character must terminate each character string in the array an array of strings as
a table of strings, where each row of the table is a string as seen in Figure:
Figure 16.1
16.1.1 Input/ Output of string:
"Storing Similar Data Items," a string is a character array terminated by a null character (\0). For
instance, a character array, array_ch, declared in the following statement, is considered a
character string:
char array_ch[7] = {`H', `e', `l', `l', `o', `!', `\0'};
In C, the null character can be used to mark the end of a string, or to return logical FALSE. C
treats \0 as one character. Each character in a string takes only 1 byte. A series of characters
enclosed in double quotes ("") is called a string constant. The C compiler can automatically add a
null character (\0) at the end of a string constant to indicate the end of the string. For example,
the character string "A character string." is considered a string constant; so is "Hello!
16.1.2 Initializing Strings
A character array can be declared and initialized like this:
char arr_str[6] = {`H', `e', `l', `l', `o', `!'};
Here the array arr_str is treated as a character array. However, if we add a null character (\0) into
the array, we can have the following statement:
char arr_str[7] = {`H', `e', `l', `l', `o', `!', `\0'};
Here the array arr_str is expanded to hold seven elements; the last element contains a null
character. Now, the character array arr_str is considered a character string because of the null
character that is appended to the array. We can also initialize a character array with a string
constant. For example, the following statement initializes a character array, str, with a string
constant, "Hello!":
char str[7] = "Hello!";
The compiler can automatically append a null character (\0) to the end of the array, and treat the
character array as a character string. Note that the size of the array is specified to hold up to
seven elements, although the string constant has only six characters enclosed in double quotes.
The extra space is reserved for the null character that the compiler will add later.
For instance, the following statement
char str[] = "I like C.";
initializes an unsized character array, str, with a string constant. Later, when the compiler sees
the statement, it will figure out the total memory space needed to hold the string constant plus an
extra null character added by the compiler itself.
We can also declare a char pointer and then initialize the pointer with a string constant. The
following statement is an example:
char *ptr_str = "I teach myself C.";
Summary
In this lesson we've learned the following:
A string is a character array with a null character as the terminator at the last element.
A string constant is a series of characters enclosed by double quotes.
The C compiler automatically appends a null character to the array that has been
initialized by a string constant.
The strlen() function can be used to measure the length of a string. This function does not
count the null character in the last element.
We can copy a string from one array to another by calling the C function strcpy().
The gets() function can be used to read a series of characters. This function stops reading
when the newline character or end-of-file (EOF) is encountered. A null character is
attached to the array that stores the characters automatically after the reading.
The puts() function sends all characters, except the null character, in a string to the stdout,
and appends a newline character to the output.
We can read different data items with the scanf() function by using various format
specifiers.
Review Question
Ques.1 Define array of string with a suitable example. (KUK)
Sol: See page
Ques.2 Write down the applications of array of string. How you can initialize in C program?
Sol: See Page
Ques.3 How I/O of strings is done in C? Give examples. (KUK)
Sol: See page
Ques.4 Discuss the use of following functions:
Strcmp, strcpy, strlen
Sol: See page
References
Let us C by Yashavant Kanetkar.
Programming in C by Dennis M Ritchie.
Fundamental of Computer and programming in C by [Link].
INTRODUCTION:
In C, a structure collects different data items in such a way that they can be
referenced as a single unit. After declaring a structure, we can define the
structure variables. struct is used to start a structure declaration.
Data items in a structure are called fields or members of the structure.
The C language allows you to pass an entire structure to a function. In
addition, a function can return a structure back to its caller. Unions like
structure contain members whose individual data types may differ from one 2
another. Unions are used to observe memory. They are useful for application
involving multiple members.
An enumeration consists of a set of named integer constants. An
enumeration type declaration gives the name of the (optional) enumeration tag
and defines the set of named integer identifiers. Variables of enum type can be
used in indexing expressions and as operands of all arithmetic and relational
operators.
CONTENTS:
17.1 What Is A Structure?
17.1.1 Declaring Structures
17.1.2 Defining Structure Variables
Variables of enum type can be used in indexing expressions and as operands of all arithmetic and
relational operators. Enumerations provide an alternative to the #define preprocessor directive
with the advantages that the values can be generated for you and obey normal scoping rules.
In ANSI C, the expressions that define the value of an enumerator constant always have int type;
thus, the storage associated with an enumeration variable is the storage required for a single int
value. An enumeration constant or a value of enumerated type can be used anywhere the C
language permits an integer expression.
enum identifier
The optional identifier names the enumeration type defined by enumerator-list. This identifier is
often called the "tag" of the enumeration specified by the list. A type specifier of the form
declares identifier to be the tag of the enumeration specified by the enumerator-list nonterminal.
The enumerator-list defines the "enumerator content." The enumerator-list is described in detail
below.
One more thing we can do with a structure is initialize a structure variable while declaring it. As
for array initializations, the initializer consists of a comma-separated list of values enclosed in
braces {}:
Summary
In this lesson we've learned the following:
A group of variables of different types with a data type called a structure.
The data items in a structure are called fields or members of the structure.
The struct keyword is used to start a structure declaration or a structure variable
definition.
The dot operator (.) is used to separate a structure name and a member name in
referencing the structure member.
A structure can be passed to a function, and a function can return a structure back to the
caller.
Passing a function with a pointer that points to a structure is more efficient than passing
the function with the entire structure.
Arrays of structures are permitted in C.
Review Questions
Ques.1 What is a struct in C? How is a struct declared n C?
Sol: See page
Ques.2 What is union in C ? How is a union declared in C? (KUK)
Sol: See page
Ques.3 What is the difference between structures and union in C? (KUK)
Sol: See page
Ques.4 What is union? How do we declare unions in C? How do we access the elements of
unions in C? (KUK)
Sol: See page
Ques.5 Write a short note on Enumerated Data type with example. (KUK)
Sol: See page
References
Let us C by Yashavant Kanetkar.
Programming in C by Dennis M Ritchie.
Fundamental of Computer and programming in C by [Link].
GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-18
Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]
Course Code: CSE 101 E Subject: FCPC Unit: IV
Lecture
Topic: Structured types, nested array structures. required
INTRODUCTION:
A struct declaration consists of a list of fields, each of which can have any
type. The total storage required for a struct object is the sum of the storage
requirements of all the fields, plus any internal padding. Structures can be used
as structures within structures. It is also called as 'nesting of structures'.
CONTENTS:
1
18.1 Struct
18.2 Structures
18.3 Structured Data Types
UNIT-IV LESSON-18
18.1 Struct
A struct in C programming language is a structured (record) type that aggregates a fixed set of
labelled objects, possibly of different types, into a single object. A struct declaration consists of a
list of fields, each of which can have any type. The total storage required for a struct object is the
sum of the storage requirements of all the fields, plus any internal padding.
For example
struct account {
int account_number;
char *first_name;
char *last_name;
float balance;
};
defines a type, referred to as struct account. To create a new variable of this type, we can write
struct account s;
which has an integer component, accessed by s.account_number, and a floating-point component,
accessed by [Link], as well as the first_name and last_name components. The structure s contains
all four values, and all four fields may be changed independently.
18.2 Structures
The syntax for directly declaring a variable as a structure is the same as we would use to define a
structured data type using the TYPES statement:
DATA BEGIN OF struc.
...
{DATA comp ...} | {INCLUDE {TYPE|STRUCTURE} ...}.
..
DATA END OF struc.
The individual components of a structure are addressed in the program with the structure
component selector (-) between the structure name and component name as follows: struc_comp.
For more information, refer to the keyword documentation.
DATA: BEGIN OF address,
name TYPE c LENGTH 20,
street TYPE c LENGTH 20,
number TYPE p,
postcode TYPE n LENGTH 5,
city TYPE c LENGTH 20,
END OF address.
This example defines a structure called address. The components can be addressed using
address-name, address-street, and so on.
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Example :
struct stud_Res
{
int rno;
char nm[50];
char std[10];
struct stud_subj
{
char subjnm[30];
int marks;
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a structure with
two members. Structure stud_Res is called as 'outer structure' while stud_subj is called as 'inner
structure.' The members which are inside the inner structure can be accessed as follow :
[Link]
[Link]
Program :
/* Program to demonstrate nested structures.*/
#include <stdio.h>
#include <conio.h>
struct stud_Res
{
int rno;
char std[10];
struct stud_Marks
{
char subj_nm[30];
int subj_mark;
}marks;
}result;
void main()
{
clrscr();
printf("\n\t Enter Roll Number : ");
scanf("%d",&[Link]);
printf("\n\t Enter Standard : ");
scanf("%s",[Link]);
printf("\n\t Enter Subject Code : ");
scanf("%s",[Link].subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&[Link].subj_mark);
printf("\n\n\t Roll Number : %d",[Link]);
printf("\n\n\t Standard : %s",[Link]);
printf("\nSubject Code : %s",[Link].subj_nm);
printf("\n\n\t Marks : %d",[Link].subj_mark);
getch();
}
Summary
In this lesson we've learned the following:
We can group variables of different types with a data type called a structure.
The data items in a structure are called fields or members of the structure.
The struct keyword is used to start a structure declaration or a structure variable
definition.
A structure can be passed to a function, and a function can return a structure back to the
caller.
The structure of Nested structures in C, Implementation of Nested structure in C and the
Structured Data Types, Structures within Structures (Nested Structures) also discussed in
this lesson.
Review Question
Ques.1 What are the nested structure in C? Explain with suitable example. (KUK)
Sol: See page
Ques.2 Explain the structure data types?
Sol: See page
Ques.3 Write a program to compute the salary of an employee using structures. (KUK)
Sol: See page
References
Let us C by Yashawant Kanetkar.
Programming in C by Dennis M Ritchie.
Fundamental of Computer and programming in C by [Link].
GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-19
Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]
Course Code: CSE 101 E Subject: FCPC Unit: IV
Lecture
Topic: Enumeration as integers, tags and types, required
INTRODUCTION:
An enumeration consists of a set of named integer constants. An enumeration
type declaration gives the name of the (optional) enumeration tag and defines
the set of named integer. A variable with enumeration type stores one of the
values of the enumeration set defined by that type.
CONTENTS:
19.1 C Enumeration Declarations 2
19.2 Tags In C
19.2.1 Expression Tags
19.2.2 Flow Control Tags
19.2.3 Conditional Tags
19.2.4 Iterator Tags
19.2.5 Url Tags
19.3 Data Types In C
19.3.1 Primary Data Types:
19.3.2 Secondary Data Types
19.4 The Standard Library Functions
UNIT-IV LESSON-19
Variables of enum type can be used in indexing expressions and as operands of all arithmetic and
relational operators. Enumerations provide an alternative to the #define preprocessor directive
with the advantages that the values can be generated for you and obey normal scoping rules.
In ANSI C, the expressions that define the value of an enumerator constant always have int type;
thus, the storage associated with an enumeration variable is the storage required for a single int
value. An enumeration constant or a value of enumerated type can be used anywhere the C
language permits an integer expression.
Syntax:
num-specifier:
enum identifier opt { enumerator-list }
enum identifier
The optional identifier names the enumeration type defined by enumerator-list. This identifier is
often called the "tag" of the enumeration specified by the list. A type specifier of the form
enum identifier { enumerator-list }
declares identifier to be the tag of the enumeration specified by the enumerator-list nonterminal.
The enumerator-list defines the "enumerator content." The enumerator-list is described in detail
below.
Example:
19.2 Tags in C
Figure 19.1 Tags in C
19.2.1 Expression Tags
The out tag evaluates an expression and outputs the result of the evaluation to the current
JspWriter object. It is the equivalent of the JSP syntax <%= expression %>. For example,
[Link] displays the number of items in a shopping cart as follows:
<c:out value="${[Link]}"/>
The set tag sets the value of an attribute in any of the JSP scopes (page, request, session,
application). If the attribute does not already exist, it is created.
The out tag evaluates an expression and outputs the result of the evaluation to the current
JspWriter object. It is the equivalent of the JSP syntax <%= expression %>. For example,
[Link] displays the number of items in a shopping cart as follows:
<c:out value="${[Link]}"/>
The set tag sets the value of an attribute in any of the JSP scopes (page, request, session,
application). If the attribute does not already exist, it is created.
The catch tag provides a complement to the JSP error page mechanism. It allows page authors to
recover gracefully from error conditions that they can control. Actions that are of central
importance to a page should not be encapsulated in a catch, so their exceptions will propagate to
an error page. Actions with secondary importance to the page should be wrapped in a catch, so
they never cause the error page mechanism to be invoked.
19.2.2 Flow Control Tags
To execute flow control logic, a page author must generally resort to using scriptlets. For
example, the following scriptlet is used to iterate through a shopping cart:
<%
Iterator i = [Link]().iterator();
while ([Link]()) {
ShoppingCartItem item =
(ShoppingCartItem)[Link]();
...
%>
<tr>
<td align="right" bgcolor="#ffffff">
<%=[Link]()%>
</td>
...
<%
}
%>
19.2.3 Conditional Tags
The if tag allows the conditional execution of its body according to value of a test attribute. The
following example from [Link] tests whether the request parameter Add is empty.
key - the key under which the item is stored in the underlying Map
value - the value that corresponds to the key
C has different data types for different types of data and can be broadly classified as:
1. Primary Data Types
2. Secondary Data Types
Syntax:
char <variable name>;
char ch = ‘a’;
Example: a, b, g, S, j.
Void Type
The void type has no values therefore we cannot declare it as variable as we did in case of
integer and float. The void data type is usually used with function to specify its type.
19.3.2 Secondary Data Types
Arrays
An array in C language is a collection of similar data-type, means an array can hold value of a
particular data type for which it has been declared. Arrays can be created from any of the C data-
types int, float, and char. So an integer array can only hold integer values and cannot hold values
other than integer.
Types of Arrays
One Dimensional Array
Two Dimensional Array
Multi Dimensional Array
Declaration Of Arrays
Structures
We used variable in our C program to store value but one variable can store only single piece
information (an integer can hold only one integer value) and to store similar type of values we
had to declare many variables. To overcome this problem we used array which can hold numbers
of similar data type. But array too have some limitations, like in our real world application we
deal with set of dissimilar data types and single array cannot store dissimilar data.
A list of the most common libraries and a brief description of the most useful functions they
contain follows:
Summary
In this lesson we've learned the following:
Different tags used to create form fields, what attributes are required by each tag, and
which attributes are optional.
Enumerations provide an alternative to the #define preprocessor directive with the
advantages that the values can be generated for you and obey normal scoping rules.
Tag descriptions in this manual use certain tag prefixes by convention; however, you can
designate any desired prefix in your taglib directives.
C has different data types for different types of data and can be broadly classified as:
Primary Data Types and Secondary Data Types.
Review Question
Ques.1 Why we use the tags and types in C language?
Sol: See page
Ques.2 What are the standard input/ output library functions? (KUK)
Sol: See page
References
Let us C by Yashavant Kanetkar.
Programming in C by Dennis M Ritchie.
Fundamental of Computer and programming in C by [Link].
GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-20
Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]
Course Code: CSE 101 E Subject: FCPC Unit: IV
Lecture
Topic: Streams, file operations, formatted I/O, required
character I/O, Line I/O, block, string I/O
INTRODUCTION:
Streams are a portable way of reading and writing data. They provide a flexible
and efficient means of I/O. A Stream is a file or a physical device (e.g. printer
or monitor) which is manipulated with a pointer to the stream.
C is not equipped with read and write statements. Instead, a
set of functions is provided for formatted I/O.
CONTENTS: 3
20.1 Streams
20.1.1 Basic I/O
20.2 File Operations
20.3 Formatted I/O
20.3.1 Formatted I/O Operations In C
20.4 Character I/O
20.4.1 Character Input
20.4.2 Character Output
20.5 String Input/Output
20.5.1 String Input
20.5.2 String Output
UNIT-IV LESSON-20
20.1 Streams
Streams are a portable way of reading and writing data. They provide a flexible and efficient
means of I/O. A Stream is a file or a physical device (e.g. printer or monitor) which is
manipulated with a pointer to the stream. There exists an internal C data structure, FILE, which
represents all streams and is defined in stdio.h. We simply need to refer to the FILE structure in
C programs when performing I/O with streams. We just need to declare a variable or pointer of
this type in our programs. We must open a stream before doing any I/O, then access it and then
close it.
Stream I/O is BUFFERED: That is to say a fixed ``chunk'' is read from or written to a file via
some temporary storage area (the buffer).
Figure 20.1
int ch;
ch = getchar( );
(void) putchar((char) ch);
20.2 File Operations
These function prototypes are in <stdio.h>: the program must #include <stdio.h>. The value EOF
(indicates end-of-file) is defined in <stdio.h>. Its value is usually -1, but this should not be relied
upon. The data type FILE is a struct type defined in <stdio.h>. A stream is a pointer-to-FILE,
and comprises a buffer plus a file. The streams stdin, stdout and stderr are automatically opened
when a program including <stdio.h> is run. Unless redirected, stdin is connected to the keyboard,
stdout and stderr to the screen. When program execution ends, all open streams are automatically
closed.
FILE *fopen(const char *filename, const char *mode);
This opens the file filename. The mode mode can be "r" for reading, "w" for writing, or "a" for
appending. It returns a stream, or NULL if the file cannot be opened.
printf
The function is defined as follows:
int printf(char *format, arg list ...) --
prints to stdout the list of arguments according specified format string. Returns number of
characters printed.
The format string has 2 types of object:
ordinary characters -- these are copied to output.
conversion specifications -- denoted by %
scanf
This function is defined as follows:
int scanf(char *format, args....) -- reads from stdin and puts input in address of variables
specified in args list. Returns number of chars read. Format control string similar to printf
scanf(``%d'',&i);
We can just give the name of an array or string to scanf since this corresponds to the start address
of the array/string.
char string[80];
scanf(``%s'',string);
#include <stdio.h>
/* character input */
int fgetc(FILE *stream);
int getc(FILE *stream);
int getchar(void);
int ungetc(int c, FILE *stream);
/* character output */
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
/* string input */
char *fgets(char *s, int n, FILE *stream);
char *gets(char *s);
/* string output */
int fputs(const char *s, FILE *stream);
int puts(const char *s);
Their descriptions are as follows.
There is also the supporting ungetc routine, which is used to push back a character on to a
stream, causing it to become the next character to be read. This is not an output operation and
can never cause the external contents of a file to be changed. A fflush, fseek, or rewind operation
on the stream between the pushback and the read will cause the pushback to be forgotten. Only
one character of pushback is guaranteed, and attempts to pushback EOF are ignored. In every
case, pushing back a number of characters then reading or discarding them leaves the file
position indicator unchanged. The file position indicator is decremented by every successful call
to ungetc for a binary stream, but unspecified for a text stream, or a binary stream which is
positioned at the beginning of the file.
Fgets reads a string into the array pointed to by s from the stream stream. It stops on either EOF
or the first newline (which it reads), and appends a null character. At most n−1 characters are
read (leaving room for the null).
Both return s if successful, or a null pointer otherwise. In each case, if EOF is encountered before
any characters have been read, the array is unchanged and a null pointer is returned. A read error
in the middle of a string leaves the array contents undefined and a null pointer is returned.
References
Let us C by Yashavant Kanetkar.
Programming in C by Dennis M Ritchie.
Fundamental of Computer and programming in C by [Link].
GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-21
Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]
Course Code: CSE 101 E Subject: FCPC Unit: IV
Lecture
Topic: Library support for numbers and character required
data, Error handling
INTRODUCTION
The C Standard Library is the standard library for the programming language
C, as specified in the ANSI C standard. C library or libc are also used to
designate a particular implementation on a given system.
C does not provide direct support for error handling (also
known as exception handling). By convention, the programmer is expected to
prevent errors from occurring in the first place, and test return values from
2
functions.
CONTENTS
21.1 C Standard Library
21.1.1 Header Files
21.2 Error Handling
21.2.1 Types Of Errors In C Language.
UNIT-IV LESSON-21
After a long period of stability, three new header files (iso646.h, wchar.h, and wctype.h) were
added with Normative Addendum 1 (NA1), an addition to the C Standard ratified in 1995. Six
more header files (complex.h, fenv.h, inttypes.h, stdbool.h, stdint.h, and tgmath.h) were added
with C99, a revision to the C Standard published in 1999, and five more files (stdalign.h,
stdatomic.h, stdnoreturn.h, threads.h, and uchar.h) with C11 in 2011. In total, there are now 29
header files:
Name Description
Declares the macros setjmp and longjmp, which are used for
<setjmp.h>
non-local exits.
Three of the header files (complex.h, stdatomic.h, threads.h) are conditional features that
implementations need not support.
Summary
In this lesson we've learned the following:
Different kind of Libraries in the C language.
Each header file contains one or more function declarations, data type definitions, and
macros..
Concept of error handling in C.
Types of errors occur in C language.
Review Question
Ques.1 What is library function and why we use the library function in C language?
Sol: See page
Ques,2 What do you understand by error handling? (KUK)
Sol: See page
Ques3 Explain types of errors in C language.?
Sol: See page
Ques.4 What is the difference a user defined function and a library function in C? (KUK)
Sol: See page
References
Let us C by Yashawant Kanetkar.
Programming in C by Dennis M Ritchie.
Fundamental of Computer and programming in C by [Link].