0% found this document useful (0 votes)
8 views172 pages

Pps Notes

This lesson note provides an overview of digital computers, detailing their anatomy, memory units, and the advantages and limitations of computer systems. It explains the functions of the Central Processing Unit (CPU) and distinguishes between primary and secondary memory types, including various storage devices. Additionally, it covers input and output devices, emphasizing their roles in user interaction with computers.

Uploaded by

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

Pps Notes

This lesson note provides an overview of digital computers, detailing their anatomy, memory units, and the advantages and limitations of computer systems. It explains the functions of the Central Processing Unit (CPU) and distinguishes between primary and secondary memory types, including various storage devices. Additionally, it covers input and output devices, emphasizing their roles in user interaction with computers.

Uploaded by

Gagandeep Chawla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

GALAXY GLOBAL GROUP OF INSTITUTIONS

Dinarpur, (Ambala)

LESSON NOTE- L-1

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: I

Topic: Anatomy of a digital Computer, Memory Units Lecture


required

INTRODUCTION:

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

CONTENTS:

1.1 INTRODUCTION
1.1.1 Advantages of computers
1.1.2 Limitations of computers

1.2 ANATOMY OF COMPUTERS


1.2.1 Central processing unit

1.3 MEMORY UNITS:


1.3.1 Units of memory
1.3.2 Types of Memory

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.1.1 Advantages of computers :


1. High speed : Computers have the ability to perform routine tasks at a greater speed than
human beings. They can perform millions of calculations in seconds.
2. Accuracy : Computers are used to perform tasks in a way that ensures accuracy.
3. Storage : Computers can store large amount of information. Any item of data or any
instruction stored in the memory can be retrieved by the computer at lightning speeds.
4. Automation : Computers can be instructed to perform complex tasks automatically
(which increases the productivity).
5. Diligence : Computers can perform the same task repeatedly & with the same accuracy
without getting tired.
6. Versatility : Computers are flexible to perform both simple and complex tasks.
7. Cost effectiveness : Computers reduce the amount of paper work and human effort,
thereby reducing costs.
1.1.2 Limitations of computers :
1. Computers need clear & complete instructions to perform a task accurately. If the
instructions are not clear & complete, the computer will not produce the required result.
2. Computers cannot think.
3. Computers cannot learn by experience.

1.2 ANATOMY OF COMPUTERS:

The computer system consists of three units:

1. Input device
2. Central Processing Unit (CPU)
3. Output device

Block diagram of a Computer :

The various functions of these units can be summarized as:

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

1.2.1 CENTRAL PROCESSING UNIT:


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.
The CPU consists of storage or memory unit, Arithmetic Logic Unit (ALU) and control unit.

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

1.3 MEMORY UNITS:


Memory or storage capacity is one of the important components of a computer. Any storage unit
of a computer system is classified on the basis of the following criteria:
1. Access time: This is the time required to locate and retrieve stored data from the
storage unit in response to program instructions.
2. Storage capacity: It is the amount of data that can be stored in the storage unit.
3. Cost per bit of storage.

1.3.1 Units of memory:


The computer stores a character in the storage cells with binary (0,1) mechanism. Thus the basic
unit of memory is a bit (binary digit – 0,1). To store a character, a computer requires 8 bits or 1
byte. This is called the word length of the storage unit. Hence the storage capacity of the
computer is measured in the number of words it can store and is expressed in terms of bytes. The
different units of measurement are:
8 Bits = 1 Byte
210 (or) 1024 Bytes = 1 Kilo Byte (KB)
210 (or)1024 KB = 1 Mega Byte (MB)
210 (or)1024 MB = 1 Gega Byte (GB)

Conversion :
ASCII – American Standard Code for Information Interchange. This code has given alphabets
like some numbers which can be converted to Binary form.

A- 65 …….Z – 90 and a – 97 ………. z – 121


By using these codes the alphabets can be converted to digital & hence to Binary form.
1.3.2 Types of Memory :
A computer memory is of two types:
1. Primary Memory ( Internal storage)
2. Secondary Memory ( External storage)
Primary Memory : Primary memory is also called internal memory and is an important part of a
computer. It is the main area in a computer where the data is stored. The stored data can be
recalled instantly and correctly whenever desired. This memory can be quickly accessed by the
CPU for reading or storing information. Primary memory is further classified into two types:

Random Access Memory (RAM) and Read- Only Memory (ROM )

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.

CD-ROMs have the following variations:


(i) CD-R(Compact disc Recordable): Data can be written onto it just once. The stored
data can be read. Data once written onto it cannot be erased.
(ii) CD-RW(Compact disc Rewritable): It is also called erasable CD. Data once written
onto it can be erased to write or record new information many times. To use a CD-ROM,
a device called CD drive is needed.

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.2What are main advantages and limitations of computer system?

Q.3What is the memory units and explain the memory architecture with diagram?

 REFERENCES

1. Fundamental of Computers, [Link].

2. Fundamental of Computer and programming in C by [Link].

GALAXY GLOBAL GROUP OF INSTITUTIONS


Dinarpur, (Ambala)

LESSON NOTE- L-2

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: I

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:

2.1 MAIN AND AUXILIARY STORAGE DEVICES

2.1.1 PRIMARY STORAGE

2.1.2 SECONDARY STORAGE

2.2 INPUT DEVICES, OUTPUT DEVICES

2.2.1 INPUT DEVICES

2.2.2 OUTPUT DEVICES

2.1 MAIN AND AUXILIARY STORAGE DEVICES

Storage is devices that hold instructions and data. Computers have two different types of
storage: primary and auxiliary.

• Primary: Internal or main memory. Also commonly called random-access memory


(RAM). The more RAM a system has, the faster and more efficiently the computer can
perform its tasks. Main memory is volatile.

• Auxiliary: Secondary storage is nonvolatile. Most common types of secondary storage


devices are magnetic disks and optical discs .

2.1.1 PRIMARY STORAGE

 Primary storage is also called internal storage or memory.


 It is used to store programs and data currently being processed by CPU.
 Primary storage circuits like light bulbs need electricity to stay on.
 If the power to the computer is turned off, all the circuits will turn off and all data in
primary storage will be lost.
 When computer is turned back on the data will not reappear. The data is lost forever.
Because of this characteristics primary storage is called volatile storage.
 This type of primary storage is called RANDOM ACCESS MEMORY or RAM.
RAM is the main type of primary storage used with computers and it is volatile.
ROM
Many computers have another type of primary storage called ROM – Read Only Memory. ROM
is non-volatile storage. This means that when the power to the computer is turned off, the content
of the ROM is not lost. ROM can store preset programs that are always put by computer
manufactures. When you turn on a PC, you will usually see a reference on BIOS (Basic Input
output System). This is part of the ROM chip containing all the programs needed to control the
keyboard, monitor, disk drive and so on.

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

2.1.2 SECONDARY STORAGE


 Secondary Storage is an optional attachment, which is cable –connected to the CPU.
 Secondary is nonvolatile.
 Any data or programs stored in secondary storage stays there, even with the computer
power turned off, unless someone purposely erases them.
 Secondary storage is a permanent from of 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.

CD -ROM (OPTICAL DISK).

 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

2.2 INPUT DEVICES, OUTPUT DEVICES

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:

Input Devices Output Devices


Keyboard Monitor
Mouse LCD
Joystick Printer
Scanner Plotter
Light Pen
Touch Screen

2.2.1 INPUT DEVICES


[1] KEYBOARD
 It is a text base input device that allows the user to input alphabets, numbers and other
characters. It consists of a set of keys mounted on a board.

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.

[5] BAR CODES


 A bar code is a set of lines of different thicknesses that represent a number. Bar Code
Readers are used to input data from bar codes. Most products in shops have bar codes on
them. Bar code readers work by shining a beam of light on the lines that make up the bar
code and detecting the amount of light that is reflected back.
[6] LIGHT PEN
 It is a pen shaped device used to select objects on a display screen. It is quite like the
mouse (in its functionality) but uses a light pen to move the pointer and select any object
on the screen by pointing to the object.
 Users of Computer Aided Design (CAD) applications commonly use the light pens to
directly draw on screen.

[7] TOUCH SCREEN


 It allows the user to operate/make selections by simply touching the display screen.
 Common examples of touch screen include information kiosks, and bank ATMs.

[8] DIGITAL CAMERA


 A digital camera can store many more pictures than an ordinary camera.
 Pictures taken using a digital camera are stored inside its memory and can be transferred
to a computer by connecting the camera to it.
 A digital camera takes pictures by converting the light passing through the lens at the
front into a digital image.
[9] THE SPEECH INPUT DEVICE
 The “Microphones - Speech Recognition” is a speech Input device.
 To operate it we require using a microphone to talk to the computer. Also we need to add
a sound card to the computer. The Sound card digitizes audio input into 0/1s.
 A speech recognition program can process the input and convert it into machine-
recognized commands or input.
2.2.2 OUTPUT DEVICES
[1] MONITOR
 Monitor is an output device that resembles the television screen and uses a Cathode Ray
Tube (CRT) to display information.
 The monitor is associated with a keyboard for manual input of characters and displays the
information as it is keyed in.
 It also displays the program or application output. Like the television, monitors are also
available in different sizes.
[2] Liquid Crystal Display (LCD)
 LCD was introduced in the 1970s and is now applied to display terminals also.
 Its advantages like low energy consumption, smaller and lighter have paved its way for
usage in portable computers (laptops).

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

[5] AUDIO OUTPUT: SOUND CARDS AND SPEAKERS:


 The Audio output is the ability of the computer to output sound.
 Two components are needed: Sound card – Plays contents of digitized recordings,
Speakers – Attached to sound card.
 SUMMARY:
 In this lesson, we studied about the basic concept of input and output devices. Also
studied about the working and functions of all these type of devices.
 Storage is devices that hold instructions and data.
 Computers have two different types of storage: primary and auxiliary.
 Input/ Output devices are required for users to communicate with the computer.
 In simple terms, input devices bring information INTO the computer
 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.

 REVIEW QUESTIONS:

Q.1What do you understand by input/ output devices? Explain with examples.

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:

1. Fundamental of Computers, [Link].

2. Fundamental of Computer and programming in C by [Link].


GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-3

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: I

Topic: Classification of Computers Lecture


required

INTRODUCTION:

Computer can be classified into three aspects:


 Representation of numbers
 Degree of specialization
 Types of application 1
They are many types of computers and they include:
 Mainframe computers
 Mini - Computers, now often called "Mid-Range" Computers
 Micro - Computers, now commonly called Personal Computers (PC)
Super computers

CONTENTS:

3.1 CLASSIFICATION OF COMPUTERS


3.2 REPRESENTATION OF NUMBERS
3.3 DEGREE OF SPECIALIZATION
3.4 TYPES OF APPLICATION
3.5 TYPES OF COMPUTERS
3.5.1 Mainframe computer
3.5.2 Minicomputer
3.5.3 Micro computer
3.5.4 Other business computers
3.1 CLASSIFICATION OF COMPUTERS
Computer can be classified into three aspects:
 Representation of numbers
 Degree of specialization
 Types of application

3.2 REPRESENTATION OF NUMBERS


There are three basic aspects of Computers, which are digital, analog and hybrid.
Digital Computer: This aspect of computer operates on numbers directly. It handles numbers
discretely and precisely rather than approximately.
Examples of digital computers are digital watch, digital phone and digital radio.
Analog Computer: This aspect of computer deals with quantities that are continuously variable
e.g. speedometer, electric meter, water meter, thermometer.
Hybrid Computer: This computer combines the features of both analog and digital computers.
They handle data in both quantities and variable.

3.3 DEGREE OF SPECIALIZATION


There are two basic types – special and general-purpose computer.

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.4 TYPES OF APPLICATION


There are two types – Scientific and Business Applications.
Scientific Applications: These computers are designed to handle scientific application more
effectively. They require small volume of data input and output.
Business Data-Processing Application: These computers are designed to handle business data
processing applications. They need a large data file, input storage, output storage devices and
large storage capabilities.

3.5 TYPES OF COMPUTERS


They are many types of computers and they include:
 Mainframe computers
 Mini - Computers, now often called "Mid-Range" Computers
 Micro - Computers, now commonly called Personal Computers (PC)
 Super computers

3.5.1 MAINFRAME COMPUTER


 System is one that has at its heart a very powerful central computer linked by cable or
telecommunications to hundreds or thousands of terminals and capable of accepting
simultaneous input from all of them.
 Mainframe has many times more processing power than a PC and offers very extensive
data storage facilities.
 Mainframe Computers are used by organizations such as banks that have very large
volumes of processing to perform and have special security needs.
 Many organizations have now replaced their old mainframe with network "client server"
systems of Mini Computers and PCs because this approach - called downsizing is
thought to be cheaper and offer greater reliability, functionality and data security than
networked systems.

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.

3.5.3 MICRO COMPUTER


 Market was first developed by companies like APPLE COMPUTERS, but a key event
was the launch of the IBM PC in August 1981.
 In the early year of the development of the PC, the Apple Macintosh (technically not a
PC ) became the standard for graphics – based applications and the IBM PC and a host
of IBM-Compatibles, were chosen for text-based (business) applications.
 However, as chips have become more powerful, the difference in emphasis has become
less important. Apple have recently introduced the power PC, which is IBM-Compatible.
PCs are now the norm for small to medium-sized business computers.
 Today microcomputers are Personal Computer system or stand-alone computer. They
are being distinguished from other computer systems because of possessing a single
microprocessor.

3.5.4 Other business computers are:


 File server
 Portables
 Workstations.

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.1How many types of computer used today environment?

Q.2What are the main categories of digital computer and where it is used? Explain.

 REFERENCES:

1. Fundamental of Computers, [Link].

2. Fundamental of Computer and programming in C by [Link].

GALAXY GLOBAL GROUP OF INSTITUTIONS


Dinarpur, (Ambala)
LESSON NOTE- L-4

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: I

Topic: Radix number system: Decimal, Binary, Octal, Hexadecimal numbers Lecture
and their inter-conversions; Representation of information inside the computers. required

INTRODUCTION-

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

CONTENTS-

41. RADIX NUMBER SYSTEM


4.2 CONVERSION
4.2.1 Conversion of Binary to decimal ( base 2 to base 10)
4.2.2 Conversion of decimal to binary ( base 10 to base 2)
4.2.3 Conversion of decimal fraction to binary fraction
4.2.4 Conversion of octal to decimal ( base 8 to base 10)
4.2.5 Conversion of decimal to octal ( base 10 to base 8)
4.2.6 Conversion of hex to decimal ( base 16 to base 10)
4.2.7 Conversion of decimal to hex ( base 10 to base 16)
4.2.8 Conversion of binary to octal and hex

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

Thus, a string of number 234.5 can be represented as:

2 × 102 + 3 × 101 + 4 × 100 + 5 × 10-1

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.

For example, 101010 is a valid binary number.

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:

Decimal equivalent of Octal Number:

(23.4)8

=2×81 +3×80 +4×8-1

= 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

4.2.1 Conversion of Binary to decimal ( base 2 to base 10)


Example: Convert (1000100)2 to decimal
= 64 + 0 + 0+ 0 + 4 + 0 + 0
= (68)10

Example: Convert (10110)2 to decimal

= 16+0+4+2+0 =22

4.2.2 Conversion of decimal to binary ( base 10 to base 2)


Example: Convert (68)10 to binary
68/¸2 = 34 remainder is 0
34/ 2 = 17 remainder is 0
17 / 2 = 8 remainder is 1
8 / 2 = 4 remainder is 0
4 / 2 = 2 remainder is 0
2 / 2 = 1 remainder is 0
1 / 2 = 0 remainder is 1
Answer = 1 0 0 0 1 0 0

4.2.3 Conversion of decimal fraction to binary fraction


Instead of division , multiplication by 2 is carried out and the integer part of the result is saved
and placed after the decimal point.
The fractional part is again multiplied by 2 and the process repeated.
Example: Convert (0.68)10 to binary fraction.
0.68 * 2 = 1.36 integer part is 1
0.36 * 2 = 0.72 integer part is 0
0.72 * 2 = 1.44 integer part is 1
0.44 * 2 = 0.88 integer part is 0
Answer = 0. 1 0 1 0…..

Example: convert (68.68)10 to binary equivalent.


Answer = 1 0 0 0 1 0 0 . 1 0 1 0….

4.2.4 Conversion of octal to decimal ( base 8 to base 10)


Example: Convert (632)8to decimal
= (6 x 82) + (3 x 81) + (2 x 80)
= (6 x 64) + (3 x 8) + (2 x 1)
= 384 + 24 + 2
= (410)10

4.2.5 Conversion of decimal to octal ( base 10 to base 8)


Example: Convert (177)10 to octal
177 / 8 = 22 remainder is 1
22 / 8 = 2 remainder is 6
2 / 8 = 0 remainder is 2
Answer = 2 6 1

4.2.6 Conversion of hex to decimal ( base 16 to base 10)


Example: Convert (F 4 C)16to decimal
= (F x 162) + (4 x 161) + (C x 160)
= (15 x 256) + (4 x 16) + (12 x 1)

The answer is read from bottom to top , same as with the binary case.
= 3840 + 64 + 12 + 0
= (3916)10

4.2.7 Conversion of decimal to hex ( base 10 to base 16)


Example: Convert (4768)10 to hex.
= 4768 / 16 = 298 remainder 0
= 298 / 16 = 18 remainder 10 (A)
= 18 / 16 = 1 remainder 2
= 1 / 16 = 0 remainder 1
Answer: 1 2 A 0

4.2.8 Conversion of binary to octal and hex


Conversion of binary numbers to octal and hex simply requires grouping bits in the binary
numbers into groups of three bits for conversion to octal and into groups of four bits for
conversion to hex. Groups are formed beginning with the LSB and progressing to the MSB.
Thus, (11100 111)2 = (347)8
(11100 010 101 010 010 001)2= (3025221)8
¿ = (E 7)16
(1 10001010 1000 0111)2 = (18 A 87)16

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

Q.2 What is ( ABBA)16 in decimal?

Q.3 Convert (6137)10 to the octal system.

 REFERENCES:

1. Fundamental of Computers, [Link].

2. Fundamental of Computer and programming in C by [Link].

GALAXY GLOBAL GROUP OF INSTITUTIONS


Dinarpur, (Ambala)
LESSON NOTE- L-5

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: I

Topic: Operating System Basics: Introduction to PC operating Systems: Lecture


DOS, Unix/Linux, Windows 2000 required

INTRODUCTION:

The operating system is the core software component of your computer. It


performs many functions and is, in very basic terms, an interface between your
computer and the outside world. The operating system provides an interface to
these parts using what is referred to as "drivers". This is why sometimes when 2
you install a new printer or other piece of hardware.

CONTENTS:

5.1 OPERATING SYSTEMS


5.1.1 Introduction to operating system
5.1.2 What does a driver do of an operating system
5.1.3 Functions of an operating system
5.2 OPERATING SYSTEM CONCERNS
5.3 TYPES OF AN OPERATING SYSTEM
5.4 BASIC INTRODUCTION TO DOS, UNIX/LINUX OS, WINDOWS XP
5.4.1 Introduction to DOS
5.4.2 Introduction to UNIX OS
5.4.3 Introduction to LINUX OS
5.4.4 Basic UNIX/LINUX commands
5.4.5 Introduction to Windows XP

5.1 OPERATING SYSTEMS

5.1.1 INTRODUCTION TO OPERATING SYSTEM:


 The operating system is the core software component of your computer. It performs many
functions and is, in very basic terms, an interface between your computer and the outside
world.
 A computer is described as consisting of several component parts including your monitor,
keyboard, mouse, and other parts. The operating system provides an interface to these
parts using what is referred to as "drivers". This is why sometimes when you install a
new printer or other piece of hardware.

5.1.2 WHAT DOES A DRIVER DO OF AN OPERATING SYSTEM:


 A driver is a specially written program which understands the operation of the device it
interfaces to, such as a printer, video card, sound card or CD ROM drive. It translates
commands from the operating system or user into commands understood by the
component computer part it interfaces with.
 It also translates responses from the component computer part back to responses that can
be understood by the operating system, application program, or user.

The below diagram gives a graphical depiction of the interfaces between the operating system
and the computer component.

5.1.3 FUNCTIONS OF AN OPERATING SYSTEM:


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.

5.2 OPERATING SYSTEM CONCERNS:


Operating systems are written by human programmers who make mistakes. Therefore there can
be errors in the code even though there may be some testing before the product is released. Some
companies have better software quality control and testing than others so you may notice varying
levels of quality from operating system to operating system.

Errors in operating systems cause three main types of problems:

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

5.3 TYPES OF AN OPERATING SYSTEM:


There are many types of operating systems. The most common is the Microsoft suite of operating
systems. They include from most recent to the oldest:
 Windows XP Professional Edition - A version used by many businesses on
workstations. It has the ability to become a member of a corporate domain.
 Windows XP Home Edition - A lower cost version of Windows XP which is for home
use only and should not be used at a business.
 Windows 2000 - A better version of the Windows NT operating system which works
well both at home and as a workstation at a business. It includes technologies which
allow hardware to be automatically detected and other enhancements over Windows NT.
 Windows ME - An upgraded version from windows 98 but it has been historically
plagued with programming errors which may be frustrating for home users.
 Windows 98 - This was produced in two main versions. The first Windows 98 version
was plagued with programming errors but the Windows 98 Second Edition which came
out later was much better with many errors resolved.
 Windows NT - A version of Windows made specifically for businesses offering better
control over workstation capabilities to help network administrators.
 Windows 95 - The first version of Windows after the older Windows 3.x versions
offering a better interface and better library functions for programs.

5.4 BASIC INTRODUCTION TO DOS, UNIX/LINUX OS, WINDOWS


XP.:

5.4.1 INTRODUCTION TO DOS:


This is about the family of operating systems for IBM PC-compatible computers. For other uses,
DOS. DOS, short for "Disk Operating System", is an acronym for several closely related
operating systems that dominated the IBM PC compatible market between 1981 and 1995, or
until about 2000 if one includes the partially DOS-based Microsoft Windows versions 95, 98,
and Millennium Edition. Related systems include MSDOS, PC-DOS, DR-DOS, FreeDOS, PTS-
DOS, ROM-DOS, JM-OS, and several others. In spite of the common usage, none of these
systems were simply named "DOS" (a name given only to an unrelated IBM mainframe
operating system in the 1960s). A number of unrelated, non-x86 microcomputer disk operating
systems had "DOS" in their name, and are often referred to simply as "DOS" when discussing
machines that use them (e.g. AmigaDOS, AMSDOS, ANDOS, Apple DOS, Atari DOS,
Commodore DOS, CSI-DOS, ProDOS, and TRS-DOS). While providing many of the same
operating system functions for their respective computer systems, programs running under any
one of these operating systems would not run under others.
5.4.2 INTRODUCTION TO UNIX OS:
Unix operating systems are widely used in servers, workstations, and mobile devices. The Unix
environment and the client–server program model were essential elements in the development of
the Internet and the reshaping of computing as centered in networks rather than in individual
computers. Both Unix and the C programming language were developed by AT&T and
distributed to government and academic institutions, which led to both being ported to a wider
variety of machine families than any other operating system. As a result, Unix became
synonymous with "open systems". Unix was designed to be portable, multi-tasking and multi-
user in a time-sharing configuration. Unix systems are characterized by various concepts: the use
of plain text for storing data; a hierarchical file system; treating devices and certain types of
inter-process communication (IPC) as files; and the use of a large number of software tools,
small programs that can be strung together through a command line interpreter using pipes, as
opposed to using a single monolithic program that includes all of the same functionality. Under
Unix, the "operating system" consists of many of these utilities along with the master control
program, the kernel. The kernel provides services to start and stop programs, handles the file
system and other common "low level" tasks that most programs share, and, perhaps most
importantly, schedules access to hardware to avoid conflicts if two programs try to access the
same resource or device simultaneously.

5.4.3 INTRODUCTION TO LINUX OS:


Linux refers to the family of Unix-like computer operating systems using the Linux kernel.
Linux can be installed on a wide variety of computer hardware, ranging from mobile phones,
tablet computers and video game consoles, to mainframes and supercomputers. Linux is a
leading server operating system, and runs the 10 fastest supercomputers in the world. The
development of Linux is one of the most prominent examples of free and open source software
collaboration; typically all the underlying source code can be used, freely modified, and
redistributed, both commercially and non-commercially, by anyone under licenses such as the
GNU General Public License. Typically Linux is packaged in a format known as a Linux
distribution for desktop and server use. Linux distributions include the Linux kernel and
supporting utilities and libraries to fulfill the distribution's intended use.
Because Linux is freely redistributable, it is possible for anyone to create a distribution for any
intended use. Commonly used applications with desktop Linux systems include the Mozilla
Firefox web-browser, the [Link] office application suite and the GIMP image editor.
The name "Linux" comes from the Linux kernel, originally written in 1991 by Linus Torvalds.
The main supporting user space system tools and libraries from the GNU Project (announced in
1983 by Richard Stallman) are the basis for the Free Software Foundation's preferred name
GNU/Linux.

5.4.4 BASIC UNIX/LINUX COMMANDS:

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.

5.4.5 INTRODUCTION TO WINDOWS XP:

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.1 What are the basic functions of an operating system?

Q.2 Describe the two general roles of an operating system, and elaborate why these roles are
important.

Q.3 What is a process? What are attributes of a process?

 REFERENCES:

1. Fundamental of Computers, [Link].

2. Fundamental of Computer and programming in C by [Link].

GALAXY GLOBAL GROUP OF INSTITUTIONS


Dinarpur, (Ambala)
LESSON NOTE- L-6

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: II

Topic: Machine level language, Assembly level language and High Level- Lecture
Language required

INTRODUCTION:

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 and a special syntax for organizing program
instructions.
1

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:

6.1 INTRODUCTION TO PROGRAMMING LANGUAGE


6.2 CHARACTERISTICS OF GOOD PROGRAMMING
LANGUAGE
6.3 MACHINE LANGUAGE
6.4 ASSEMBLY LANGUAGE
6.5 HIGH LEVEL LANGUAGE

6.1 INTRODUCTION TO PROGRAMMING LANGUAGE:

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

6.2 CHARACTERISTICS OF GOOD PROGRAMMING LANGUAGE:

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.

2. Complexity management (architecture support) – the extent to which inherent language


features support the management of system complexity, in terms of addressing issues of data,
algorithm, interface, and architectural complexity.
3. Concurrency support – the extent to which inherent language features support the
construction of code with multiple threads of control (also known as parallel processing).

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.

7. Object-oriented programming support – the extent to which inherent language features


support the construction of object-oriented code.

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.

6.3 MACHINE 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. 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.

 Advantages of Machine Language:


1. It is a most efficient in term of storage area use and execution speed and it also allows
programmer to utilize the computer's potential for processing data.
2. The only advantage is that program of machine language run very fast because no
translation program is required for the CPU.
3. In machine language, the very basic and specific commands may be used, like to where
the specific data will be stored, how operations and functions be carried out. and since it
is in a code the machine can understand, it may not need a compiler.
 Disadvantages of Machine Language:
1. It is very difficult to program in machine language. The programmer has to know details
of hardware to write program.
2. The programmer has to remember a lot of codes to write a program which results in
program errors.
3. It is difficult to debug the program.
6.4 ASSEMBLY LANGUAGE:

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.

 Advantages of Assembly Languages:


1. Assembly language is a symbolic representation of a processor's native code. Using
machine code allows the programmer to control precisely what the processor does.
2. It offers a great deal of power to use all of the features of the processor. The resulting
program is normally very fast and very compact.
3. In small programs it is also very predictable. Timings, for example, can be calculated
very precisely and program flow is easily controlled.
4. It is often used for small, real time applications.

 Disadvantages of Assembly Languages:


1. The programmer needs to have a good understanding of the hardware being used.
2. As programs become larger, assembly language get very cumbersome.
3. Maintenance of assembly language is difficult, especially if another programmer is
brought in to carry out modifications after the code has been written.
4. Assembly langauge also has no support of an operating system, nor does it have any
complex instructions.
5. Storing and retrieving data is a simple task with high level languages; assembly needs the
whole process to be programmed step by step.
6. Mathematical processes also have to be performed with binary addition and subtraction
when using assembly which can get very complex.
6.5 HIGH LEVEL 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.

 Advantages of High Level Language:


1. In high level languages we can write programs in English like manner and is more
convenient to use.
2. Programmer can perform complex task by using high level languages with less efforts.
3. High level languages are very similar to nature language such as English so they are very
easy to learn and use.
4. For higher level languages programmers needs not to learn about internal structure of the
computer.
5. High level language programs require less time and efforts that due the preparation cost
of the program.
6. High level programs are very easy to maintain than lower level languages.
7. Compilers of high level languages automatically catch and point out the errors made by
the programmers.

 Disadvantages of High Level Languages:


1. Though it is much easier to code in a high level language, oftentimes access to more low-
level functionalities are lost.
2. For instance, the ability to communicate directly with the compiler and alter code before
it gets transferred into machine code is lost.
3. To make it more easier for the programmer to understand and write code. High level
programming languages like C, C++ and Java give you comfort and a pool of options
because they basically use a syntax that is similar to the everyday English we speak.
4. Coding a computer today is just one step below to talking to a human. It is that easy.
5. Low level programming languages are important because of space and speed. If you write
a program in a high level language, say Java, first the Java Compiler will compile it to
byte code. Now, this byte code is again compiled during run time to assembly code(low
level) which in turn is again converted to executable code. But, when you write low level
code, it is directly converted into executable code avoiding all the other steps. This will
incredibly save you space and increase speed.

 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:

1. Fundamental of Computers, [Link].

2. Fundamental of Computer and programming in C by [Link].


3. Let us C by Yashwant Kanetkar.

GALAXY GLOBAL GROUP OF INSTITUTIONS


Dinarpur, (Ambala)
LESSON NOTE- L-7

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: II

Topic: Introduction to Assembler, Compiler, Interpreter, Debuggers, Lecture


Linker and Loader required

INTRODUCTION:

A computer can execute only machine language program directly. Hence we


need to translator/convertor to translate the any language program to its
equivalent machine language program. We have different kind of translator such
as compiler, assembler, interpreter, linker , loader etc.
2

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.

An interpreter translates high-level instructions into an intermediate form, which


it then executes. In contrast, a compiler translates high-level instructions directly into
machine language. Compiled programs generally run faster than interpreted programs.
The advantage of an interpreter, however, is that it does not need to go through the
compilation stage during which machine instructions are generated. This process can be
time-consuming if the program is long. The interpreter, on the other hand, can
immediately execute high-level programs. For this reason, interpreters are sometimes
used during the development of a program, when a programmer wants to add small
sections at a time and test them quickly. In addition, interpreters are often used in
education because they allow students to program interactively.

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.1 What is a linker? Why it is required?

Q.2 What is an interpreter? How does it differs from a complier?

Q.3 What are the advantages and disadvantages of compiler, assembler and interpreter?

 REFERENCES:

1. Fundamental of Computers, [Link].

2. Fundamental of Computer and programming in C by [Link].

3. Let us C by Yashwant Kanetkar.


GALAXY GLOBAL GROUP OF INSTITUTIONS
Dinarpur, (Ambala)
LESSON NOTE- L-11

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: III
Topic: C fundamentals, Formatted Input/ Output Lecture
required
INTRODUCTION:
C is a general purpose, high level programming language. Dennis Ritchie
created it at AT’s & T Bell labs in 1972.
The popularity of C is due to its following features:
 C is a powerful and flexible language.
 C is a popular language preferred by professional programmers.
 C is a portable language.
 C is modular. C code can (and should) be written in routines called
functions. 2

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.3 STANDARD INPUT AND OUTPUT


11.3.1 scanf ( )
11.3.2 printf ( )
11.1 C-FUNDAMENTALS:

11.1.1An Introduction of C

History of the C Language

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?

In today's world of computer programming, there are many high-level languages to


choose from, such as C, Pascal, BASIC, and Java. These are all excellent languages suited for
most programming tasks. Even so, there are several reasons why many computer professionals
feel that C is at the top of the list:

1. C is a powerful and flexible language. C is used for projects as diverse as operating


systems, word processors, graphics, spreadsheets, and even compilers for other
languages.
2. C is a popular language preferred by professional programmers. As a result, a wide
variety of C compilers and helpful accessories are available.
3. C is a portable language. Portable means that a C program written for one computer
system (an IBM PC, for example) can be compiled and run on another system (a DEC
VAX system, perhaps) with little or no modification.
4. C is a language of few words, containing only a handful of terms, called keywords, which
serve as the base on which the language's functionality is built.
5. C is modular. C code can (and should) be written in routines called functions. These
functions can be reused in other applications or programs.
11.2 Types, Operators & Expressions

11.2.1 THE C CHARACTER SET


C uses the uppercase letters A to Z, the lowercase letters a to z, the digit 0 to 9, and some special
characters to form basic program elements (e.g., constants variables, operators, expression) as we
discussed above. The special characters are listed below:
* + \ ” <
# ) = ; } >
^ ( ] , { ?
& - [ : ‘ /
% _ == ~ . (blank)<>

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.2 IDENTIFIERS AND KEYWORDS


Identifiers are names given to various elements of a program, such as variables, functions and
arrays. Identifiers consist of digits and letters, in any order but the rule is first character should be
a letter. Anyone can use both uppercase and lowercase letters. But uppercase and lowercase
letters are not having same meaning e.g. RAM & ram are not same. The underscore character (_)
can also be included and is considered to be a letter. Any identifier can start with underscore
character, though this is not a good programming practice. Some of the following names are
valid identifiers:
She, Z02, computer_02, _wind
Classes, areal, interest_rate, PERIOD
Now, we list out the following names which are not valid identifiers:
2nd, “y”, ship-no, flag error
The first identifier name starting with 2 (i.e. a digit) is not valid, because first character must be a
letter, illegal character ‘‘ ’’ is present in the “y” identifier, similarly ship-no, flag error are also
invalid identifier name as hyphen & blank character are not allowed in the naming convention of
identifiers. An identifier can be arbitrarily long. The standard keywords are listed below:

auto extern size of break float static


case for struct const typedef if
switch char goto unsigned default long
continue int union void do register
volatile double return while else short
signed enum

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

‘A’, ‘y’ ‘4’ ‘$’


Each character constant has its equivalent ASCII value like ‘A’ has

65, ‘y’ has 121 ‘4’ has 52 & so on.


Certain nonprinting characters as well as the double quote(“), the apostrophe (‘) , the question
mark (?) and the backslash(\) can be expressed in terms of escape sequences. An escape
sequence always begins with a backward slash and is followed by one or more special characters.
Several character constants, expressed in terms of escape sequences are:

‘\n’ ‘\t’ ‘\b’ ‘\\’ ‘\’


The escape sequence \f represents the null character which is used to indicate the end of a string.
11.2.4 DATA TYPES
C supports different types of data, each of which may be represented differently within the
computer’s memory. The various basic data types are listed below in tabular form:
Data type Description Typical memory requirements
Int integers quantity 2 bytes or 1 word
char simple character 1 byte
float floating-point number 1 word (4 bytes)
double double-precision floating 2 words (8 bytes)

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.

11.2.5 VARIABLES AND ARRAYS


A quantity which may vary during program execution is called a variable. Each variable has a
specific storage location in memory where its value is stored. The variable is given a name, the
variable name is the “name tag” for the storage location. The value of the variable at any instant
during the execution of a program is equal to the number stored in the storage location identified
by the name of the variable.

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.

Variable Type Keyword Bytes Required Range


Character char 1 -128 to 127
Integer int 2 -32768 to 32767
Short integer short 2 -32768 to 32767
Long integer long 4 -2,147,483,648 to 2,147,438,647
Unsigned character unsigned char 1 0 to 255
Unsigned integer unsigned int 2 0 to 65535
Unsigned short integer unsigned short 2 0 to 65535
Unsigned long integer unsigned long 4 0 to 4,294,967,295

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];

11.2.7 PREPARING TO PROGRAM

When creating a program in C (or for that matter, a computer program in any language), you
should follow a similar sequence of steps:

1. Determine the objective(s) of the program.


2. Determine the methods you want to use in writing the program.
3. Create the program to solve the problem.
4. Run the program to see the results.

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.

Creating the Source Code

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

I. The Assignment Operator


The assignment operator is the equal sign (=). Its use in programming is somewhat different from
its use in regular math. If you write
x = y;
in a C program, it doesn't mean "x is equal to y." Instead, it means "assign the value of y to x."
In a C assignment statement, the right side can be any expression, and the left side must be
a variable name. Thus, the form is as follows:
variable = expression;
When executed, expression is evaluated, and the resulting value is assigned to variable.

II. Mathematical Operators


C's mathematical operators perform mathematical operations such as addition and subtraction. C
has two unary mathematical operators and five binary mathematical operators. Unary
Mathematical Operators The unary mathematical operators are so named because they take a
single operand. C has two unary mathematical operators.

Operator Symbol Action Examples


Increment ++ Increments the operand by one ++x, x++
Decrement -- Decrements the operand by one --x, x—

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;

Binary Mathematical Operators


C's binary operators take two operands. The binary operators, which include the common
mathematical operations found on a calculator.

Operator Symbol Action Example


Addition + Adds two operands x+y
Subtraction - Subtracts the second operand x-y
from the first operand

Multiplication * Multiplies two operands x*y


Division / Divides the first operand by x/y
the second operand
Modulus % Gives the remainder when the 100 modulus 9 equals 1
first operand is 10 modulus 5 equals 0
divided by x % y the 40 modulus 6 equals 4
second operand.
III. Relational Operators
C's relational operators are used to compare expressions, asking questions such as, "Is x greater
than 100?" or "Is y equal to 0?" An expression containing a relational operator evaluates to either
true (1) or false (0). C's six relational operators are listed:
Operator Symbol Question Asked Example
Equal == Is operand 1 equal to operand 2? x == y
Greater than > Is operand 1 greater than operand 2? x>y
Less than < Is operand 1 less than operand 2? x<y
Greater than >= Is operand 1 greater than or x >= y
or equal to equal to operand 2?
Less than or equal to <= Is operand 1 less than or x <= y
equal to operand 2?
Not equal != Is operand 1 not equal to operand 2? x != y

Relational operators in use.


Expression How It Reads What It Evaluates To
5 == 1 Is 5 equal to 1? 0 (false)
5 > 1 Is 5 greater than 1? 1 (true)
5 != 1 Is 5 not equal to 1? 1 (true)
(5 + 10) == (3 * 5) Is (5 + 10) equal to (3 * 5)? 1 (true)
DO learn how C interprets true and false. When working with relational operators, true is equal
to 1, and false is equal to 0.
DON'T confuse ==, the relational operator, with =, the assignment operator.
This is one of the most common errors that C programmers make.

IV. Logical Operators


C's logical operators let you combine two or more relational expressions into a single expression
that evaluates to either true or false. Table 4.7 lists C's three logical operators.
C's logical operators.
Operator Symbol Example
AND exp1 && exp2 True (1) only if both exp1 and exp2 are true; false (0) otherwise

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.

11.3 FORMATTED INPUT AND OUTPUT

11.3.1 scanf() : ( Input function )


scanf() is used to read the input from the keyboard in a particular format. We can also read more
than one input at the same time which is of different data type.

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

w - width of input data(optional)

data type - Conversion character or type of data given to the variables


Format specifier :
Format specifier Meaning
%c character format specifier
%d Integer format specifier
%i Integer format specifier (same as %d)
%f Floating-point format specifier
% e or % E Scientific notation format specifier
% g or % G Uses %f or %e, whichever result is shorter
%o Unsigned octal format specifier
%s String format specifier
%u Unsigned integer format specifier
% x or % X Unsigned hexadecimal format specifier
%p Displays the corresponding argument that is a pointer
%n Records the number of characters written so far
%% Outputs a percent sign

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 )

 It displays information on screen.


 It returns the number of characters printed.
 It displays the text you put inside the double quotes.
 It requires the backslash character(escape sequence) to display some special characters.
 It can display variables by using the % conversion character.
 Printf format: a string argument followed by any additional
arguments.
Syntax :
printf("control string",list);
where control string gives the format of data to be displayed, list contains the list of
variables, constants, array names to be printed. The general form is

%w.p data type


where % - conversion specification indicator

w - width of output data(optional)

p - Number of digits after decimal point or number of characters to to


displayed from a string

data type - type of output data or conversion character

Printing integer numbers :


The general format of control string to output an integer is
%wd
where w - width of output data(optional)
d - conversion character for integer
Example :
Assume x=2000;

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.

Q.3 What is the purpose of scanf ( ) and printf ( ) functions?

 REFERENCES:
 Let us C by Yashwant Kanetkar.
 Fundamental of Computer and programming in C by [Link].
 Brian W. Kernighan and Dennis M. Ritchie

GALAXY GLOBAL GROUP OF INSTITUTIONS


Dinarpur, (Ambala)
LESSON NOTE- L-12

Faculty/Author: Sachin Gupta S e me s te r : I Class: [Link]


(ECE)
Course Code: CSE 101 E Subject: FCPC Unit: III
Topic: Expressions, selection statements, loops and their applications Lecture
required
INTRODUCTION:
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. An expression is a
combination of constants, variables, and operators that are used to denote
computations.
Looping, also called iteration, is used in programming to perform the same set
of statements over and over until certain specified conditions are met.
2
CONTENTS:

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;

12.2.1 Statement Blocks


A group of statements can form a statement block that starts with an opening brace ({) and ends
with a closing brace
(}). A statement block is treated as a single statement by the C compiler.
For instance, the following
for(. . .) {
s3 = s1 + s2;
mul = s3 * c;
remainder = sum % c;
}
is a statement block that starts with { and ends with }. Here for is a keyword in C that determines
the statement block. A statement block provides a way to group one or more statements together
as a single statement. Many C keywords can only control one statement. If you want to put more
than one statement under the control of a C keyword, you can add those statements into a
statement block so that the block is considered one statement by the C keyword.

12.2.2 Selection Statements:


Sometimes in programming, we need to be able to choose between two or more alternatives.
Selection statements include if and switch statements. Logical expressions need to be discussed
as it is used in statements such as if.
if Syntax form:
Syntax:
if (expression / condition)
statement;
else
statement;
if (expression / condition)
{ statement1;
statement2;
statementn;}
else
{ statement1;
statement2;
statementn; }
12.2.3 Switch Statement
A construct that is used to replace deeply nested or chained (Multiple) if else statements.
Example: Suppose that an ice cream store has asked us to write a program that will automate
taking of the orders?
– We will need to present a menu and
– Based on the customer's choice take an appropriate action.
include <stdio.h>
main()
{
int choice;
printf("What flavor ice cream do you want?\n");
printf("Enter 1 for chocolate\n");
printf("Enter 2 for vanilla\n");
printf("Enter 3 for strawberry\n");
printf("Enter 4 for green tea flavor, yuck\n");
printf("Enter you choice: ");
scanf("%d“,&choice);
if (choice==1){
printf("Chocolate, good choice\n");}
else if (choice==2) {printf("Vanillarific\n");}
else if (choice==3) {printf("Berry Good\n");}
else if (choice==4) {printf("Big Mistake\n");}
else {printf("We don't have any.\n");
printf("Make another selection.\n");}
return 0;}
This program will works fine, but the if else block is cumbersome.
It would be easy, particularly if there were more choices and maybe sub choices involving more
if else's to end up with program that doesn't perform the actions intended.

• The general form of a switch statement is:


switch (variable)
{
case expression1: Action1; break;
case expression2: Action2; break;
....
default: default_Action;
}

12.3 LOOP CONCEPT IN C


Loop Means--Doing the Same Thing Over and Over. Looping, also called iteration, is
used in programming to perform the same set of statements over and over until certain
specified conditions are met.
Three statements in C are designed for looping:
 The for statement
 The while statement
 The do-while statement
The following sections explore these statements:

12.3.1 The for loop

The general form of the for statement is


for (expression1; expression2; expression3) {
statement1;
statement2;
.
.
.
}

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

12.3.2 The while Loop


The while statement is also used for looping. Unlike the situation with the for statement, there is
only one expression field in the while statement.

The general form of the while statement is:


while (expression) {
statement1;
statement2;
.
.
.
}

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;
}

12.3.3 The do-while Loop


The general form for the do-while statement is
do {
statement1;
statement2;
.
.
.
} while (expression);

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;
}

12.4 Break and Continue


It is sometimes convenient to be able to exit from a loop other than by testing at the top or
bottom. The break statement provides an early exit from for, while, and does, just as from
switch. A break causes the innermost enclosing loop or switch to be exited immediately.
The following function, trim, removes trailing blanks, tabs and newlines from the end of a string,
using a break to exit from a loop when the rightmost non-blank, non-tab, non-newline is found.
/* trim: remove trailing blanks, tabs, newlines */
int trim(char s[])
{
int n;
for (n = strlen(s)-1; n >= 0; n--)
if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
break;
s[n+1] = '\0';
return n;
}
strlen returns the length of the string. The for loop starts at the end and scans backwards looking
for the first character that is not a blank or tab or newline. The loop is broken when one is found,
or when n becomes negative (that is, when the entire string has been scanned). You should verify
that this is correct behavior even when the string is empty or contains only white space
characters.
The continue statement is related to break, but less often used; it causes the next iteration of the
enclosing for, while, or do loop to begin. In the while and do, this means that the test part is
executed immediately; in the for, control passes to the increment step. The continue statement
applies only to loops, not to switch. A continue inside a switch inside a loop causes the next loop
iteration.
As an example, this fragment processes only the non-negative elements in the array a; negative
values are skipped.
for (i = 0; i < n; i++)
if (a[i] < 0) /* skip negative elements */
continue;
... /* do positive elements */
The continue statement is often used when the part of the loop that follows is complicated, so
that reversing a test and indenting another level would nest the program too deeply.
 Summary:

In this lesson we've learned the following:


 A combination of constants, variables, and operators is called an expression in the C
language. An expression is used to denote different computations.
 The arithmetic operators include +, -, *, /, and %.
 A function body contains variable declarations and statements. Usually, a function should
accomplish just one task.
 Looping can be used to perform the same set of statements over and over until specified
conditions are [Link] makes your program concise.
 There are three statements, for, while, and do-while, that are used for looping in C.
 The empty for( ; ; ) statement can be used to form an infinite loop.
 There is only one expression field in the while statement, and the expression is used as
the specified condition.
 The while statement does not end with a semicolon.
 The do-while statement places its expression at the bottom of the loop.
 The do-while statement does end with a semicolon.
 Review Questions:
Q.1 Explain with example, if….else control construct in C?
Q.2 How is while loop is different from do…while loop?
Q.3 Write a C program to calculate the sum of all numbers from 0 to 100 that are
divisible by 4.

 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

Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]


Course Code: CSE 101 E Subject: FCPC Unit: III

Topic: Basic types, arrays, functions, including recursive Lecture


functions required

INTRODUCTION:

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.
C also allows programmers to define their own functions for carrying
out various individual tasks. 2
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.

CONTENTS:

13.1 What Is An Array?


13.1.1 Types Of Arrays
[Link] One Dimensional Array
[Link] Two Dimensional Array
[Link] Multi dimensional Array
13.2 Functions
13.2.1 Passing Argument To A Function
13.3 Function Prototypes And Recursion
UNIT-3 LESSON-13

13.1 What Is An Array?

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.

13.1.1 Types of Arrays:


1. One dimension array (Also known as 1-D array).
2. Two dimension array (Also known as 2-D array).
3. Multi-dimension array.

[Link] One Dimensional Array


 Declaration of One Dimensional Arrays:
Syntax: data_type array_name[width];
Example: int roll[8];
In our example, int specifies the type if the variable, roll specifies the name of the variable and
the value in bracket [8] is new for newbie. The bracket ([ ]) tells compiler that it is an array and
number mention in the bracket specifies that how many elements (values in any array is called
elements) it can store. This number is called dimension of array.
Figure 13.1 1-D Array Arrangement

 C Array Assignment and Initialization


We can initialize and assign values to the arrays in the same way as we do with variable. We can
assign value to an array at the time of declaration or during runtime. Let’s look at each approach.
Syntax: data_type array_name[size]={list of values};
Example:
int arr[5]={1,2,3,4,5};
int arr[]={1,2,3,4,5};
In our above array example we have declared an integer array and named it “arr” which can hold
5 elements, we are also initializing arrays in the same time.
Both statements in our example are valid method to declare and initialize single dimension array.
In our first example we mention the size (5) of an array and assigned it values in curly brace,
separating element’s value by comma (,). But in second example we left the size field blank but
we provided its element’s value. When we only give element values without providing size of an
array then C compiler automatically assumes its size from given element values.
There is one more method to initialize array C programming; in this method we can assign
values to individual element of an array. For this let’s look at example:

 Array Initialization Example


#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5],i;
clrscr();
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;
printf("Value in array arr[0] : %d\n",arr[0]);
printf("Value in array arr[1] : %d\n",arr[1]);
printf("Value in array arr[2] : %d\n",arr[2]);
printf("Value in array arr[3] : %d\n",arr[3]);
printf("Value in array arr[4] : %d\n",arr[4]);
printf("\n");
for(i=0;i<5;i++)
{
printf("Value in array arr[%d] : %d\n",i,arr[i]);
}
getch();
}

[Link] Two Dimensional Arrays in C


Syntax : data_type array_name[row][column];
For example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
int a[2][2]={{11,12},{21,22}};

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
} getch();
}

[Link] Multidimensional Arrays


A multidimensional array has more than one subscript. A two-dimensional array has two
subscripts, a three-dimensional array has three subscripts, and so on. There is no limit to the
number of dimensions a C array can have. For example, you might write a program that plays
checkers. The checkerboard contains 64 squares arranged in eight rows and eight columns. Your
program could represent the board as a two-dimensional array, as follows:
int checker[8][8];
The resulting array has 64 elements:
checker[0][0], checker[0][1],
checker[0][2]...checker[7][6], checker[7][7].
Similarly, a three-dimensional array could be thought of as a cube. Four-dimensional arrays (and
higher) are probably best left to your imagination. All arrays, no matter how many dimensions
they have, are stored sequentially in memory.
For example:
#include <stdio.h>
#include <stdio.h>
int main ()
{
int value [10] [10] [10] ,i,j,k; // Declaring an Array
for (k = 0; k<10; k++)
{
for (j = 0; j<10; j++)
{
for (i = 0; i<10; i++)
{
value [k] [j] [i] = k*10+j*10+i; // Loading the Array
}}}
for (k = 0; k<10; k++)
{
for (int j = 0; j<100; j++)
{
for (int i = 0; i<100; i++)
{
printf ("\n%d",value [k] [j] [i]); // Displaying the Array
}}}
return 0;
}

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.

13.2.1 Defining a Function


Function is a self-contained program segment that carries out some specific well-defined task.
Every C program consists of one or more functions. The most important function is main.
Program execution will always begin by carrying out the instruction in main. The definitions of
functions may appear in any order in a program file because they are independent of one another.
A function can be executed from anywhere within a program. Once the function has been
executed, control will be returned to the point from which the function was accessed.
Functions contain special identifiers called parameters or arguments through
which information is passed to the function and from functions information is returned via the
return statement. It is not necessary that every function must return information, there are some
functions also which do not return any information for example the system defined function
printf. Before using any function it must be defined in the program.
Function definition has three principal components: the first line, the parameter
declarations and the body of the functions. The first line of a function definition contains the data
type of the information return by the function, followed by function name, and a set of arguments
or parameters, separated by commas and enclosed in parentheses. The set of arguments may be
skipped over. The data type can be omitted if the function returns an integer or a character. An
empty pair of parentheses must follow the function name if the function definition does not
include any argument or parameters.

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.

13.3 Function Prototypes and Recursion


Many C compilers permits each of the argument data types within a function declaration to be
followed by an argument name, that is data-type function name (type1 argument 1, type 2
argument2… type n argument n); Function declarations written in this form are called function
prototypes. Function prototypes are desirable, however, because they further facilitate error
checking between the calls to a function and the corresponding function definition.
Some of the function prototypes are given below:
int example (int, int); or int example (int a, int b);
void example 1(void); or void example 1(void);
void fun (char, long); or void fun (char c, long f );

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

Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]


Course Code: CSE 101 E Subject: FCP C Unit: III

Topic: Program organization: local and external variables and Lecture


scope & arrays required

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:

14.1 Local Variables


14.2 External Variable
14.3 Scope, Lifetime And The Static Keyword
UNIT-3 LESSON-14

14.1 LOCAL VARIABLES


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. Here is an example of four local variables being declared within a function:
int func1(int y)
{
int a, b = 10;
float rate;
double cost = 12.55;
/* function code goes here... */
}
The preceding declarations create the local variables a, b, rate, and cost, which can be used by
the code in the function. The function parameters are considered to be variable declarations, so
the variables, if any, in the function's parameter list also are available. When you declare and use
a variable in a function, it is totally separate and distinct from any other variables that are
declared elsewhere in the program. This is true even if the variables have the same name.
A demonstration of local variables.:
/* Demonstrates local variables. */
#include <stdio.h>
int x = 1, y = 2;
void demo(void);
main()
{
printf("\nBefore calling demo(), x = %d and y = %d.", x, y);
demo();
printf("\nAfter calling demo(), x = %d and y = %d\n.", x, y);
return 0;
}
void demo(void)
{
/* Declare and initialize two local variables. */
int x = 88, y = 99;
/* Display their values. */
printf("\nWithin demo(), x = %d and y = %d.", x, y);
}

Before calling demo(), x = 1 and y = 2.


Within demo(), x = 88 and y = 99.
After calling demo(), x = 1 and y = 2.

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.

14.2 External Variable


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.

 Definition, declaration and the extern keyword:


To understand how external variables relate to the extern keyword, it is necessary to know the
difference between defining and declaring a variable. 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. The
declaration informs the compiler that a variable by that name and type exists, but the compiler
need not allocate memory for it since it is allocated elsewhere.

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>

int i; /* i is an external variable */

void print_count(void)

printf("T minus %d and counting\n", i);

int main(void)

{
for (i = 10; i > 0; --i)

print_count();

return 0;

14.3 Scope, Lifetime and the Static Keyword


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.

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.

15.1.1 The general form of declaration of String variable is -


char name [size];
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";
Also a string variable though can be accesed (Input/Output) character by character using a loop
but generally they are not. The reason being that both printf and scanf provides a simple way of
string input/ouput using a %s specifier.
Also string manipulation can be done very easily using some predefined functions available in
header <string.h>.

15.1.2 General form of declaration of Array of string is -


char name [SIZE1] [SIZE2];
Here SIZE1 indicates the number of strings each having a maximum length of SIZE2.
Basic functionality of Arrays of String can be seen in C Source Code Below.
#include <stdio.h>
#include <string.h>
int main ()
{
char name [5] [100] = { "Jitesh Banga", "Rohit Goyal", "Nalin Diwan", "Mukesh Kumar",
"Manish Jain"}
char input [100] = "None";
int i;
while (1)
{
printf ("\nEnter Name : ");
scanf ("%s", &input);
for ( i = 0; i<5; i++)
{
if (!strcmp (input, name [i])
{
printf ("\nWelcome %s", name [i]);
break;
} }
printf ("\nInvalid User, Access Denied");
}
return 0;
}

15.2 String Literals


String literals are described by the following lexical definitions:
stringliteral ::= [stringprefix](shortstring | longstring)
stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''"
| '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | escapeseq
longstringitem ::= longstringchar | escapeseq
shortstringchar ::= <any source character except "\" or newline or the quote>
longstringchar ::= <any source character except "\">
escapeseq ::= "\" <any ASCII character>
One syntactic restriction not indicated by these productions is that whitespace is not allowed
between the string prefix and the rest of the string literal. The source character set is defined by
the encoding declaration; it is ASCII if no encoding declaration is given in the source file.

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:

Escape Sequence Meaning


\newline Ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh

Figure 15.1 Escape Sequences

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

15.3 String Variables

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

16.2 Application of A String


16.2.1 The Strlen( ) Function
16.2.2 Copying Strings With Strcpy( )
16.2.3 The Gets( ) And Puts( ) Functions
16.2.4 The Scanf( ) Function
UNIT-IV LESSON-16

16.1 Arrays of Strings


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. We
can declare a two dimensional character array of MAX strings of size SIZE as follows:

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.";

16.2 Application of a String


16.2.1 The strlen( ) Function
The syntax for the strlen( ) function is
#include <string.h>
size_t strlen(const char *s);
Here s is a char pointer variable. The return value from the function is the number of bytes.
size_t is a data type defined in the string.h header file. The size of the data type depends on the
particular computer system. Note that string.h has to be included in your program before you can
call the strlen( ) function.

16.2.2 Copying Strings with strcpy( )


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() to do
the job for us.
The syntax for the strcpy( function is
#include <string.h>
char *strcpy(char *dest, const char *src);
Here the content of the string src is copied to the array referenced by dest. The strcpy( ) function
returns the value of src if it is successful. The header file string.h must be included in our
program before the strcpy( ) function is called.

Reading and Writing Strings


Now let's focus on how to read or write strings with the standard input and output streams—that
is, stdin and stdout. In C, there are several functions we can use to deal with string reading or
writing. The following subsections introduce some of the functions.

16.2.3 The gets( ) and puts( ) Functions


The gets( ) function can be used to read characters from the standard input stream.
The syntax for the gets( ) function is
#include <stdio.h>
char *gets(char *s);
Here the characters read from the standard input stream are stored in the character array
identified by s. The gets( ) function stops reading, and appends a null character \0 to the array,
when a newline or end-of-file (EOF) is encountered. The function returns s if it concludes
successfully. Otherwise, a null pointer is returned. The puts( ) function can be used to write
characters to the standard output stream (that is, stdout).
The syntax for the puts( ) function is
#include <stdio.h>
int puts(const char *s);
Here s refers to the character array that contains a string. The puts( ) function writes the string to
the stdout. If the function is successful, it returns 0. Otherwise, a nonzero value is returned. The
puts( ) function appends a newline character to replace the null character at the end of a character
array. Both the gets( ) and puts( ) functions require the header file stdio.h.

16.2.4 The scanf( ) Function


The scanf( ) function provides another way to read strings from the standard input stream.
Moreover, this function can actually be used to read various types of input data. The formats of
arguments to the scanf( ) function are quite similar to those used in the printf( ) function.
The syntax for the scanf( ) function is
#include <stdio.h>
int scanf(const char *format, …);
Here various format specifiers can be included inside the format string referenced by the char
pointer variable format. If the scanf( ) function concludes successfully, it returns the num-ber of
data items read from the stdin. If an error occurs, the scanf( ) function returns EOF (end-of-file).

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

GALAXY GLOBAL GROUP OF INSTITUTIONS


Dinarpur, (Ambala)
LESSON NOTE- L-17
Faculty/Author: Sonam Dhawan S e me s te r : I Class: [Link]
Course Code: CSE 101 E Subject: FCPC Unit: IV
Lecture
Topic:Structures, Unions and Enumerations , Structure required

variables and operations on structures

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

17.2 What Is Union?


17.3 C Enumeration Declarations
17.3.1 Syntax Of Enumeration Declaration
17.4 Operations On Structures
UNIT-IV LESSON-17

17.1 What Is A Structure?


In C, a structure collects different data items in such a way that they can be referenced as a single
unit. There are several major differences between an array and a structure. Besides the fact that
data items in a structure can have different types, each data item has its own name instead of a
subscript value. In fact, data items in a structure are called fields or members of the structure.

17.1.1 Declaring Structures


The general form to declare a structure is
struct struct_tag {
data_type1 variable1;
data_type2 variable2;
data_type3 variable3;
. .
.
};
Here struct is the keyword used in C to start a structure declaration. struct_tag is the tag name of
the structure. variable1, variable2, and variable3 are the members of the structure. Their data
types are specified respectively by data_type1, data_type2, and data_type3. The declarations of
the members have to be enclosed within the opening and closing braces ({ and }) in the structure
declaration, and a semicolon (;) has to be included at the end of the declaration.
The following is an example of a structure declaration:
struct automobile {
int year;
char model[8];
int engine_power;
float weight;
};
Here struct is used to start a structure declaration. automobile is the tag name of the structure. In
this example, there are three types of variables, char, int, and float. The variables have their own
names, such as year, model, engine_power, and weight.

17.1.2 Defining Structure Variables


After declaring a structure, we can define the structure variables. For instance, the following
structure variables are defined with the structure data type of automobile from the previous
section:
struct automobile sedan, pick_up, sport_utility;
Here three structure variables, sedan, pick_up, and sport_utility, are defined by the structure of
automobile. All three structure variables contain the four members of the structure data type of
automobile.
Also, we can combine the structure declaration and definition into one statement like this:
struct automobile {
int year;
char model[8];
int engine_power;
float weight;
} sedan, pick_up, sport_utility;
Here three structure variables, sedan, pick_up, and sport_utility, are defined with the structure
data type of automobile in the single statement.

17.2 What Is Union?


Unions like structure contain members whose individual data types may differ from one another.
However the members that compose a union all share the same storage area within the
computer’s memory where as each member within a structure is assigned its own unique storage
area. Thus unions are used to observe memory. They are useful for application involving
multiple members. Where values need not be assigned to all the members at any one time. Like
structures union can be declared using the keyword union as follows:
union item
{
int m;
float p;
char c;
}
code;
this declares a variable code of type union item. The union contains three members each with a
different data type. However we can use only one of them at a time. This is because if only one
location is allocated for union variable irrespective of size. The compiler allocates a piece of
storage that is large enough to access a union member we can use the same syntax that we use to
access structure members. That is
code.m
code.p
code.c
are all valid member variables. During accessing we should make sure that we are accessing the
member whose value is currently stored.
For example a statement such as
code.m=456;
code.p=456.78;
printf(“%d”,code.m);
Would prodece erroneous result.
In effect a union creates a storage location that can be used by one of its members at a time.
When a different number is assigned a new value the new value supercedes the previous
members value. Unions may be used in all places where a structure is allowed. The notation for
accessing a union member that is nested inside a structure remains the same as for the nested
structure.

17.3 C Enumeration Declarations

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
(called the "enumeration set," "enumerator constants," "enumerators," or "members"). A variable
with enumeration type stores one of the values of the enumeration set defined by that type.

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.

17.3.1 Syntax of enumeration declaration


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

enum identifier { enumerator-list }

17.4 Operations on Structures


There is a relatively small number of operations which C directly supports on structures. As
we've seen, we can define structures, declare variables of structure type, and select the members
of structures. We can also assign entire structures: the expression
c1 = c2
would assign all of c2 to c1 (both the real and imaginary parts, assuming the preceding
declarations). We can also pass structures as arguments to functions, and declare and define
functions which return structures. But to do anything else, we typically have to write our own
code (often as functions). For example, we could write a function to add two complex numbers:
struct complex
cpx_add(struct complex c1, struct complex c2)
{
struct complex sum;
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
return sum;
}
We could then say things like
c1 = cpx_add(c2, c3)

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 {}:

struct complex c1 = {1, 2};


struct complex c2 = {3, 4};
Of course, the type of each initializer in the list must be compatible with the type of the
corresponding structure member.

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

18.4 What are Nested Structures In C?

18.4.1 Structures Within Structures (Nested Structures)

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.

18.3 Structured Data Types


To construct a new structured data type struc_typein a program, we use several TYPES
statements:
TYPES BEGIN OF struc_type.
...
{TYPES dtype ...} | {INCLUDE {TYPE|STRUCTURE} ...}.
...
TYPES END OF struc_type.
The two TYPES statements with the additions BEGIN OF und END OFmay enclose as many
TYPESstatements as required, including additional complete structure definitions, as well as the
statements INCLUDE TYPE and INCLUDE STRUCTURE. This way you can create nested
structures.
The individual components of a structured data type are addressed in the program with the
structure component selector (-) between the structure name and component name as follows:
struc_type-dtype.
For more information, refer to the keyword documentation.
TYPES: spfli_type TYPE spfli,
surname(20) TYPE c,
BEGIN OF address,
name TYPE surname,
street(30) TYPE c,
city TYPE spfli_type-cityfrom,
END OF address,
town TYPE address-city.
This example shows the definition of two structure types in a program - spfli_type and address.
The structure of the data type spfli_type is taken from the database table SPFLI in the ABAP
Dictionary. The components of spfli_type are the same as the columns of SPFLI. The individual
data types of the components are the ABAP equivalents of the data types of the columns of the
database table. The structure type address is newly defined. The component address-name takes
the data type of the previously defined type surname, the component address-street is newly
defined, address-city takes the data type of column cityfrom of the structure type spfli_type.

18.4 What are Nested Structures In C?


Structures can contain other structures as members; in other words, structures can nest. Consider
the following two structure types:
struct first_structure_type { int member_of_1; };
struct second_structure_type{ double double_member;
struct first_structure_type first_struct_member; };
The first structure type is incorporated as a member of the second structure type.
We can initialize a variable of the second type as follows:
struct second_structure_type second_struct_member;
second_struct_member.double_member = 12345.6789;
second_struct_member.first_struct_member.integer_member_of_1 = 5;
The member operator . is used to access members of structures that are themselves members of a
larger structure. No parentheses are needed to force a special order of evaluation; a member
operator expression is simply evaluated from left to right.

18.4.1 Structures within Structures (Nested Structures) :


Structures can be used as structures within structures. It is also called as 'nesting of structures'.
Syntax:

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

Standard library: Input / output

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

19.1 C Enumeration Declarations


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
(called the "enumeration set," "enumerator constants," "enumerators," or "members"). A variable
with enumeration type stores one of the values of the enumeration set defined by that type.

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:

enum DAY /* Defines an enumeration type */

{ saturday, /* Names day and declares a */

sunday = 0, /* variable named workday with */


monday, /* that type */
tuesday,
wednesday, /* wednesday is associated with 3 */
thursday,
friday
} workday;
The value 0 is associated with saturday by default. The identifier sunday is explicitly set to 0.
The remaining identifiers are given the values 1 through 5 by default.

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.

19.2.4 Iterator Tags


The forEach tag allows you to iterate over a collection of objects. You specify the collection via
the items attribute, and the current item is available through a scope variable named by the item
attribute.
A large number of collection types are supported by forEach, including all implementations of
[Link] and [Link]. If the items attribute is of type [Link], then the
current item will be of type [Link], which has the following properties:

 key - the key under which the item is stored in the underlying Map
 value - the value that corresponds to the key

19.2.5 URL Tags


The jsp:include element provides for the inclusion of static and dynamic resources in the same
context as the current page. However, jsp:include cannot access resources that reside outside of
the Web application and causes unnecessary buffering when the resource included is used by
another element.

19.3 Data Types in C

C has different data types for different types of data and can be broadly classified as:
1. Primary Data Types
2. Secondary Data Types

Figure 19.2 Data types in C


19.3.1 Primary Data Types
Integer Data Types:
Integers are whole numbers with a range of values, range of values are machine dependent.
Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to
+32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for
number. To control the range of numbers and storage space, C has three classes of integer
storage namely short int, int and long int. All three data types have signed and unsigned forms. A
short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned
integers are always positive and use all the bits for the magnitude of the number. Therefore, the
range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a
longer range of values and it occupies 4 bytes of storage space.
Syntax:
int <variable name>;
int num1;
short int num2;
long int num3;
Example: 5, 6, 100, 2500.

Figure 19.3 Integer Data Type Memory Allocation:


Floating Point Data Types
The float data type is used to store fractional numbers (real numbers) with 6 digits of precision.
Floating point numbers are denoted by the keyword float. When the accuracy of the floating
point number is insufficient, we can use the double to define the number. The double is same as
float but with longer precision and takes double space (8 bytes) than float. To extend the
precision further we can use long double which occupies 10 bytes of memory space.
Syntax:
float <variable name>;
float num1;
double num2;
long double num3;
Example: 9.125, 3.1254.

Figure 19.4 Floating Point Data Type Memory Allocation

Character Data Type:


Character type variable can hold a single character and are declared by using the keyword char.
As there are singed and unsigned int (either short or long), in the same way there are signed and
unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have
values between 0 and 255, signed characters have values from –128 to 127.

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

Syntax : type var_name[size];

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.

19.4 The Standard Library Functions


Some of the "commands" in C are not really "commands" at all but are functions. For example,
we have been using printf and scanf to do input and output, and we have used rand to generate
random numbers - all three are functions.

A list of the most common libraries and a brief description of the most useful functions they
contain follows:

1. stdio.h: I/O functions:


1. getchar() returns the next character typed on the keyboard.
2. putchar() outputs a single character to the screen.
3. printf() as previously described
4. scanf() as previously described
2. string.h: String functions
1. strcat() concatenates a copy of str2 to str1
2. strcmp() compares two strings
3. strcpy() copys contents of str2 to str1
3. ctype.h: Character functions
1. isdigit() returns non-0 if arg is digit 0 to 9
2. isalpha() returns non-0 if arg is a letter of the alphabet
3. isalnum() returns non-0 if arg is a letter or digit
4. islower() returns non-0 if arg is lowercase letter
5. isupper() returns non-0 if arg is uppercase letter
4. math.h: Mathematics functions
1. acos() returns arc cosine of arg
2. asin() returns arc sine of arg
3. atan() returns arc tangent of arg
4. cos() returns cosine of arg
5. exp() returns natural logarithm
6. fabs() returns absolute value of num
7. sqrt() returns square root of num
5. time.h: Time and Date functions
1. time() returns current calendar time of system
2. difftime() returns difference in secs between two times
3. clock() returns number of system clock cycles since program execution
6. stdlib.h: Miscellaneous functions
1. malloc() provides dynamic memory allocation, covered in future sections
2. rand() as already described previously
3. srand() used to set the starting point for rand()

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

20.1.1 Basic I/O


There are a couple of function that provide basic I/O facilities. Probably the most common are:
getchar( ) and putchar( ). They are defined and used as follows:

 int getchar(void) -- reads a char from stdin


 int putchar(char ch) -- writes a char to stdout, returns character written.

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.

int fflush(FILE *stream);


Flushing an output stream causes any unwritten data in the buffer to be written. On an input
stream, the effect is undefined (but usually clears the buffer). The return value is normally zero,
or EOF for a write error.

int fclose(FILE *stream);


This closes stream. For an output stream, any buffered data is first written. For an input stream,
any unread data is discarded. It normally returns zero, or EOF for an error.

int remove(const char *filename);


This deletes the file filename. It normally returns zero, or non-zero for an error.

int rename(const char *oldname, const char *newname);


This renames the file oldname to newname. It normally returns zero, or non-zero for an error.

int fprintf(FILE *stream, const char *format, ...);


This acts exactly like printf except that the data is written to stream, rather than stdout. It
normally returns the number of characters written, or a negative value for an error.

int fscanf(FILE *stream, const char *format, ...);


This acts exactly like scanf except that the data is read from stream, rather than stdin. It normally
returns the number of input items converted and assigned, or EOF for an error.

int fgetc(FILE *stream);


This normally returns the next character read from stream (as an int), or EOF for an error. (The
char is converted to an int because EOF is usually -1, while unsigned char is usually from 0 to
255 so could not be used to return EOF.)

char *fgets(char *s, int n, FILE *stream);


This reads a maximum of n - 1 characters into the array s. It stops if a newline ('\n') is found. The
newline is included in the array. The array is terminated by the null character '\0'. It returns s (a
pointer-to-char), or NULL for an error.

int fputc(int c, FILE *stream);


This writes the character c (converted to unsigned char) to stream. It normally returns c, or EOF
for an error.

int fputs(const char *s, FILE *stream);


This writes string s to stream. (Note: unlike puts, fputs does not add a newline '\n' to the end of
s.) It normally returns a non-negative value, or EOF for an error.

void rewind(FILE *stream);


This "rewinds" stream back to the start of the file. It does not return a value.

int feof(FILE *stream);


This normally returns zero, or non-zero if the end-of-file marker for stream has been reached.
20.3 Formatted I/O

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

20.3.1 Formatted I/O Operations in C


C is not equipped with read and write statements. Instead, a set of functions is provided for
formatted I/O.
The scanf, sscanf and fscanf Functions
The scanf, sscanf and fscanf functions all uses the same formats for the input variables. The
function scanf reads interactively from the CRT terminal, sscanf reads from a string variable
which contains the input and fscanf reads from a file. To call these functions, use
scanf(format,argument list);
sscanf(string,format,argument list);
fscanf(file pointer,format,argument list);
in which format is a character string which contains all the specifications to be used for reading
the data, e.g., %f for floating numbers and %d for decimal integers, etc. argument list is a list of
pointers which direct the converted data into a memory location. If a memory location is
identified by a variable name x, then the pointer must be written &x. String is a the string which
contains the data to be read from. It is sometimes convenient to read an entire string from the
terminal and then read from that string on one or several occasions. file pointer is the identifier of
type FILE for an opened file; it was assigned to a file using the fopen statement.

The printf, sprintf and fprintf Functions


The printf, sprintf and fprintf functions all uses the same formats for output variables. The
function printf writes to the CRT terminal, sprintf writes to a string variable and fprintf writes to
a file. To call these functions, use
printf(format,argument list);
sprintf(string,format,argument list);
fprintf(file pointer,format,argument list);
in which format, string and file pointer all have the same meanings as those defined above.
The argument list, on the other hand, does not required pointers, just the values.

The fopen Function


To do input/output from a file, rather than the terminal, the file must be “opened” before any
“read” or “write” can be performed. The fopen function can be called by
fp=fopen(name,mode);
in which fp is the file pointer to be used later for referencing a file when fscanf or fprintf is used.
fp must be declared as FILE *fp at the beginning of the program name is the name of the file to
be opened. mode is "r" for read, "w" for write and "a" for append.

20.4 Character I/O


A number of functions provide for character oriented I/O. Their declarations are:

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

20.4.1 Character input


These read an unsigned char from the input stream where specified, or otherwise stdin. In each
case, the next character is obtained from the input stream. It is treated as an unsigned char and
converted to an int, which is the return value. On End of File, the constant EOF is returned, and
the end-of-file indicator is set for the associated stream. On error, EOF is returned, and the error
indicator is set for the associated stream. Successive calls will obtain characters sequentially. The
functions, if implemented as macros, may evaluate their stream argument more than once, so do
not use side effects here.

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.

20.4.2 Character output


These are identical in description to the input functions already described, except performing
output. They return the character written, or EOF on error. There is no equivalent to End of File
for an output file.

20.5 String Input/Output


20.5.1 String Input

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.

20.5.2 String output


These write strings to the output file; stream where specified, otherwise stdout. The terminating
null is not written. Non-zero is returned on error, zero otherwise. Beware: puts appends a
newline to the string output; fputs does not!
Summary
In this lesson we've learned the following:
 Different kind of library functions in the C language.
 Input and Output streams used in c language.
 A Stream is a file or a physical device which is manipulated with a pointer to the stream.
 A library function is a function that can be called by a program to perform some task, but
it is not part of the program itself.
 Different kind of File operations in the C language.
 Formatted Input and Output functions used in c language.
 Character I/O and line I/O implemented in C.
 String function used in C language.
Review Question
Ques.1 What is the streams and write down the main functions of streams?
Sol: See page
Ques.2 Explain all type of file operations in C language?
Sol: See page
Ques.3 What is the main difference between formatted I/O and character I/O? (KUK)
Sol: See page
Ques.4 Explain the string I/O with a suitable 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-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

21.1 C Standard Library


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. The C standard library provides macros, type definitions, and functions for tasks
like string handling, mathematical computations, input/output processing, memory allocation and
several other operating system services.

21.1.1 Header files


The application programming interface (API) of the C standard library is declared in a number of
header files. Each header file contains one or more function declarations, data type definitions,
and macros.

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

Contains the assert macro, used to assist with detecting logical


<assert.h> errors and other types of bug in debugging versions of a
program.

<complex.h> A set of functions for manipulating complex numbers.

<ctype.h> Defines set of functions used to classify characters by their


types or to convert between upper and lower case in a way that
Name Description

is independent of the used character set (typically ASCII or one


of its extensions, although implementations utilizing EBCDIC
are also known).

<errno.h> For testing error codes reported by library functions.

Defines a set of functions for controlling floating-point


<fenv.h>
environment.

Defines macro constants specifying the implementation-


<float.h>
specific properties of the floating-point library.

<inttypes.h> Defines exact width integer types.

Defines several macros that are equivalent to some of the


<iso646.h> operators in C. For programming in ISO 646 variant character
sets.

Defines macro constants specifying the implementation-


<limits.h>
specific properties of the integer types.

<locale.h> Defines localization functions.

<math.h> Defines common mathematical functions.

Declares the macros setjmp and longjmp, which are used for
<setjmp.h>
non-local exits.

<signal.h> Defines signal handling functions.

<stdalign.h> For querying and specifying the alignment of objects.

For accessing a varying number of arguments passed to


<stdarg.h>
functions.
Name Description

<stdatomic.h> For atomic operations on data shared between threads.

<stdbool.h> Defines a boolean data type.

<stddef.h> Defines several useful types and macros.

<stdint.h> Defines exact width integer types.

<stdio.h> Defines core input and output functions

Defines numeric conversion functions, pseudo-random


<stdlib.h> numbers generation functions, memory allocation, process
control functions

<stdnoreturn.h> For specifying non-returning functions.

<string.h> Defines string handling functions.

<tgmath.h> Defines type-generic mathematical functions.

Defines functions for managing multiple Threads as well as


<threads.h>
mutexes and condition variables.

<time.h> Defines date and time handling functions

<uchar.h> Types and functions for manipulating Unicode characters.

<wchar.h> Defines wide string handling functions.

Defines set of functions used to classify wide characters by


<wctype.h>
their types or to convert between upper and lower case

Three of the header files (complex.h, stdatomic.h, threads.h) are conditional features that
implementations need not support.

21.2 Error Handling


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

21.2.1 Types of errors in C language.


Errors in C can be of following types:
1. Syntax Errors: Errors in syntax(grammar) of the program.
2. Semantic Errors: Errors in the meaning of the program.
3. Logical Errors: Errors in logic of the program. Compiler cannot diagnose these kind of
errors.
4. Runtime Errors:
i) Insufficient memory
ii)Segmentation fault
iii)Floating exception
5. Compile Errors:
i) parse error
ii) implicit declaration
iii) no matching function
iv) Unsatisfied symbols
v) incomplete type
vi) cannot call member function
vii) bad argument
viii) cannot allocate an object.

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

You might also like