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

Complete CP Notes

This document provides an overview of computer programming and the basic components and functions of a computer system. It discusses that a computer consists of four main units: an input unit, storage unit, central processing unit, and output unit. The central processing unit is further broken down into an arithmetic logic unit and control unit. The document also describes different types of computer memory, input and output devices, and provides examples of each.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
483 views

Complete CP Notes

This document provides an overview of computer programming and the basic components and functions of a computer system. It discusses that a computer consists of four main units: an input unit, storage unit, central processing unit, and output unit. The central processing unit is further broken down into an arithmetic logic unit and control unit. The document also describes different types of computer memory, input and output devices, and provides examples of each.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 91

Computer Programming

1.1 Computer: It is an electronic machine which performs following major operations or functions

Accepts data or instructions as input,

Stores data and instruction

Processes data as per the instructions,

Controls all operations inside a computer, and

Gives results in the form of output.


Therefore it consists of mainly four basic units; namely input unit, storage unit, central processing unit and output unit. Central
Processing unit further includes Arithmetic logic unit and control unit, as shown in the figure.

Functional Units:

a. Input Unit: This unit is used for entering data and programs into the computer system by the user for processing e.g.
Keyboard, Mouse etc.

b. Storage Unit: The storage unit is used for storing data and instructions before and after processing

e.g. RAM, Hard Disk etc.

c. Output Unit: The output unit is used for storing the result as output produced by the computer after processing e.g.
Monitor, Printer etc.

d. Processing: The task of performing operations like arithmetic and logical operations is called processing. The Central
Processing Unit (CPU) takes data and instructions from the storage unit and makes all sorts of calculations based on the
instructions given and the type of data provided. It is then sent back to the storage unit. CPU includes Arithmetic logic unit (ALU)
and control unit (CU)
1
Arithmetic Logic Unit: All calculations and comparisons, based on the instructions provided, are carried out within the ALU. It
performs arithmetic functions like addition, subtraction, multiplication, division and also logical operations like greater than, less
than and equal to etc.

Control Unit: Controlling of all operations like input, processing and output are performed by control unit. It takes care of step
by step processing of all operations inside the computer.

Memory
Computers memory can be classified into two types; primary memory and secondary memory

a. Primary Memory can be further classified as RAM and ROM.

RAM or Random Access Memory is the unit in a computer system. It is the place in a computer where the operating system,
application programs and the data in current use are kept temporarily so that they can be accessed by the computers processor. It
is said to be volatile since its contents are accessible only as long as the computer is on. The contents of RAM are no more
available once the computer is turned off.

ROM or Read Only Memory is a special type of memory which can only be read and contents of which are not lost even when
the computer is switched off. It typically contains manufacturers instructions. Among other things, ROM also stores an initial
program called the bootstrap loader whose function is to start the operation of computer system once the power is turned on.

b. Secondary Memory

RAM is volatile memory having a limited storage capacity. Secondary/auxiliary memory is storage other than the RAM. These
include devices that are peripheral and are connected and controlled by the computer to enable permanent storage of programs and
data.

CD ROM
Secondary storage devices are of two types; magnetic and optical. Magnetic devices include hard disks and optical storage devices
are CDs, DVDs, Pen drive, Zip drive etc.

Hard Disk

Hard disks are made up of rigid material and are usually a stack of metal disks sealed in a box. The hard disk and the hard disk
drive exist together as a unit and is a permanent part of the computer where data and programs are saved. These disks have storage
capacities ranging from 1GB to 80 GB and more. Hard disks are rewritable.

Compact Disk

Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB. It can hold large amount of information
such as music, full-motion videos, and text etc. CDs can be either read only or read write type.

Digital Video Disk

Digital Video Disk (DVD) is similar to a CD but has larger storage capacity and enormous clarity. Depending upon the disk type it
can store several Gigabytes of data. DVDs are primarily used to store music or movies and can be played back on your television
or the computer too. These are not rewritable.

Input / Output Devices:


These devices are used to enter information and instructions into a computer for storage or processing and to deliver the processed
data to a user. Input/Output devices are required for users to communicate with the computer. In simple terms, input devices bring

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

Input Devices
An input device is any device that provides input to a computer. There are many input devices, but the two most common ones are
a keyboard and mouse. Every key you press on the keyboard and every movement or click you make with the mouse sends a
specific input signal to the computer.

Keyboard: The keyboard is very much like a standard typewriter keyboard with a few additional keys. The basic QWERTY
layout of characters is maintained to make it easy to use the system. The additional keys are included to perform certain special
functions. These are known as function keys that vary in number from keyboard to keyboard.

Mouse: A device that controls the movement of the cursor or pointer on a display screen. A mouse is a small object you can roll
along a hard and flat surface. Its name is derived from its shape, which looks a bit like a mouse. As you move the mouse, the
pointer on the display screen moves in the same direction.

Trackball: A trackball is an input device used to enter motion data into computers or other electronic devices. It serves the same
purpose as a mouse, but is designed with a moveable ball on the top, which can be rolled in any direction.

Touchpad: A touch pad is a device for pointing (controlling input positioning) on a computer display screen. It is an alternative
to the mouse. Originally incorporated in laptop computers, touch pads are also being made for use with desktop computers. A
touch pad works by sensing the users finger movement and downward pressure. Touch Screen: It allows the user to
operate/make selections by simply touching the display screen. A display screen that is sensitive to the touch of a finger or stylus.
Widely used on ATM machines, retail point-of-sale terminals, car navigation systems, medical monitors and industrial control
panels.

Light Pen: Light pen is an input device that utilizes a light-sensitive detector to select objects on a display screen.

Magnetic ink character recognition (MICR): MICR can identify character printed with a special ink that contains particles of
magnetic material. This device particularly finds applications in banking industry.

Optical mark recognition (OMR): Optical mark recognition, also called mark sense reader is a technology where an OMR
device senses the presence or absence of a mark, such as pencil mark. OMR is widely used in tests such as aptitude test.

Bar code reader: Bar-code readers are photoelectric scanners that read the bar codes or vertical zebra strips marks, printed on
product containers. These devices are generally used in super markets, bookshops etc.

Scanner

Scanner is an input device that can read text or illustration printed on paper and translates the information into a form that
the computer can use.
3
Output Devices:
Output device receives information from the CPU and presents it to the user in the desired from. The processed data, stored in
the memory of the computer is sent to the output unit, which then converts it into a form that can be understood by the user.
The output is usually produced in one of the two ways on the display device, or on paper (hard copy).

Monitor: is often used synonymously with computer screen or display. Monitor is an output device that resembles the
television screen (fig. 1.8). It may use 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.

Printer: Printers are used to produce paper (commonly known as hard copy) 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.

Plotter: Plotters are used to print graphical output on paper. It interprets computer commands and makes line drawings on
paper using multi colored automated pens. It is capable of producing graphs, drawings, charts, maps etc.

Facsimile (FAX): Facsimile machine, a device that can send or receive pictures and text over a telephone line. Fax
machines work by digitizing an image.

Sound cards and Speaker(s): An expansion board that enables a computer to manipulate and output sounds. Sound cards
are necessary for nearly all CD-ROMs and have become commonplace on modern personal computers. Sound cards enable
the computer to output sound through speakers connected to the board, to record sound input from a microphone connected to
the computer, and manipulate sound stored on a disk.

1.2 Computer Characteristics:


1. Speed: Computer work at an incredible speed. A powerful computer is capable performing about 3-4 million instructions per
second.

2. Accuracy: The degree of accuracy of computer is very high and every calculation is performed with the same accuracy. The
errors in computer are due to human and inaccurate data.

3. Diligent: A computer is free from tiredness, lack of concentration, fatigue, etc. It can work for hours without creating any error.
If millions of calculations are to be performed, a computer will perform every calculation with the same accuracy. Due to this
capability it overpowers human being in routine type of work.

4. Versatility: It means the capacity to perform completely different type of work. You may use your computer to prepare payroll
slips. Next moment you may use it for inventory management or to prepare electric bills.

5. Storage capacity: The Computer has an in-built memory where it can store a large amount of data. You can also store data in
secondary storage devices such as floppies, which can be kept outside your computer and can be carried to other computers.

6. No feeling : It does not have feelings or emotion, taste, knowledge and experience. Thus it does not get tired even after long
hours of work. It does not distinguish between users.

4
7. No IQ: Computer is a dumb machine and it cannot do any work without instruction from the user. It performs the instructions
at tremendous speed and with accuracy. It is you to decide what you want to do and in what sequence. So a computer cannot take
its own decision as you can.
1.3 History of Computer:

Generation Key Hardware Key Software Key characteristics Example

(Period)

First Vacuum Tubes, Machine & Bulky in size, ENIAC, EDVAC,


Punched cards etc. assembly languages Unreliable, Difficult UNIVAC etc.
(1942-1955)
to use, limited
commercial use

Second Transistors, High level Faster, smaller, more Honeywell 400,IBM


Magnetic Tapes and programming reliable and easier to 7030 etc.
(1955-1964)
disk as secondary languages, scientific program
storage and commercial
applications

Third Integrated Time sharing Faster, smaller more IBM 360/370,


circuits(IC) with operating system, reliable and easier
(1964- 1975) PDP -8, PDP -11 etc.
small scale standardization of and cheaper to use
integration(SSI) and high level
medium scale programming
integration languages
technology, larger
capacity disks and
magnetic tapes

Fourth ICs with VLSI Operating system for Small, affordable IBM PC, Apple
technology, personal computers ,reliable ,easy to use, II,CRAY 1 etc.
(1975-1989)
Microprocessor, like UNIX, totally general
semiconductor Windows purpose machine
memory, larger
capacity hard disk
etc.

Fifth ICs with ultra large World Wide Web, Portable ,more IBM note books,
scale integration Multimedia powerful ,cheaper Pentium,Core2Duo,
(1989-Present)
technology, Applications ,reliable and easier PARAM etc.
to use.
Larger capacity main
memory and hard
disk

1.4 Classification of computer:


Based on the configuration computer can be classified as follows
Types Super Computer Mainframe Mini Computer Micro Computer
Computer

Size May be room or May be room May have size of May be on a desk
5
building Washing machine

Speed In PFLOPs In FLOPS MIPS KIPS

Peta floating point


operations per sec.

Memory capacity In Peta Bytes In TB In TB In TB

Cost Very Expensive Less than super Less than mainframe Less than mini

Around 1000 million Around 75000 dollar May be in lacks May be in thousands
dollar

Purpose Weather forecasting, To run business In small business For personal use
operations and firms
Research &
Exploration In Bank and
Insurance company

Example CRAY YMP, DEC, ICL and IBM Hitachi 2800 IBM PC, PC-AT
CRAY2, NEC SX-3, 3000 series.
CRAY XMP and
PARAM

1.5 Classification of computer:


Classification based on operation can be done as follows.

Analog Computer, Digital Computer and Hybrid computer

Analog computers: These are used to process analog data. Analog data is of continuous nature and which is not discrete or

separate. Such type of data includes temperature, pressure, speed weight, voltage, depth etc. It measures continuous changes in

some physical quantity e.g. The Speedometer of a car measures speed, the change of temperature is measured by a Thermometer,

the weight is measured by Weights machine. Analog computers are the first computers being developed and provided the basis for

the development of the modern digital computers. Analog computers are widely used for certain specialized engineering and

scientific applications, for calculation and measurement of analog quantities. They are frequently used to control process such as

those found in oil refinery where flow and temperature measurements are important. They are used for example in paper making

and in chemical industry. Analog computers do not require any storage capability because they measure and compare quantities in

a single operation. Output from an analog computer is generally in the form of readings on a series of dial (Speedometer of a car)

or a graph on strip chart.

e.g. TDC Mark III (Torpedo Data Computer)

Digital Computer:

A Digital Computer, as its name implies, works with digits to represent numerals, letters or other special symbols. Digital

Computers operate on inputs which are ON-OFF type and its output is also in the form of ON-OFF signal. Normally, an ON is

represented by a 1 and an OFF is represented by a 0. So we can say that digital computers process information which is based on

the presence or the absence of an electrical charge or we prefer to say a binary 1 or 0.

6
A digital computer can be used to process numeric as well as non-numeric data. It can perform arithmetic operations like addition,

subtraction, multiplication and division and also logical operations. Most of the computers available today are digital computers.

The most common examples of digital computers are accounting machines and calculators.The results of digital computers are

more accurate than the results of analog computers. Analog computers are faster than digital. Analog computers lack memory

whereas digital computers store information. We can say that digital computers count and analog computers measures.

e.g. HP 530

Hybrid computer:

A hybrid is a combination of digital and analog computers. It combines the best features of both types of computers, i-e. It has the

speed of analog computer and the memory and accuracy of digital computer. They help the user, to process both continuous and

discrete data. For example a petrol pump contains a processor that converts fuel flow measurements into quantity and price values.

In hospital Intensive Care Unit (ICU), an analog device is used which measures patient's blood pressure and temperature etc,

which are then converted and displayed in the form of digits. Hybrid computers for example are used for scientific calculations, in

defense and radar systems.

e.g. Dell XPS 12

1.6 Memory Hierarchy in a computer: Following figure represents hierarchy of memory in terms of Access time and
storing capacity.

1.7 Unit of memory:

1 Byte = 8 bits

1 KB (Kilo Bytes) = 1024 bytes

1 MB (Mega Bytes) = 1024 KB

1 GB (Giga Bytes) = 1024 MB

7
1 TB (Tera Bytes) = 1024 GB

1 PB ( Peta Bytes) = 1024 TB

1.8 What is operating System: It is the set of programs that controls a computer and works as an interface between user
and hardware.

e.g.

Its functions:

Process Management: It controls all processes from start to shutdown. It also control creation and deletion of user and system
processes.

Memory Management: It controls allocation and deallocation of memory space as per need. It controls loading of processes
when space is available.

File Management: It controls creation, deletion, renaming, copying and moving of file and directories.

Security Management: It performs many tasks like Alert message, password and firewall protection.

Command interpreter: It works as an interface between user and system. Two types of interface like Command line and
Graphical User Interface (GUI).In command line user interact with the system by command to perform specific task while in GUI
user interact with the help of mouse to access windows icons and menus.

Its types:

Single User: One user can access one computer at a time e.g. DOS

Multi User: Many users can access the same computer at the same time and different time e.g. Windows NT, UNIX

Multiprocessing: more than one processor is there e.g. UNIX, LINUX, and WINDOWS XP

Multitasking: It allows many software processes to run at the same time e.g. UNIX, LINUX, and WINDOWS 7.

Multithreading: It allows different parts of a software program to run concurrently e.g. LINUX, UNIX and WINDOWS XP (Ref.
http://www.computerhope.com/msdos.htm).

About some operating System:


Android is a mobile operating system (OS) based on the Linux kernel and currently developed by Google. Its source code is
released by Google under open source licenses. It uses touch inputs that loosely correspond to real-world actions, like swiping,
pinching, and reverse pinching to manipulate on-screen objects. It is the most widely used mobile OS and, as of 2013. Google
Play store has over 1 million Android apps published, and over 50 billion apps downloaded.

8
DOS (Disk Operating System): DOS was the first operating system used by IBM-compatible computers. It was originally
available in two versions that were essentially the same, but marketed under two different names. "PC-DOS" was the version
developed by IBM and sold to the first IBM-compatible manufacturers. "MS-DOS" was the version that Microsoft bought the
rights to, and was bundled with the first versions of Windows.
DOS uses a command line, or text-based interface, that allows the user to type commands. This made the operating system
difficult for novices to use, which is why Microsoft later bundled the graphic-based Windows operating system with DOS. The
first versions of Windows (through Windows 95) actually ran on top of the DOS operating system. Windows operating system was
rewritten for Windows NT (New Technology), which enabled Windows to run on its own, without using DOS. Later versions of
Windows, such as Windows 2000, XP, and Vista, also do not require DOS.

Windows operating system: It is a graphical user interface based operating systems developed, marketed, and sold by Microsoft.
It was developed by Microsoft to overcome the limitations of DOS OS. First successful version of this was windows 3.0 released
in 1990. It is basically an environment where different programs can run at the same time. It consists of several families
like Windows NT, Windows Embedded and Windows Phone. Microsoft Windows came to dominate the world's personal
computer market with over 90% market share, overtaking Mac OS, which had been introduced in 1984.

Linux: Open source operating system which is enhanced and backed by thousands of programmers worldwide. Its name is
derived from its originator Linus Torvalds who was a student at the university of Helsinki, Finland in early 1990. It is a multi
tasking and multiprocessing operating system (OS). It has two interfaces known as the shell or command-line interface (CLI) and
a graphical user interface (GUI. For desktop systems, the default mode is usually a graphical user interface,

1.9 A number system: Itdefines how a number can be represented using distinct symbols. A number can be represented
differently in different systems. For example, the two numbers (2A) 16 and (52)8 both refer to the same quantity, (42) 10, but their
representations are different.

In a positional number system, the position a symbol occupies in the number determines the value it represents. In this system, a
number represented as:

has the value of:

in which S is the set of symbols, b is the base (or radix).

The decimal system (base 10)

The word decimal is derived from the Latin root decem (ten). In this system the base b = 10 and we use ten symbols

S = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

The symbols in this system are often referred to as decimal digits or just digits.

The following shows the place values for the integer +224 in the decimal system.
9
Note that the digit 2 in position 1 has the value 20, but the same digit in position 2 has the value 200. Also note that we normally
drop the plus sign, but it is implicit.

The following shows the place values for the real number +24.13.

Binary Number: The word binary is derived from the Latin root bini (or two by two). In this system the base b = 2 and we use
only two symbols,

S = {0, 1}

The symbols in this system are often referred to as binary digits or bits (binary digit).

The following shows that the number (11001)2 in binary is the same as 25 in decimal. The subscript 2 shows that the base is 2.

The equivalent decimal number is N = 16 + 8 + 0 + 0 + 1 = 25.

The following shows that the number (101.11)2 in binary is equal to the number 5.75 in decimal.

The hexadecimal system (base 16:

The word hexadecimal is derived from the Greek root hex (six) and the Latin root decem (ten). In this system the base b = 16
and we use sixteen symbols to represent a number. The set of symbols is

S = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F}

Note that the symbols A, B, C, D, E, F are equivalent to 10, 11, 12, 13, 14, and 15 respectively. The symbols in this system are
often referred to as hexadecimal digits

The following shows that the number (2AE)16 in hexadecimal is equivalent to 686 in decimal.
10
The equivalent decimal number is N = 512 + 160 + 14 = 686.

The octal system (base 8):

The word octal is derived from the Latin root octo (eight). In this system the base b = 8 and we use eight symbols to represent a
number. The set of symbols is

S = {0, 1, 2, 3, 4, 5, 6, 7}

The following shows that the number (1256)8 in octal is the same as 686 in decimal.

Note that the decimal number is N = 512 + 128 + 40 + 6 = 686.

1.10 Conversion:

We need to know how to convert a number in one system to the equivalent number in another system. Since the decimal system is
more familiar than the other systems, we first show how to covert from any base to decimal. Then we show how to convert from
decimal to any base. Finally, we show how we can easily convert from binary to hexadecimal or octal and vice versa.

11
Any base to decimal conversion

The following shows how to convert the binary number (110.11)2 to decimal: (110.11)2 = 6.75.

The following shows how to convert the hexadecimal number (1A.23)16 to decimal.

Note that the result in the decimal notation is not exact, because
2
3 16 = 0.01171875. We have rounded this value to three digits (0.012).

The following shows how to convert (23.17)8 to decimal

This means that (23.17)8 19.234 in decimal. Again, we have rounded up 7 82 = 0.109375.

12
1.11 Decimal to any base

The following shows how to convert 35 in decimal to binary. We start with the number in decimal, we move to the left while
continuously finding the quotients and the remainder of division by 2. The result is 35 = (100011) 2.

The following shows how to convert 126 in decimal to its equivalent in the octal system. We move to the right while continuously
finding the quotients and the remainder of division by 8. The result is 126 = (176)8.

The following shows how we convert 126 in decimal to its equivalent in the hexadecimal system. We move to the right while
continuously finding the quotients and the remainder of division by 16. The result is 126 = (7E) 16

13
Converting the fractional part of a number in decimal to other bases:

Convert the decimal number 0.625 to binary.

Since the number 0.625 = (0.101)2 has no integral part, the example shows how the fractional part is calculated.

The following shows how to convert 0.634 to octal using a maximum of four digits. The result is 0.634 = (0.5044) 8. Note that we
multiple by 8 (base octal).

14
The following shows how to convert 178.6 in decimal to hexadecimal using only one digit to the right of the decimal point. The
result is 178.6 = (B2.9)16 Note that we divide or multiple by 16 (base hexadecimal).

Binary-hexadecimal conversion:

Show the hexadecimal equivalent of the binary number (110011100010)2.

Solution

We first arrange the binary number in 4-bit patterns:

100 1110 0010

Note that the leftmost pattern can have one to four bits. We then use the equivalent of each pattern shown in Table 2.2 on page 25
to change the number to hexadecimal: (4E2)16.

What is the binary equivalent of (24C)16?

Solution

Each hexadecimal digit is converted to 4-bit patterns:

2 0010, 4 0100, and C 1100

The result is (001001001100)2.

Binary-octal conversion:

Show the octal equivalent of the binary number (101110010)2.

Solution

15
Each group of three bits is translated into one octal digit. The equivalent of each 3-bit group is shown in Table 2.2 on page 25.

101 110 010

The result is (562)8.

What is the binary equivalent of for (24)8?

Solution

Write each octal digit as its equivalent bit pattern to get

2 010 and 4 100

The result is (010100)2.

Octal-hexadecimal conversion:

1.12 Binary Arithmatic:

16
1.13 Computer languages: we use a computer language to write a program in computer. A computer language is a set of
predefined words and predefined rules (syntax). Over the years, computer languages have evolved from machine language to
high-level languages.

Machine languages(First Generation Language):

In the earliest days of computers, the only programming languages available were machine languages. Each computer had its own
machine language, which was made of streams of 0s and 1s. It is the language understood by a computer. In this data and
operation is represented in terms of binary number. We use Opcode as shown in the table.

Assembly language(2nd Generation language):

The next evolution in programming came with the idea of replacing binary code for instruction and addresses with symbols or
mnemonics. Because they used symbols, these languages were first known as symbolic languages. The set of these mnemonic
languages were later referred to as assembly languages.

17
High Level Language(3rd Generation Language):

Although assembly languages greatly improved programming efficiency, they still required programmers to concentrate on the
hardware they were using. Working with symbolic languages was also very tedious, because each machine instruction had to be
individually coded. The desire to improve programmer efficiency and to change the focus from the computer to the problem being
solved led to the development of high-level languages.

Over the years, various languages, most notably BASIC, COBOL, Pascal, Ada, C, C++ and Java, were developed. Program for
adding two integers in C is shown below.

Non-Procedural Languages(4th Generation Language):

These are easy to understand and use like Query Language SQL. Such languages enable a person to specify exactly what
information they require from the database and usually embedded within database management.

Writing query:

Select name, class, address from student where rollno=10;

Natural Languages (5th Generation Language):

Natural-Language: Languages that use ordinary conversation in ones own language. Research and experimentation toward this
goal is being done. Intelligent compilers are now being developed to translate natural language (spoken) programs into structured
machine-coded instructions that can be executed by computers. Effortless, error-free natural language programs are still some
distance into the future.

Typical examples of a 5GL include Prolog and Mercury.

18
1.14 Difference among hardware, software and firmware:

Hardware Software Firmware


The physical components of The collection of program and other Pre written program that is stored in
computers are called hardware such associated documents that helps to ROM. It configures the computer
as input devices, output devices, control, manage and integrate the and not easily modified by users.
processing devices, memory devices components of computer system to
etc. accomplish a specific task. It is a Example: Instructions coded in
non-touchable, non viable set of BIOS (Basic Input Output Service)
Example: Registers, CPU, Hard instructions coded in computer are example of Firmware. Firmware
Disk, Floppy Disk, Printers, and languages. It is a vital part of ROM contains loader program to
Mouse etc which are touchable, computer, without it computer is load a program into memory.
visible and replaceable. nothing.

Example: Operating system,


compiler and interpreter, application
software etc.

1.15 Software Classification: Software can be classified as follows

System Software Application Software

Like Operating System (Windows, DOS, Linux etc.)

General purpose Specific Purpose Utility software

e.g. MS Office e.g. Library Information system e.g. compiler, Interpreter

Compiler: It is a software which converts (or translates) source program written using high level language into object code.

Program in HLL Compiler Object code

It checks whole program lexically, syntactically and if error then give message to the programmer and does not convert into object
code.

Example: Turbo C++, gcc etc.

Interpreter: It translate program into machine code.

Interpreter 19
Program machine code

Get next instruction

It checks program statement by statement and convert into machine if there is no error. Therefore it is slower than compiler.

Example: Thin Basic for Windows, Java Script engine for Java Script.

Assembler: It converts program written in assembly language or symbolic language into machine code.

Program Executable code


Assembler

Example: MASSAM (Microsoft Assembler), FASM (Flat Assembler)

Linker: In high level languages, some built in header files or libraries are stored. These libraries are predefined and these
contain basic functions which are essential for executing the program. These functions are linked to the libraries by a program
called Linker. If linker does not find a library of a function then it informs to compiler and then compiler generates an error. The
compiler automatically invokes the linker as the last step in compiling a program .

Loader: It is a program that loads machine codes of a program into the system memory. It is the part of an Operating
System that is responsible for loading programs. It is one of the essential stages in the process of starting a program. Because it
places programs into memory and prepares them for execution. Loading a program involves reading the contents of executable
file into memory. Once loading is complete, the operating system starts the program by passing control to the loaded program
code. All operating systems that support program loading have loaders. In many operating systems the loader is permanently
resident in memory.

1.16 Algorithm: It is a well-ordered collection of unambiguous and effectively computable operations, that

when executed, produces a result and halts in a finite amount of time. It is for user understanding.

Characteristics of an Algorithm:

Well-ordered: the steps are in a clear order

Unambiguous: the operations described are understood by a computing agent without further simplification

Effectively computable: the computing agent can actually carry out the operation Algorithm to find the average of two numbers

Step1: Start

Step 2: Input two numbers

Step3: Calculate average

Step 4: Print average

Step 5: Stop

There are generally three various ways to represent an algorithm.

1. Pseudocode

2. Flow Chart

3. Program

20
1.17 Pseudocode (or Program Design Language): It is representation of an algorithm in code like format. It will be
closer to any high level language like C, Pascal, Fortran etc. It is for programmer understanding.

Read A ,B

Sum =A+B

Avg = Sum/2

Print Avg

1.18 Flow Chart: It is used to visualize an algorithm. It means it is pictorial representation of the algorithm which shows the
flow of steps in an algorithm.

Symbol used in flow chart:

Start/Stop

Input/ Output

Process

Flow of steps

Connector

Algorithm to calculate age:

1. Start

2. Get year born

3. Calculate age

4. Print age

5. If age > 50 print OLD

6. End

21
Flow chart:

To find the biggest between two numbers

Algorithm:

Step 1 Start.

Step 2. Input A, B

Step 3. Comprare A and B

Step 4. Print Biggest one

Step 5. Stop

Pdeudo code

Read A,B

If A>B

Print A

Else

Print B

22
Flow Chart:

Start

Read A, B

A False
>B? Print B

True

Print A

Stop

Questions

Q.1. What is an Algorithm. What are different types of algorithm? Write its properties. Find largest of 3 numbers.

Q.2. Draw neat and clean diagram of digital computer.

Q.3. What is Operating system. Write about multiprogramming and multithreading.

Q.4 Perform the following:


(786)10 = ( )2
(10101.1101)2 = ( )8
(161)8 = ( )10
(11101001)2 = ( )16

Q.5. What are Symbols used in flowchart and flowchart of factorial of a number. Write about Generation of computers along with
advantages and disadvantages?

Q.6.What is goals of operating system?

Q7. What do you mean by System software and application software?

Q.8. Write difference between Compiler and interprete.

Q.9.Differentiate between:
a. High and low level.

23
b. Compiler and interpreter.
c. Logical and runtime error.
d. Algorithm and flowchart.

Q.10. Define Operating system. Name of 4 OS. Write its features.

Q.11. For a digital computer explain the following:


a. Cache memory.
b. Control unit.
c. ALU.

Q.12. Convert:
a. (999)10 = (? )16
b. (11011101999)2 = (? )8
c. (786)10 = ( ?)BCD
d. Twos complement of 1100100. And write the value in decimal.

Q.1. Define CPU. Explain its major components.

Q.2. What do you mean by application software? Give any two examples.

Q.3.What is an operating system? List the various types of OS.

Q.4.What do you mean by algorithm? Discuss characteristics of algorithm.

Q.5. What is secondary memory? Give any two examples.

Q.6. How plotter is different from printer.

Q.7. Convert the following:


a) (1110101.101)2 = (? )8
b) (5454.11)6 = ( ?)10
c) (CD1B)16 = (? )8
d) (254.5)10 = (? )2
Q.8. Various types of programming languages and their characteristics.

Q.9. Convert the following:


(D123.AB)16 = ( ?)10
(-76)8 = (? )10
(AB15)16 + (EF5)16 = (? )10
(642)8 = (? )10

Q.9. Neat diagram of digital computer.

Q.1. Write in brief about the components of central processing unit of a computer.

Q.2. Make the hierarchy of different memories available in a computer.

Q.3. Write difference between compiler and interpreter.

Q.4. Define operating system with its different functions.

24
Q.5. Convert the following:
a) (FA1.2C)16=(?)8
b) (756)10=(?)4
c) (11011.011)2=(?)16
d) (574.32)8=(?)2

Q.6. Define algorithm? Make flowchart to find prime numbers between 101 and 999.

Q.1. What are the classification of computer? Explain any two in detail.

Q.2. Describe the functionalities of an operating system.

Q.3. Convert the hexa decimal number (A9C5.DB4)16 to octal number.

Q.4. Draw a flowchart to find the sum and reverse of a given number.

Q.5. Discuss various functionalities of compiler, linker and loader.

Q.6. Describe about the basic components of computer with a neat block diagram.

25
2.1 Introduction

C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating
system at AT&T Bell Labs. C is a highly flexible and adaptable language because of which it withstood the test of time. Since its
creation in 1972, its been used for a wide variety of programs including general purpose and business applications, gaming,
operating systems, databases, device driver programming, graphics programming, firmware for micro-controllers,
compilers/assemblers of other programming languages and so on.C is the most widely used language in the world and has a large
developer community because of which it is very stable and robust.

Q 1. Write short note on C language?

Q 2. Enumerate various applications of C language?

2.2 History of C language

In 1972 a programmer, Dennis Ritchie, created a new language called


C. C was not entirely a new language. It was derived from another
programming language called B which in turn was derived from an old
programming language called BCPL. C was designed with one goal in
mind: writing operating systems. During the years 1972-73, Dennis
Ritchie along with his colleagues at AT&T Bell Labs rewrote the entire
UNIX operating system in C language which initially was written in
assembly language.

Traditional C borrowed many concepts from ALGOL, BCPL and B. It


added the concept of data types and other powerful features. It was a
non-standardized version developed for internal usage inside AT&T and
Bell Labs to mainly develop UNIX OS.

After the publication the of book The C Programming Language by


Brian Kerninghan and Dennis Ritchie in 1978, the C language became
popularly known as K&R C based on initials of its authors.

By late 1980s C became highly dominant in software industry.


However each software vendor started developing and maintaining his
own version of C and its associated libraries. This led to inconsistency
and incompatibility issues. In order to tackle these issues, ANSI
(American National Standard Institute) released a standardized version
of C known as ANSI C in 1989. ISO (International Organization for
Standardization)approved ANSI C in 1990, and it became ISO C.

In 1999, ISO standardization committee updated C language according


to the changing trends in the software industry and named it C99. C99
provides several new features, such as inline functions, new data types-
long and long int, variable length arrays and support for single line
comment.
Fig 2.1 Evolution of C language
The current standard of C is C11 which formalized by ISO
standardization committee in 2011. C11 provides several enhancements
over C99 including multithreading support, safer standard libraries, and better compliance with other industry standards

26
2.3
Q 3.Features of note
Write a short C language
on history and development of C?

C is very fast and efficient as it directly interacts with hardware and because it provides variety of operators and data types.
C is portable as a program written in C can be run on a variety of devices

C is highly extensible with the help of user defined libraries

C is modular as its programs are always broken down and


written with the help of functions

C is a very compact language. Its original specification


contained just 32 keywords and a very limited set of libraries.
If a user wants more functionality he can always use external
libraries.

Fig 2.2 Features of C language

Q 4. Explain the features of C language?

2.4 Advantages of C language


Simple yet powerful
High Performance
Highly extensible
Portable

2.5 Disadvantages of C language


C is less sophisticated than newer languages like Java, C# or Python so the programmer need to write more lines of
code to achieve similar results
C does not support object oriented programming
C does not support exception(run time error) handling
C does not have strict type checking- e.g., we can pass an integer value for the float data type
C does not have the concept of namespaces
C does not have the concept of constructors and destructors

Note: The disadvantages of C will be more clear after you have thoroughly studied all the five units.

Q 5. Explain the advantages and disadvantages C language?

2.6 Writing the First C Program


Let us consider a simple C program. Our first example displays a line of text. The program and its screen output are shown
below:
1 //A simple program to print Hello World
2 #include<stdio.h> Output of the program:
3
4 //main function starts execution
5 void main() Hello World
6 { 27
7 printf(Hello world\n);
8 }
9 //main function completes execution
Even though this program is simple, it illustrates several important features of the C language.

2.6.1 Comments: Lines 1, 3 and 8 begin with // (double forward slash), indicating that these two lines are comments. We insert
comments to documentprograms and improve program readability. Comments do not cause the computerto perform any action
when the program is run. Comments are ignored by the C compilerand do not cause any machine-language object code to be
generated. The preceding comments simply describe the purpose of the program, from where the program starts execution and
where the program stops execution. Comments also help other people read and understand our program.

Note: We can also use /**/ multi-line comments in which everything from /* on the first line to */ at the end of the last line is a
comment.

2.6.2 Preprocessor Directives: Line 2 (#include<stdio.h>) is a directive (command) to the C preprocessor which is a special
program. Lines beginning with # are processed by the preprocessorbefore compilation. Line 2 tells the preprocessor to include the
contents of the standardinput/output header (<stdio.h>) in the program. This header contains informationused by the compiler
when compiling calls to standard input/output library functions suchas printf(). A much detailed discussion about the c
preprocessor will follow in unit 5.

2.6.3 Blank Lines and White Space: Line 3 is simply a blank line. You use blank lines, space characters and tab characters
(i.e.,tabs) to make programs easier to read. Together, these characters are known as whitespace. White-space characters are
normally ignored by the compiler.

2.6.4 The main Function: Line 5 (void main() ) is called the main function. It is the point in a C program from where the
execution starts. The parentheses after main indicate that main() is a programbuilding block called a function. C programs contain
one or more functions, one of whichmust always be main(). Every program in C begins executing at the function main. Functions
canreturn information. The keyword void to the left of main indicates that here main()does not return any value.

A left brace, {, begins the body of every function (line 6). A corresponding right brace ends each function (line 8). This pair of
braces and the portion of the program betweenthe braces is called a block. A block is always executed in entirety i.e., either all the
statements inside are executed or none of them is executed.

2.6.5 An Output Statement: Line 7 (printf) instructs the computer to perform an action, namely to print on the screen the string
ofcharacters enclosed within quotation marks.A string is sometimes called a character string,a message or a literal. The entire line,
including the printf function (the f stands forformatted), its argument within the parentheses and the semicolon (;), is called a
statement.Every statement must end with a semicolon (also known as the statement terminator).When the preceding printf
statement is executed, it prints the message Welcome toC! on the screen. The characters normally print exactly as they appear
between the doublequotes in the printf statement. \n is a special symbol called the escape sequence that tells the compiler to move
to the cursor to the next line after displaying the message on the screen.

2.7 Executing the first C program (Turbo C)

Step 1: Locate the TC.exe file and open it. You will usually find it at location C:\TC\BIN\.

Step 2:Goto File >New and then write your C program

Step 3: Save the program using F2 (or File > Save), remember the extension should be either .cpp or .c.

Step 4: Compile the program using Alt + F9 or Compile > Compile

Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C program.

Step 6: Alt+F5 to view the output of the program at the output screen.

Q 6. Write a short note on writing and executing the first C program?

2.8 General Structure of a C Program

28
Documentation Section
Link Section
Definition Section
Global Declaration Section
void main()
{
Declaration Section
Executable part
}
Subprogram section
Function 1
Function 2
.
.
Function n

The Documentation Section consists of a set of comment lines giving the name of the program and other details.

The Link Section provides instructions to the compiler to link functions from the system library.

The Definition Section defines all symbolic constants.

The Global Declaration Section: There are some variables and those variables are declared in this section that is outside of all
functions.

main() function: Every C program must have one main function section. This section contains two parts, declaration and
executable part.

Declaration Part declares all the variables used in the executable part.
There should be at least one statement in the executable part which contains instructions to perform certain task.

The declaration and executable part must appear between the opening and closing braces. All statements in the declaration part
should end with the semicolon.

The Subprogram Section contains all the user defined functions that are called in the main function.

Q 7. Describe the structure of a C program?

2.9 Compilation of a C Program

29
The compilation process of a C program involves following steps:

1. Preprocessing is the first step of any C compilation. It processes include-files, conditional compilation instructions and
macros.
2. Compilation is the second pass. It takes the output of the preprocessor, and the source code, and generates assembler
source code.
3. Assembly is the third stage of compilation. It takes the assembly source code and produces an assembly listing with
offsets. The assembler output is stored in an object file.
4. Linking is the final stage of compilation. It takes one or more object files or libraries as input and combines them to
produce a single (usually executable) file. In doing so, it resolves references to external symbols, assigns final addresses
to procedures/functions and variables, and revises code and data to reflect new addresses (a process called relocation).

There is one more step involved before actual execution of a C program takes place. It is called loading. In this step, the
loader brings the C program from secondary storage (e.g., hard disk) to main memory (i.e., RAM) and prepares it for
execution. It allocates memory and other necessary resources to the program and hands over the CPU control to it.

Q 8. Explain the compilation process of a C program?or


Q 9. Explain various components of C language?

30
2.10 Standard Input/Output (I/O) in C

When we are saying Input that means to feed some data into program.C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement.

When we are saying Output that means to display some data on screen, printer or in any file. C programming language provides a
set of built-in functions to output the data on the computer screen as well as you can save that data in text or binary files.

2.10.1 The Standard Files

C programming language treats all the devices as files. So devices such as the display are addressed in the same way as files and
following three file are automatically opened when a program executes to provide access to the keyboard and screen.

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file points are the means to access the file for reading and writing purpose. This section will explain how to read values from
the screen and how to print the result on the screen.

2.10.2 The getchar() & putchar() functions [Unformatted I/O]

The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads
only single character at a time. We can use this method in the loop in case we want to read more than one characters from the
screen.

The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only
single character at a time. We can use this method in the loop in case we want to display more than one character on the screen.
Check the following example:

#include <stdio.h>
void main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
}

When the above code is compiled and executed, it waits for you to input some text when you enter a text and press enter then
program proceeds and reads only a single character and displays it as follows:

Enter a value : this is test


You entered: t

2.10.3 The gets() & puts() functions [Unformatted I/O]

The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF
(End of File).

The int puts(const char *s) function writes the string s and a trailing newline to stdout.

31
#include <stdio.h>
void main( )
{
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
}

When the above code is compiled and executed, it waits for us to input some text when we enter a text and press enter then
program proceeds and reads the complete line till end and displays it as follows:

Enter a value : this is test


You entered: This is test

2.10.4 The scanf() and printf() functions [Formatted I/O]

The int scanf(const char *format, ...) function reads input from the standard input stream stdin and scans that input according to
format provided.

The int printf(const char *format, ...) function writes output to the standard output stream stdout and produces output according
to a format provided.

The format can be a simple constant string, but we can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or
float respectively. There are many other formatting options available which can be used based on requirements. For now let us
proceed with a simple example which makes things clear:

#include <stdio.h>
void main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
}

When the above code is compiled and executed, it waits for us to input some text, when we enter a text and press enter then
program proceeds and reads the input and displays it as follows:

Enter a value : seven 7


You entered: seven 7

Here, it should be noted that scanf() expect input in the same format as we provided %s and %d, which means we have to provide
valid input like "string integer", if we provide "string string" or "integer integer" then it will be assumed as wrong input. Second,
while reading a string scanf() stops reading as soon as it encounters a space so "this is test" are three strings for scanf().

2.10.4.1 Format specifiers

Some important format specifiers in C:

%csingle character

%d (%i) signed integer


32
%ldlong integer

%e (%E) exponential format

%f floating point decimal

%lf long float long floating point decimal

%ounsigned octal value

%p pointer address stored in pointer

%s array of char sequence of characters

%uunsigned integer

%x (%X)unsigned hexadecimal value

2.10.4.2 I/O of integers using printf()

Let us consider following C program:

#include<stdio.h>
void main()
{
int c=5;
printf("Number=%d",c);
}

Output

Number=5

Inside quotation of printf() there, is a format specifier "%d" (for integer). If this format specifier matches with remaining
argument,i.e, c in this case, value of c is displayed.

Let us consider one more example:

#include<stdio.h>
void main()
{
int c;
printf("Enter a number\n");
scanf("%d",&c);
printf("Number=%d",c);
}

Output

Enter a number
4
Number=4

The scanf() function is used to take input from user. In this program, the user is asked a input and value is stored in variable c.
Note the '&' sign before c. &c denotes the address of c and value is stored in that address.

33
2.10.4.3 I/O of floats in C

Consider the following C program:

#include <stdio.h>
void main()
{
float a;
printf("Enter value: ");
scanf("%f",&a);
printf("Value=%f",a); //%f is used for floats instead of %d
}

Output

Enter value: 23.45


Value=23.450000

Format specifier "%f" is used for floats to take input and to display floating value of a variable.

2.10.4.4 I/O of Characters

#include <stdio.h>
void main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.",var1);
}

Output

Enter character: g
You entered g.

format specifier "%c" is used in case of characters.

2.10.4.5 I/O of ASCII values

When character is typed in the above program, the character itself is not recorded a numeric value(ASCII value) is stored. And
when we displayed that value by using "%c", that character is displayed.

#include <stdio.h>
void main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.\n",var1);
/* \n prints the next line(performs work of enter). */
printf("ASCII value of %d",var1);
}

Output

34
Enter character:
g
103

When, 'g' is entered, ASCII value 103 is stored instead of g.

We can display character if we know ASCII code only. This is shown by following example.

#include <stdio.h>
void main()
{
int var1=69;
printf("Character of ASCII value 69: %c",var1);
}

Output

Character of ASCII value 69: E

The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b' is 98 and so on to 'z' is 122.

2.10.4.6 Variations in Output for integer and floats

Integer and floating-points can be displayed in different formats in C programming as:

#include<stdio.h>
void main()
{
printf("Case 1:%6d\n",9876);
/* Prints the number right justified within 6 columns */
printf("Case 2:%3d\n",9876);
/* Prints the number to be right justified to 3 columns but, there are 4 digits so number is not right justified */
printf("Case 3:%.2f\n",987.6543);
/* Prints the number rounded to two decimal places */
printf("Case 4:%.f\n",987.6543);
/* Prints the number rounded to 0 decimal place, i.e, rounded to integer */
printf("Case 5:%e\n",987.6543);
/* Prints the number in exponential notation(scientific notation) */
}

Output:

Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988
Case 5:9.876543e+002

2.10.4.7Variations in Input for integer and floats

#include <stdio.h>
void main()
{
int a,b;
float c,d;
printf("Enter two intgers: ");
/*Two integers can be taken from user at once as below*/

35
scanf("%d%d",&a,&b);
printf("Enter intger and floating point numbers: ");
/*Integer and floating point number can be taken at once from user as below*/
scanf("%d%f",&a,&c);
}

Similarly, any number of input can be taken at once from user.

Q 10. Write a short note on standard input/output (I/O) in C

2.11 Constants, Variables and Datatypes


A program consists of set of instructions, the instructions are informed using certain symbols and words according to some rigid
rules (or Grammar). Every program instructions must contain confirm precisely to the syntax, rules of the language. Like any
other language C also has its own vocabulary and grammar.

2.11.1 Character set:

A character denotes any alphabet, digit or special symbol used to represent information.
Alphabets A, B, .., Y, Z a, b, , y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' <> , . ? /

2.11.2 Constants:

Constants are identifiers whose value does not change. Constants are used to define fixed values like PI or the charge on an
electron so that their value does not get changed in the program even by mistake. To declare a constant, precede the normal
variable declaration with const keyword and assign it a value. For example,

const float pi = 3.14;

Another way to designate a constant is to use the pre-processor command define.

#define PI 3.14159

When the preprocessor reformats the program to be compiled by the compiler, it replaces each defined name with its
corresponding value wherever it is found in the source program. Hence, it just works like the Find and Replace command
available in a text editor.

Constants refers to fixed value that do not change during the execution of a program. C constants can be divided into two major
categories:
Numeric constant (Integer constant and Real constant)
Character constant (Single character constant and String constant)

Let us consider a problem involving usage of constants:

#include<stdio.h>
void main()

{
const int x=10;
printf(%d,x);
}

2.11.3 Variables:

An entity that may vary during program execution is called a variable. Variable names are names given to locations in memory.
These locations can contain integer, real or character constants.

36
Rules for Constructing Variable Names:
A variable name is any combination of 1 to 31 alphabets, digits or underscores.
The first character in the variable name must be an alphabet or underscore.
No commas or blanks are allowed within a variable name.
No special symbol other than an underscore (as in gross_sal) can be used in a variable name.
e.g. simple_intrest,SUM, m1 etc.

2.11.4 Keywords:
Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The
keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is
not allowed by the computer. There are only 32 keywords available in C.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2.11.5 Identifiers:
Identifiers refers to the name of variables, functions and arrays. These are user-defined names and consists of a sequence of letters
and digits, with a letter as first character. Both upper case and lowercase letters are permitted. Underscore is permitted in
identifier. Rules for naming an identifier are same as rules for naming a variable.

2.11.6 Fundamental Datatypes in C

They are also called Primitive Datatypes.

2.11.6.1 Integer Datatype

Keyword: int
Minimum Range: -32768 to 32767
Format specifier: %d

An integer is a whole number (a number without a fractional part). It can be positive or negative numbers like 1, -2, 3, etc., or
0.The sizes of the integer variables depend on the hardware and operating system of the computer.

2.11.6.2 Floating Point Datatype

Keyword: float
Minimum Range:-3.4e38 to +3.4e38
Format specifier: %f

37
Floating point numbers are numbers with a decimal point. The float type can take large floating point numbers with a small degree
of precision (Precision is simply the number of decimal places to which a number can be calculated with accuracy. If a number
can be calculated to three decimal places, it is said to have three significant digits.)

2.11.6.3 Double Floating Datatype

Keyword: double
Minimum Range:-1.7e308 to +1.7e308
Format specifier: %lf

Double-precision floating point numbers are also numbers with a decimal point. We know that the float type can take large
floating point numbers with a small degree of precision but the double-precision double type can hold even larger numbers with a
higher degree of precision.

2.11.6.4 Character Datatype

Keyword:char
Minimum Range:-128 to +127
Format specifier: %c

char is a special integer type designed for storing single characters. The integer value of a char corresponds to an ASCII
(American Standard Code for Information Interchange) character. E.g., a value of 65 corresponds to the letter A, 66 corresponds
to B, 67 to C, and so on.

2.11.6. 5 Void Datatype

Keyword: void
Minimum Range: nil
Format specifier: nil

The type specifier void indicates that no value is available. It has three main functions

1. Function returns as void


There are various functions in C which do not return value or we can say they return void. A function with no return value has the
return type as void. For example void exit (int status);
2. Function arguments as void
There are various functions in C which do not accept any parameter. A function with no parameter can accept as a void. For
example, int rand(void);
3. Pointers to void
A pointer of type void * represents the address of an object, but not its type. For example a memory allocation function void
*malloc( size_t size ); returns a pointer to void which can be casted to any data type.

2.11.7 Extended Datatypes or Type Modifiers

The fundamental data types explained above have the following modifiers.

short
long

signed

unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI
has the following rules:

38
short int <=int <= long int

float <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int'
should be less or the same bytes than a 'long int'. What this means in the real world is:

Type Bytes Range


---------------------------------------------------------------------
short int 2 -32,768 -> +32,767 (32kb)
unsigned short int 2 0 -> +65,535 (64Kb)
unsigned int 4 0 -> +4,294,967,295 ( 4Gb)
int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
signed char 1 -128 -> +127
unsigned char 1 0 -> +255
float 4
double 8
long double 12

These figures only apply to todays generation of PCs. Mainframes and midrange machines could use different figures, but would
still comply with the rule above. We can find out how much storage is allocated to a data type by using the sizeof operator.

Here is an example to check size of memory taken by various datatypes.

#include<stdio.h>
void main()
{
printf("sizeof(char) == %d\n", sizeof(char));
printf("sizeof(short) == %d\n", sizeof(short));
printf("sizeof(int) == %d\n", sizeof(int));
printf("sizeof(long) == %d\n", sizeof(long));
printf("sizeof(float) == %d\n", sizeof(float));
printf("sizeof(double) == %d\n", sizeof(double));
printf("sizeof(long double) == %d\n", sizeof(long double));
printf("sizeof(long long) == %d\n", sizeof(long long));
}

2.11.8 Type Qualifiers


A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether:
The value of a variable can be changed.
The value of a variable must always be read from memory rather than from a register

Standard C language recognizes the following two qualifiers:


const
volatile

The const qualifier is used to tell C that the variable value cannot change after initialisation.

const float pi=3.14159;

Now pi cannot be changed at a later time within the program.Another way to define constants is with the #define preprocessor
which has the advantage that it does not use any storage

The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler
(such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code
referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it
may have changed. You will use this qualifier once you will become expert in "C". So for now just proceed.
39
Q 11. What are variables, constants, identifiers and keywords?
2.12 Storage rules
Q 12. Enumerate Classes in C variables and identifiers?
for naming
Q 13.variable
Every Write a in
short note on fundamental
C programming has twoand extendedtype
properties: datatypes in C language?
and storage class. Type refers to the data type of variable whether it is
character or integer or floating-point value etc. And storage class determines how long it stays in existence.
The storage class of a variable defines the scope (visibility) and life time of variables and/or functions declared within a
C Program. In addition to this, the storage class gives the following information about the variable or the function.
It is used to determine the part of memory where storage space will be allocated for that variable or function (whether the
variable/function will be stored in a register or in RAM)
it specifies how long the storage allocation will continue to exist for that function or variable.
It specifies the scope of the variable or function. That is, the part of the C program in which the variable name is visible,
or accessible.
It specifies whether the variable or function has internal, external, or no linkage
It specifies whether the variable will be automatically initialized to zero or to any indeterminate value

There are 4 types of storage class:


1. automatic
2. external
3. static
4. register

2.12.1 Automatic storage class


Keyword for automatic variable
auto
Variables declared inside the function body are automatic by default. These variable are also known as local variables as they are
local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are rarely used.

2.12.2 External storage class


External variable can be accessed by any function. They are also known as global variables. Variables declared outside every
function are external variables.
Example to demonstrate working of external variable

void Check();
int a=5;
/* a is global variable because it is outside every function */
int main(){
a+=4;
Check();
return 0;
}

void Check(){
++a;
/* ----- Variable a is not declared in this function but, works in any function as they are global variable ------- */
printf("a=%d\n",a);
}
Output
a=10

2.12.3 Register Storage Class


Keyword to declare register variable
register
Example of register variable
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register rather than memory. Value stored
in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared register variables.
Since, there are limited number of register in processor and if it couldn't store the variable in register, it will automatically store it
in memory.

40
2.12.4 Static Storage Class
The value of static variable persists until the end of the program. A variable can be declared static using keyword: static. For
example:
static int i;
Here, i is a static variable.
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c=c+5;
}
Output
0 5 10
During first function call, it will display 0. Then, during second function call, variable c will not be initialized to 0 again, as it is
static variable. So, 5 is displayed in second function call and 10 in third call.
If variable c had been automatic variable, the output would have been:
0 0 0

FEATURE STORAGE CLASS

Auto Extern Register Static

Accessibility Accessible within the Accessible within all Accessible within the Local: Accessible
function or block in program files that are a function or block in within the function or
which it is declared part of the program which it is declared block in which it is
declared
Global: Accessible
within the program in
which it is declared
Storage Main Memory Main Memory CPU Register Main Memory

Existence Exists when the Exists throughout the Exists when the Local: Retains value
function or block in execution of the function or block in between function calls
which it is declared is program which it is declared is or block entries
entered. Ceases to entered. Ceases to Global: Preserves
exist when the control exist when the control value in program files
returns from the returns from the
function or the block function or the block
in which it was in which it was
declared declared
Default Garbage Zero Garbage Zero
value

Q 14. Explain various storage classes in C

2.13 Operators in C

C language supports a lot of operators to be used in expressions. These operators can be categorized into the following major
groups:
Arithmetic operators
Relational Operators
41
Equality Operators
Logical Operators
Unary Operators
Conditional Operators
Bitwise Operators
Assignment operators
Comma Operator
Sizeof Operator

2.13.1 Arithmetic Operators

Operation Operator Syntax Comment Result

Multiply * a*b result = a * b 27

Divide / a/b result = a / b 3

Addition + a+b result = a + b 12

Subtraction - a-b result = a b 6

Modulus % a%b result = a % b 0

2.13.2 Relational Operators


Also known as a comparison operator, it is an operator that compares two values. Expressions that contain relational operators are
called relational expressions. Relational operators return true or false value, depending on whether the conditional relationship
between the two operands holds or not.

Operator Meaning Example

< Less Than 3 < 5 Gives 1

> Greater Than 7 > 9 Gives 0

>= Less Than Or Equal To 100 >= 100 Gives 1

<= Greater Than Equal To 50 >=100 Gives 0

2.13.3 Equality Operators


C language supports two kinds of equality operators to compare their operands for strict equality or inequality. They are equal to
(==) and not equal to (!=) operator. The equality operators have lower precedence than the relational operators.

Operator Meaning

== RETURNS 1 IF BOTH OPERANDS ARE EQUAL, 0 OTHERWISE


!= RETURNS 1 IF OPERANDS DO NOT HAVE THE SAME VALUE, 0
OTHERWISE

2.13.4 Logical Operators


C language supports three logical operators. They are- Logical AND (&&), Logical OR (||) and Logical NOT (!).As in case of
arithmetic expressions, the logical expressions are evaluated from left to right.

42
A B A||B
0 0 0 A !A
0 1 1 0 1
1 0 1 1 0
1 1 1

2.13.5 Unary Operators


Unary operators act on single operands. C language supports three unary operators. They are unary minus, increment and
decrement operators.When an operand is preceded by a minus sign, the unary operator negates its value. The increment operator is
a unary operator that increases the value of its operand by 1. Similarly, the decrement operator decreases the value of its operand
by 1. For example,
int x = 10, y;
y = x++;
is equivalent to writing
y = x;
x = x + 1;
whereas, y = ++x;
is equivalent to writing
x = x + 1;
y = x;

2.13.6 Conditional Operator (Ternary Operator)

The conditional operator operator (?:) is just like an if .. else statement that can be written within expressions. The syntax of the
conditional operator is
exp1 ? exp2 : exp3
Here, exp1 is evaluated first. If it is true then exp2 is evaluated and becomes the result of the expression, otherwise exp3 is
evaluated and becomes the result of the expression. For example,
large = ( a > b) ? a : b
Conditional operators make the program code more compact, more readable, and safer to use as it is easier both to check and
guarantee that the arguments that are used for evaluation.
Conditional operator is also known as ternary operator as it is neither a unary nor a binary operator; it takes three operands.

2.13.7Bitwise Operators

Bitwise operators perform operations at bit level. These operators include: bitwise AND, bitwise OR, bitwise XOR and shift
operators.
The bitwise AND operator (&) is a small version of the boolean AND (&&) as it performs operation on bits instead of
bytes, chars, integers, etc.

x y x&y
0 0 0
0 1 0
1 0 0
1 1 1

The bitwise OR operator (|) is a small version of the boolean OR (||) as it performs operation on bits instead of bytes,
chars, integers, etc.

x y x|y
0 0 0
0 1 1
1 0 1
1 1 1
43
The bitwise NOT (~), or complement, is a unary operation that performs logical negation on each bit of the operand. By
performing negation of each bit, it actually produces the ones' complement of the given binary value.
x ~x
0 1
1 0

The bitwise XOR operator (^) performs operation on individual bits of the operands. The result of XOR operation is
shown in the table
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0

2.13.8 Bitwise Shift Operators

In bitwise shift operations, the digits are moved, or shifted, to the left or right. The CPU registers have a fixed number of available
bits for storing numerals, so when we perform shift operations; some bits will be "shifted out" of the register at one end, while the
same number of bits are "shifted in" from the other end.

In a left arithmetic shift, zeros are shifted in on the right. For example;

unsigned int x = 11000101;

Then x << 2 = 00010100

If a right arithmetic shift is performed on an unsigned integer then zeros are shifted on the left.

unsigned int x = 11000101;

Then x >> 2 = 00110001

2.13.9 Assignment Operators

The assignment operator is responsible for assigning values to the variables. While the equal sign (=) is the
fundamental assignment operator, C also supports other assignment operators that provide shorthand ways to
represent common variable assignments. They are shown in the table.

Operator Syntax Equivalent To

/= variable /= expression variable = variable / expression

\= variable \= expression variable = variable \ expression

*= variable *= expression variable = variable * expression

+= variable += expression variable = variable + expression

-= variable -= expression variable = variable expression

&= variable &= expression variable = variable & expression

^= variable ^= expression variable = variable ^ expression

<<= variable <<= amount variable = variable << amount

>>= variable >>= amount variable = variable >> amount

2.13.10 Comma Operator


44
The comma operator in C takes two operands. It works by evaluating the first and discarding its value, and then evaluates the
second and returns the value as the result of the expression. Comma separated operands when chained together are evaluated in
left-to-right sequence with the right-most value yielding the result of the expression. Among all the operators, the comma operator
has the lowest precedence. For example,
int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x = 6.

2.13.11 Sizeof Operator

sizeof is a unary operator used to calculate the sizes of data types. It can be applied to all data types. The operator returns the size
of the variable, data type or expression in bytes. 'sizeof' operator is used to determine the amount of memory space that the
variable/expression/data type will take. For example,

sizeof(char) returns 1, that is the size of a character data type. If we have,

int a = 10;

unsigned int result;

result = sizeof(a);

then result = 2

Q 15. Write short note on various category of operators present in C

2.14 Type Casting (or Type Conversion)

Type casting is a way to convert a variable from one data type to another data type. For example, if we want to store a long value
into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast
operator as follows:

(type_name) expression

Consider the following example where the cast operator causes the division of one integer variable by another to be performed as
a floating-point operation:

#include <stdio.h>
void main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );

When the above code is compiled and executed, it produces the following result:

Value of mean : 3.400000

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to
type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the
use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are
necessary.

2.14.1 Integer Promotion

45
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either
to int or unsigned int. Consider an example of adding a character in an int:
#include <stdio.h>
void main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}

When the above code is compiled and executed, it produces the following result:

Value of sum : 116

Here, value of sum is coming as 116 because compiler is doing integer promotion and converting the value of 'c' to ascii before
performing actual addition operation.

2.14.2 Usual Arithmetic Conversion

The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first
performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the
following hierarchy:

The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us
take following example to understand the concept:

#include <stdio.h>
void main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}

When the above code is compiled and executed, it produces the following result:

Value of sum : 116.000000

46
Here, it is simple to understand that first c gets converted to integer but because final value is double, so usual arithmetic
conversion applies and compiler convert i and c into float and add them yielding a float result.

Q 16. What is typecasting? Explain various types of typecasting mechanism present in C

2.15 Precedence of Operators


If more than one operators are involved in an expression then, C language has predefined rule of priority of operators. This rule of
priority of operators is called operator precedence.

In C, precedence of arithmetic operators(*,%,/,+,-) is higher than relational operators(==,!=,>,<,>=,<=) and precedence of


relational operator is higher than logical operators(&&, || and !). Suppose an expression:

(a>b+c&&d)

This expression is equivalent to:

((a>(b+c))&&d)

i.e, (b+c) executes first

then, (a>(b+c)) executes

then, (a>(b+c))&&d) executes

(a>b+c&&d)

This expression is equivalent to:

((a>(b+c))&&d)

i.e, (b+c) executes first


47
then, (a>(b+c)) executes

then, (a>(b+c))&&d) executes


2.16 Associativity of Operators
Associativity indicates in which order two operators of same precedence(priority) executes. Let us suppose an expression:

a==b!=c

Here, operators == and != have same precedence. The associativity of both == and != is left to right, i.e, the expression in left is
executed first and execution take pale towards right. Thus, a==b!=cequivalent to :

(a==b)!=c

The table below shows all the operators in C with precedence and associativity.

Note: Precedence of operators decreases from top to bottom in the given table.

Summary of C operators with precedence and associativity


Operator Meaning of operator Associativity
() Functional call Left to right
[] Array element reference
-> Indirect member selection
. Direct member selection
! Logical negation Right to left
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
* Multiply Left to right
/ Divide
% Remainder
+ Binary plus(Addition) Left to right
- Binary minus(subtraction)
<< Left shift Left to right
>> Right shift
< Less than Left to right
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to Left to right
!= Not equal to
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Left to right
= Simple assignment Right to left
*= Assign product
/= Assign quotient
%= Assign remainder
-= Assign sum
&= Assign difference
^= Assign bitwise AND
|= Assign bitwise XOR

48
<<= Assign bitwise OR
>>= Assign left shift
Assign right shift
, Separator of expressions Left to right

Q 17. What is operator precedence and associativity? Explain with examples?

Questions

1. In C programming what will be the value of r if r=p%q where p=-17 and q=5.
2. In C programming, what will be the output of the following code? Explain your answer.
3. What are identifiers, variables and constants? Mention rules to construct an identifier. Give some examples.
4. What is the meaning of scope of a variable? Give various types of scope in C programming?
5. Write a Program (WAP) in C in which values of variables x, y, x are input by the user, then their values are rotated such
that x has value of y, y has value of z, and z has value of y.
6. Explain datatypes in C language, mentioning their range, space they occupy in memory and keyword used for their
representation in memory.
7. Explain four storage classes in C, mentioning their place of storage, default initial value, scope and life of each item
8. What do you mean by operator precedence and associativity?
9. What do you mean by implicit and explicit typecasting?
10. Give any four format specifiers used in printf()
11. Explain the ternary operator in detail with example.
12. Explain various operators present in C?
13. Explain the general structure of a C program?
14. Explain logical and bit operators with example.
15. Explain logical and bit operators with example.
16. Write about the formatted and unformatted Input/Output functions in C.

Unit 3

Conditional Program Execution / Decision Making

Introduction

49
We have seen that a C program is a set of statements which are normally executed sequentially in the order in which they appear.
However, in practice, we have a number of situations where we may have to change the order of execution of the statements based
on certain conditions or repeat a group of statements until certain specified conditions are met. This involves a kind of decision
making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements
accordingly.

C language possesses such decision-making capabilities by supporting the following statements:


3.1 IF statement
3.2 IF-ELSE statement
3.3 Nesting of IF-ELSE statements
3.4 ELSE-IF ladder
3.5 SWITCH statement
3.6 GOTO statement
3.7 Conditional operator/ Ternary operator (? :)

These statements are popularly known as decision-making statements.

3.1 IF Statement:
Theif statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a
two way decision statement and is used in conjunction with an expression. It takes the following form:

if (test expression)
{
statement block 1;
}
statement x;

The statement block 1 may be a single statement or a group of statements. If the testexpression is true, the statement block 1 will
be executed; otherwise the statement block 1 will be skipped and the control will jump to the statement-x. When the condition is
true both the statement block 1 and the statement x are executed in sequence.

Flowchart

Program
void main()
{
int age;
printf(\nEnter Age);
scanf(%d,&age);
if(age>=18)
printf(\nYou are eligible to vote);
}
Output
Enter Age
20
You are eligible to vote
Enter Age
10
No output

The second run of the program does not produced any message because the expression (age>=18) results to false.
50
3.2 IF-ELSE Statement:
In the if-else construct, first the test expression is evaluated. If the expression is true, statement block 1 is executed and statement
block 2 is skipped. Otherwise, if the expression is false, statement block 2 is executed and statement block 1 is ignored. In any
case after the statement block 1 or 2 gets executed and finally the control will pass to statement x. Therefore, statement x is
executed in every case. It takes the following form:

if (test expression)
{
statement block1;
}
else
{
statement block 2;
}
statement x;

Flowchart

Program
// Program to find whether a number is even or odd.
#include<stdio.h>
void main()
{
int a;
printf("\n Enter the value of a : ");
scanf("%d", &a);
if(a%2==0)
printf("\n %d is even", a);
else
printf("\n %d is odd", a);
return 0;
}
Output
Enter the value of a
20
20 is even
Enter the value of a
13
13 is odd

3.3 Nesting of IF-ELSE Statements:


When a series of decisions are involved we may have to use more than one if-else statement in nested form as shown below:

if(test condition1)
{
If(test condition2)

51
{
statement block 1;
}
else
{
statement block 2;
}
}
else
{
statement block x;
}
statement y;

If the condition 1 is false, the statement block x will be executed; otherwise it continues to perform second test. If the condition 2
is true the statementblock 1 will be evaluated otherwise statementblock 2 will be executed and then the control is transferred to
statementy.

Flowchart

Program
void main()
{
int A,B,C;
printf(\nEnter the numbers);
scanf(%d%d%d, &A,&B,&C);
if(A>B)
{
if(A>C)
printf(A);
else
printf(C);
}
else
{
if(B>C)
printf(B);
else
printf(C);
}

3.4 ELSE-IF Ladder:


There is another way of putting ifs together when multipath decisions are involved. A multipath decisions is a chain of ifs in which
the statements associated with each else is an if. It takes the following general form:

52
This construct is known as the else if ladder. The conditions are evaluated from the top (of the ladder) downwards. As soon as true
condition is found the statement associated with it is executed and the control is transferred to the statement-x (skipping the rest of
the ladders). When all the conditions are false then the final else containing default statement will be executed.

Flowchart

Program
// Program to classify a number as positive, negative or zero.
#include<stdio.h>
main()
{
int num;
printf("\n Enter any number : ");
scanf("%d", &num);
if(num==0)
printf("\n The value is equal to zero");
else if(num>0)
printf("\n The number is positive");
else
printf("\n The number is negative");
return 0;
53
}

3.5 SWITCH Statement:


We have seen that when one of the many alternatives is to be selected we can use an if statement to control the selection. However
the complexity of such a program increases dramatically when the number of alternatives increases. The program becomes
difficult to read and follow. At times it may confuse even the person who designed it. Fortunately, C has a built in multi-way
decision statement known as switch. The switch statement tests the value of a given variable (or expression) against the list of case
values and when a match is found a block of statement associated with that case is executed.
The general form if given below:

switch ( expression )
{
case value-1:
block-1
break;
case value-2:
block-2
break;


default:
default-block
}
statement-x;

Flowchart

Program
void main()
{
char grade;
printf(Enter the grade of student);
scanf(%c,&grade);
switch(grade)
{
case 'A':
printf("\n Excellent");
break;
case 'B':
printf("\n Good");
break;
case 'C':
printf("\n Fair");
break;

54
default:
printf("\n Invalid Grade");
} }

3.6 GOTO Statement:


So far we discussed ways of controlling the flow of execution based on certain specified conditions. C supports the goto statement
to branch unconditionallyfrom one point to another in the program. Although it may not be essential to use the goto statement in a
highly structured language like C, there may be occasions when the use of goto might be desirable.
The goto requires a lablel in order to identify the place where the branch is to be made. A label is any valid variable name and
must be followed by colon. The label is placed immediately before the statement where the control is to be transferred. The
general forms of goto and label statements are shown below:
goto label; label:
statement;

lablel:
statement; goto label;

a) Forward jump b) Backward jump

The label can be anywhere in the program either before or after the goto label; statement.

During running a program when a statement like


goto begin;
is met, the flow of control will jump to the statement immediately following the label begin:. This happens unconditionally.
If the label is placed after the goto statement then it is called a forward jump and in case it is located before the goto statement, it
is said to be a backward jump.

Such infinite loops should be avoided in programming.

55
Program
int num, sum=0;
read: // label for go to statement
printf("\n Enter the number. Enter 999 to end : ");
scanf("%d", &num);
if (num != 999)
{
if(num < 0)
goto read; // jump to label- read
sum += num;
goto read; // jump to label- read
}
printf("\n Sum of the numbers entered by the user is = %d", sum);

3.7 Conditional Operator / Ternary Operator (? :):


The conditional operator is a combination of ? and :, and it takes three operands. This operator is popularly known as the
conditional or ternary operator. The general form of use of the conditional operator is as follows:
conditional expression ? expression1 : expression2;

The conditional expression is evaluated first. If the result is nonzero, expression1 is evaluated and is returned as the value of the
conditional expression. Otherwise expression2 is evaluated and its value is returned. For example the segment

if (x<0)
flag=0;
else
flag=1;

Can be written as

flag=(x<0)?0:1;

Program
#include <stdio.h>
main()
{
int a , b;
a = 10;
printf( "Value of b is %d\n", (a == 1) ? 20: 30 );

56
printf( "Value of b is %d\n", (a == 10) ? 20: 30 );
}

3.8. Looping / Iterative Statements


Iterative statements are used to repeat the execution of a list of statements, depending on the value of an integer expression.
A program loop (or iteration) therefore consists of two segments, one is known as body of the loop and other is known as the
control statements. Depending on the position of the control statement in a loop a control structure may be classified as:
a) Entry controlled loop: condition is tested before the start of the loop.
b) Exit controlled loop: test is performed at the end of the loop.

The entry controlled loop is also known as pre-test loop and exit controlled loop is known as post-test loop.
Iterative statements are used to repeat the execution of a list of statements, depending on the value of an integer expression. In this
section, we will discuss all these statements.

3.9 While loop


3.10 Do-while loop
3.11 For loop
A looping process in general would include the following 4 steps:
1. Initialization of counter
2. Test condition (check the value of counter)
3. Body of loop
4. Increment / Decrement (update counter)

3.9 While Loop


It is entry controlled loop. The while loop is used to repeat one or more statements while a particular condition is true. In the while
loop, the condition is tested before any of the statements in the statement block is executed. If the condition is true, only then the
statements will be executed otherwise the control will jump to the immediate statement outside the while loop block.We must
constantly update the condition of the while loop.

statement x;
while (condition)
{
statement_block;
}
statement y;

57
Program to print numbers from 0 to 10 using while loop
#include<stdio.h>
int main()
{
int i = 0;
while(i<=10)
{
printf(\n %d, i);
i = i + 1; // condition updated
}
return 0;
}

3.10 Do While Loop


The do-while loop is similar to the while loop. The only difference is that in a do-while loop, the test condition is tested at the end
of the loop. So it is known as exit controlled loop. The body of the loop gets executed at least one time (even if the condition is
false). The major disadvantage of using a do while loop is that it always executes at least once, so even if the user enters some
invalid data, the loop will execute. Do-while loops are widely used to print a list of options for a menu driven program.

statement x;
do
{
statement_block;
} while (condition);
statement y;

Program to print numbers from 0-10 using do-while loop


#include<stdio.h>
int main()
{
int i = 0;
do
{

58
printf(\n %d, i);
i = i + 1;
} while(i<=10);
return 0;
}

3.11 For Loop


It is a entry controlled loop. The for loop is used to repeat a task until a particular condition is true. The syntax of a for loop is as
follows

for (initialization; condition; increment/decrement/update)


{
statement block;
}
statement Y;

When a for loop is used, the loop variable is initialized only once.
With every iteration of the loop, the value of the loop variable is updated and the condition is checked. If the condition is true,
the statement block of the loop is executed else, the statements comprising the statement block of the for loop are skipped and
the control jumps to the immediate statement following the for loop body.
Updating the loop variable may include incrementing the loop variable, decrementing the loop variable or setting it to some
other value like, i +=2, where i is the loop variable.

Look at the code given below which print first n numbers using a for loop.

Program
#include<stdio.h>
int main()
{
int i, n;
printf(\n Enter the value of n :);
scanf(%d, &n);
for(i=0; i<= n; i++)
{
printf(\n %d, i);
}
return 0;
}

3.12 Break statement

59
The break statement is used to terminate the execution of the nearest enclosing loop in which it appears. When compiler
encounters a break statement, the control passes to the statement that follows the loop in which the break statement appears. Its
syntax is quite simple, just type keyword break followed with a semi-colon.
break;
In switch statement if the break statement is missing then every case from the matched case label to the end of the switch,
including the default, is executed.

Program
int i;
for(i=1; i<= 5; i++)
{ if (i==3)
break;
printf(\t %d, i);
}
Output
1
2

3.13 Continue Statement


The continue statement can only appear in the body of a loop. When the compiler encounters a continue statement then the rest of
the statements in the loop are skipped and the control is unconditionally transferred to the loop-continuation portion of the nearest
enclosing loop. Its syntax is quite simple, just type keyword continue followed with a semi-colon.

continue;

If placed within a for loop, the continue statement causes a branch to the code that updates the loop variable.

Program
int i;
for(i=1; i<= 5; i++)
{ if (i==3)
continue;
printf(\t %d, i);
}
Output
1
2
4
5

Functions

3.14 Introduction
60
C enables its programmers to break up a program into segments commonly known as functions, each of which can be written
more or less independently of the others. Every function in the program is supposed to perform a well-defined task. Therefore, the
program code of one function is completely insulated from that of other functions. Every function has a name which acts as an
interface to the outside world in terms of how information is transferred to it and how results generated by the function are
transmitted back from it.

In the fig, main() calls another function, func1() to perform a well-defined task. main() is known as the calling function and
func1() is known as the called function. When the compiler encounters a function call, instead of executing the next statement in
the calling function, the control jumps to the statements that are a part of the called function. After the called function is executed,
the control is returned back to the calling program.

Any function can call any other function.

3.15 Why do we need functions?


Dividing the program into separate well defined functions facilitates each function to be written and tested separately.
This simplifies the process of getting the total program to work.
Understanding, coding and testing multiple separate functions are far easier than doing the same for one huge function.
If a big program has to be developed without the use of any function (except main()), then there will be countless lines in
the main() .
All the libraries in C contain a set of functions that the programmers are free to use in their programs. These functions
have been prewritten and pre-tested, so the programmers use them without worrying about their code details. This speeds up
program development.

3.16 Terminology of functions


A function, f that uses another function g, is known as the calling function and g is known as the called function.
The inputs that the function takes are known as arguments
When a called function returns some result back to the calling function, it is said to return that result.
The calling function may or may not pass parameters to the called function. If the called function accepts arguments, the
calling function will pass parameters, else not.
Main() is the function that is called by the operating system and therefore, it is supposed to return the result of its
processing to the operating system.

3.17 Function declaration


Function declaration is a declaration statement that identifies a function with its name, a list of arguments that it accepts
and the type of data it returns.
The general format for declaring a function that accepts some arguments and returns some value as result can be given
as:
return_data_type function_name(data_type variable1, data_type variable2,..);
No function can be declared within the body of another function.

61
Example, float avg ( int a, int b);

3.18 Function definition


Function definition consists of a function header that identifies the function, followed by the body of the function
containing the executable code for that function
When a function defined, space is allocated for that function in the memory.
The syntax of a function definition can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..)


{
.
statements
.
return( variable);
}

The no. and the order of arguments in the function header must be same as that given in function declaration statement.

3.19 Function call


The function call statement invokes the function.
When a function is invoked the compiler jumps to the called function to execute the statements that are a part of that
function.
Once the called function is executed, the program control passes back to the calling function.
Function call statement has the following syntax.

function_name(variable1, variable2, );

Program
#include<stdio.h>
int sum(int a, int b); // FUNCTION DECLARATION
int main()
{
int num1, num2, total = 0;
printf(\n Enter the first number : );
scanf(%d, &num1);
printf(\n Enter the second number : );
scanf(%d, &num2);
total = sum(num1, num2); // FUNCTION CALL
printf(\n Total = %d, total);
return 0;
}
// FUNCTION DEFNITION
int sum ( int a, int b) // FUNCTION HEADER
{ // FUNCTION BODY
return (a + b);
}

3.20 Return statement


The return statement is used to terminate the execution of a function and return control to the calling function. When the
return statement is encountered, the program execution resumes in the calling function at the point immediately following the
function call.
By default, the return type of a function is int.
For functions that has no return statement, the control automatically returns to the calling function after the last statement
of the called function is executed.

3.21 Passing parameters to the function


There are two ways in which arguments or parameters can be passed to the called function.
Call by value in which values of the variables are passed by the calling function to the called function.
Call by reference in which address of the variables are passed by the calling function to the called function.

62
3.21.1 Call by value
In the Call by Value method, the called function creates new variables to store the value of the arguments passed to it. Therefore,
the called function uses a copy of the actual arguments to perform its intended task.
If the called function is supposed to modify the value of the parameters passed to it, then the change will be reflected only in the
called function. In the calling function no change will be made to the value of the variables.

#include<stdio.h>
void add( int n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 20
The value of num after calling the function = 2

3.21.2 Call by reference


In call by reference, we declare the function parameters as references rather than normal variables.
To indicate that an argument is passed using call by reference, an ampersand sign (&) is placed after the type in the parameter list.
This way, changes made to that parameter in the called function body will then be reflected in its value in the calling program.

#include<stdio.h>
void add( int &n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(&num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add( int *n)
{
*n = *n + 10;
printf("\n The value of num in the called function = %d", n);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 20
The value of num after calling the function = 20

3.22 Recursive functions


A recursive function is a function that calls itself to solve a smaller version of its task until a final call is made which does not
require a call to itself.
Every recursive solution has two major cases, they are base case, in which the problem is simple enough to be solved directly
without making any further calls to the same function recursive case, in which first the problem at hand is divided into simpler
sub parts.
63
Second the function calls itself but with sub parts of the problem obtained in the first step. Third, the result is obtained by
combining the solutions of simpler sub-parts.

Finding Factorial of a Number using Recursion

Base case is when n=1, because if n = 1, the result is known to be 1

Recursive case of the factorial function will call itself but with a smaller value of n, this case can be given as

factorial(n) = n X factorial (n-1)

#include<stdio.h>
int Fact(int)
{ if(n==1)
retrun 1;
return (n * Fact(n-1));
}
main()
{ int num;
scanf(%d, &num);
printf(\n Factorial of %d = %d, num, Fact(num));
return 0;
}

The Fibonacci series can be given as:


0 1 1 2 3 5 8 13 21 34 55
That is, the third term of the series is the sum of the first and second terms. On similar grounds, fourth term is the sum of second
and third terms, so on and so forth. Now we will design a recursive solution to find the nth term of the Fibonacci series. The
general formula to do so can be given as

main()
{ int n;
printf(\n Enter the number of terms in the series : );
scanf(%d, &n);
for(i=0;i<n;i++)
printf(\n Fibonacci (%d) = %d, i, Fibonacci(i));
}
int Fibonacci(int num)
{ if(num == 0 || num==1)
return num;
return ( Fibonacci (num - 1) + Fibonacci(num 2));
}

3.23 Types of recursion


Any recursive function can be characterized based on:
whether the function calls itself directly or indirectly (direct or indirect recursion).
whether any operation is pending at each recursive call (tail-recursive or not).
the structure of the calling pattern (linear or tree-recursive).

64
3.23.1 Direct Recursion
A function is said to be directly recursive if it explicitly calls itself. For example, consider the function given below.

int Func( int n)


{
if(n==0)
retrun n;
return (Func(n-1));
}

3.23.2 Indirect Recursion


A function is said to be indirectly recursive if it contains a call to another function which ultimately calls it. Look at the functions
given below. These two functions are indirectly recursive as they both call each other.

int Func1(int n) int Func2(int x)


{ {
if(n==0) return Func1(x-1);
return n; }
return Func2(n);
}

3.23.3 Tail Recursion


A recursive function is said to be tail recursive if no operations are pending to be performed when the recursive function returns to
its caller. That is, when the called function returns, the returned value is immediately returned from the calling function.Tail
recursive functions are highly desirable because they are much more efficient to use as in their case, the amount of information
that has to be stored on the system stack is independent of the number of recursive calls.

int Fact(n) int Fact1(int n, int res)


{ {
return Fact1(n, 1); if (n==1)
} return res;
return Fact1(n-1, n*res);
}

3.23.4 Linear and Tree Recursion


Recursive functions can also be characterized depending on the way in which the recursion grows- in a linear fashion or
forming a tree structure.
In simple words, a recursive function is said to be linearly recursive when no pending operation involves another
recursive call to the function. For example, the factorial function is linearly recursive as the pending operation involves only
multiplication to be performed and does not involve another call to Fact.
On the contrary, a recursive function is said to be tree recursive (or non-linearly recursive) if the pending operation
makes another recursive call to the function. For example, the Fibonacci function Fib in which the pending operations
recursively calls the Fib function.

65
3.24 Pros and cons of recursion
Pros: Recursive solutions often tend to be shorter and simpler than non-recursive ones.
Code is clearer and easier to use
Recursion represents like the original formula to solve a problem.
Follows a divide and conquer technique to solve problems
In some (limited) instances, recursion may be more efficient
Cons: For some programmers and readers, recursion is a difficult concept.
Recursion is implemented using system stack. If the stack space on the system is limited, recursion to a deeper level will
be difficult to implement.
Aborting a recursive process in midstream is slow and sometimes nasty.
Using a recursive function takes more memory and time to execute as compared to its non-recursive counter part.
It is difficult to find bugs, particularly when using global variables

Some Important Programs

Program: To calculate factorial of a number.


#include <stdio.h>
int main()
{
int c, n, fact = 1;

printf("Enter a number to calculate it's factorial\n");


scanf("%d", &n);

for (c = 1; c <= n; c++)


fact = fact * c;

printf("Factorial of %d = %d\n", n, fact);

return 0;
}

Program: To calculate sum of digits of a number.


#include <stdio.h>
int main()
{
int n, t, sum = 0, remainder;

printf("Enter an integer\n");
scanf("%d", &n);

t = n;

while (t != 0)
{
remainder = t % 10;
sum = sum + remainder;
t = t / 10;
}

printf("Sum of digits of %d = %d\n", n, sum);

return 0;
}

Program: To reverse a number.


#include <stdio.h>
int main()
{
int n, reverse = 0;

printf("Enter a number to reverse\n");


66
scanf("%d", &n);

while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}

printf("Reverse of entered number is = %d\n", reverse);


return 0;
}

Program: To check whether a given number is armstrong or not.


#include <stdio.h>
int main()
{
int number, sum = 0, temp, remainder;

printf("Enter an integer\n");
scanf("%d",&number);

temp = number;

while( temp != 0 )
{
remainder = temp%10;
sum = sum + remainder*remainder*remainder;
temp = temp/10;
}

if ( number == sum )
printf("Entered number is an armstrong number.\n");
else
printf("Entered number is not an armstrong number.\n");

return 0;
}

Program: To generate Fibonacci Series.


#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;

printf("Enter the number of terms\n");


scanf("%d",&n);

printf("First %d terms of Fibonacci series are :-\n",n);

for ( c = 0 ; c < n ; c++ )


{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;

67
}

Program: To calculate LCM and GCD.


#include <stdio.h>
int main()
{
int a, b, x, y, t, gcd, lcm;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
a = x;
b = y;
while (b != 0)
{
t = b;
b = a % b;
a = t;
}

gcd = a;
lcm = (x*y)/gcd;

printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);


printf("Least common multiple of %d and %d = %d\n", x, y, lcm);
return 0;
}

68
Question
1. Describe about the types of looping statements in C with necessary syntax.
2. Write a C program to find the multiplication of two matrices.
3. What are the types of function? Write a C program to find the factorial of a given number using recursion.
4. What is the difference between break and continue? Describe the structure of switch-case with neat example.

5. What are the different types of functions? Write a program in C to short list of names of students in an ascending order.
6. Write a program to print following pattern
1
23
456
7 8 9 10
7. Define recursive function. Write a program in C to generate Fibnocii series (0 1 1 2 3 5 8 13) using recursive function.
8. Write a C program to find the sum of individual digits in a five digit number.
9. Write the difference between call by value and call by reference with suitable example.
10. Write a program to find greatest among three numbers using conditional operator.
11. Differentiate between nested-if and switch statements in C with example.
12. Write a program in C to sort list of 10 integers in an ascending order.
13. Write a program to multiply the two matrices of MxN.

14. Write the purpose and syntax of at least two iterative statements in C.
15. WAP to generate fabonacci series up to the last term less than 100. Also calculate sum and total count of the fabonacci
numbers.
16. What is sorting? Give flowchart and algorithm to sort the integer numbers.
17. Given two matrices of 4x4. Write the functions sum_matrix() and multiply_matix() to add and multiply two matices.
18. Differentiate between call by value and call by reference.
19. Write a program to calculate GCD.
20. WAP to calculate the multiplication of all the digits of a 5 digit number.
21. Write a program which stores the marks of N students in integer array. Calculate average marks obtained and deviation from
the average.
22. Explain ternary operator.
23. Define user defined and library functions.
24. What are iterative control statements? Differentiate between while loop and do-while loop.
25. Define recursion. Give its advantage. Which data structure is used to implement recursion? Write a program to calculate
factorial of a number using recursion.
26. Write a program to check whether a number is perfect number or not. If the sum of factor is equal to number itself then it is a
perfect number. E.g Factor of 6 are 1, 2, 3 whose sum 1+2+3=6.
27. Write a program to find the prime numbers between the given range.

28. Write a program to generate following pattern.


A
BA
ABA
BABA
ABABA
29. Write a program o read five digit number if it is even then add the digits otherwise multiply them.
30. Write a program to generate the given series upto less than 200.
1 4 + 9 16 + 25 .
31. Write a program to read age of 100 persons and count the number of persons in the age group 50 to 60. Use for and continue
statements.
32. Write a program to check whether a number is even or odd without else option.

69
Unit 4
4.1 Array

An array is a collection of data items, all of the same type, accessed using a common name.
A one-dimensional array is like a list. A two dimensional array is like a table; The C language places no limits on the
number of dimensions in an array, though specific implementations may.

4.2 Declaring Arrays

Array variables are declared identically to variables of their data type, except that the variable name is followed by one
pair of square [ ] brackets for each dimension of the array.
Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.

Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.

Examples:

int i_Array[ 10 ];
float f_Array[ 1000 ];

4.3 Initializing Arrays

Arrays may be initialized when they are declared, just as any other variables.
Place the initialization data in curly {} braces following the equals sign. Note the use of commas in the examples below.

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array
elements will be automatically initialized to zero.

If an array is to be completely initialized, the dimension of the array is not required. The compiler will automatically size
the array to fit the initialized data. ( Variation: Multidimensional arrays - see below. )

Examples:

int i_Array[ 6 ] = { 1, 2, 3, 4, 5, 6 };
float f_Array[ 100 ] = { 1.0, 5.0, 20.0 };

4.4 Using Arrays


Elements of an array are accessed by specifying the index (offset ) of the desired element within square [ ] brackets after
the array name.
Array subscripts must be of integer type.

VERY IMPORTANT: Array indices start at zero in C, and go to one less than the size of the array. For example, a five
element array will have indices zero through four. This is because the index in C is actually an offset from the beginning
of the array. ( The first element is at the beginning of the array, and hence has zero offset. )

Sample Programs Using 1-D Arrays

The first sample program uses loops and arrays to calculate the first twenty Fibonacci numbers. Fibonacci numbers are
used to determine the sample points used in certain optimization methods.

/* Program to calculate the first 20 Fibonacci numbers. */

#include <stdlib.h>
#include <stdio.h>

int main( void ) {

70
int i, fibonacci[ 20 ];

fibonacci[ 0 ] = 0;
fibonacci[ 1 ] = 1;

for( i = 2; i < 20; i++ )


fibonacci[ i ] = fibonacci[ i - 2 ] + fibonacci[ i - 1 ];

for( i = 0; i < 20; i++ )


printf( "Fibonacci[ %d ] = %f\n", i, fibonacci[ i ] );

} /* End of sample program to calculate Fibonacci numbers */

4.5 Multidimensional Arrays

Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets after the variable name in the
declaration statement.
One dimensional arrays do not require the dimension to be given if the array is to be completely initialized. By analogy,
multi-dimensional arrays do not require the first dimension to be given if the array is to be completely initialized. All
dimensions after the first must be given in any case.

For two dimensional arrays, the first dimension is commonly considered to be the number of rows, and the second
dimension the number of columns.

Two dimensional arrays are considered by C/C++ to be an array of ( single dimensional arrays ). For example, "int
numbers[ 5 ][ 6 ]" would refer to a single dimensional array of 5 elements, wherein each element is a single dimensional
array of 6 integers.

C stores two dimensional arrays by rows, with all elements of a row being stored together as a single unit.

Multidimensional arrays may be completely initialized by listing all data elements within a single pair of curly {} braces,
as with single dimensional arrays.

Sample Program Using 2-D Arrays

/* Sample program Using 2-D Arrays */

#include <stdlib.h>
#include <stdio.h>

int main( void ) {

/* Program to add two multidimensional arrays */

int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };


int b[ 2 ][ 3 ] = { { 1, 2, 3 }, { 3, 2, 1 } };
int sum[ 2 ][ 3 ], row, column;

/* First the addition */

for( row = 0; row < 2; row++ )


for( column = 0; column < 3; column++ )
sum[ row ][ column ] =
a[ row ][ column ] + b[ row ][ column ];

/* Then print the results */

printf( "The sum is: \n\n" );

for( row = 0; row < 2; row++ ) {


for( column = 0; column < 3; column++ )
71
printf( "\t%d", sum[ row ][ column ] );
printf( '\n' ); /* at end of each row */
}
return 0;
}
The C language gives you five ways to create a custom data type:
The structure, which is a grouping of variables under one name and is called an aggregate data
type. (The terms compound or conglomerate are also commonly used.)
The union, which enables the same piece of memory to be defined as two or more different types of variables.
The bit-field, which is a special type of structure or union element that allows easy access to
individual bits.
The enumeration, which is a list of named integer constants.
The typedef keyword, which defines a new name for an existing type.

4.6 Structures
A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information
together. A structure declaration forms a template that can be used to create structure objects (that is, instances of a structure). The
variables that make up the structure are called members. (Structure members are also commonly referred to as elements or fields.)
The following code fragment shows how to declare a structure that defines the name and address fields. The keyword struct tells
the compiler that a structure is being declared.

struct addr
{
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
};
Notice that the declaration is terminated by a semicolon. This is because a structure declaration is a statement. Also, the structure
tag addr identifies this particular data structure and is its type specifier. At this point, no variable has actually been created. Only
the form of the data has been defined.
When you declare a structure, you are defining an aggregate type, not a variable. Not until you declare a variable of that type does
one actually exist. To declare a variable (that is, a physical object) of type addr, write:
struct addr info;
This declares a variable of type addr called addr_info. Thus, addr describes the form of a structure (its type), and addr_info is
an instance (an object) of the structure. When a structure variable (such as addr_info) is declared, the compiler automatically
allocates Sufficient memory to accommodate all of its members. The general form of a structure declaration is
struct tag {
type member-name;
type member-name;
type member-name;
} structure-variables;

4.6.1 Accessing Structure Members


Individual members of a structure are accessed through the use of the . operator (usually called the dot operator). For example, the
following statement assigns the ZIP code 12345 to the zip field of the structure variable addr_info declared earlier:
addr_info.zip = 12345;

The general form for accessing a member of a structure is object-name.member-name Therefore, to print the ZIP code on the
screen, write
printf("%lu", addr_info.zip);

In the same fashion, the character array addr_info.name can be used in a call to gets( ), as shown here:
gets(addr_info.name);

4.6.2 Structure Assignments


The information contained in one structure can be assigned to another structure of the same type
using a single assignment statement. You do not need to assign the value of each member separately. The following program
illustrates structure assignments:
#include <stdio.h>
int main(void)
72
{
struct {
int a;
int b;
} x, y;
x.a = 10;
y = x; /* assign one structure to another */
printf("%d", y.a);
return 0;
}

After the assignment, y.a will contain the value 10.

4.6.3 Arrays of Structures


To declare an array of structures, you must first define a structure and then declare an array variable of that type. For example, to
declare a 100-element array of structures of type addr defined earlier, write
struct addr addr_list[100];

This creates 100 sets of variables that are organized as defined in the structure addr. To access a specific structure, index the array
name. For example, to print the ZIP code of structure 3, write
printf("%lu", addr_list[2].zip);
Like all array variables, arrays of structures begin indexing at 0.

When you want to refer to a specific structure within an array of structures, index the structure array name. When you want to
index a specific element of a structure, index the element. Thus, the following statement assigns 'X' to the first character of name
in the third structure of addr_list.
addr_list[2].name[0] = 'X';

4.6.4 Passing Structures to Functions

4.6.4.1 Passing Structure Members to Functions


When you pass a member of a structure to a function, you are passing the value of that member to the function. It is irrelevant that
the value is obtained from a member of a structure.

For example,
consider this structure:
struct fred
{
char x;
int y;
float z;
char s[10];
} mike;
Here are examples of each member being passed to a function:
func(mike.x); /* passes character value of x */
func2(mike.y); /* passes integer value of y */
func3(mike.z); /* passes float value of z */
func4(mike.s); /* passes address of string s */
func(mike.s[2]); /* passes character value of s[2] */
In each case, it is the value of a specific element that is passed to the function. It does not matter that the element is part of a larger
unit.
If you wish to pass the address of an individual structure member, put the & operator before the
structure name. For example, to pass the address of the members of the structure mike, write
func(&mike.x); /* passes address of character x */
func2(&mike.y); /* passes address of integer y */
func3(&mike.z); /* passes address of float z */
func4(mike.s); /* passes address of string s */
func(&mike.s[2]); /* passes address of character s[2] */
Note that the & operator precedes the structure name, not the individual member name.

4.6.4.2 Passing Entire Structures to Functions

73
When a structure is used as an argument to a function, the entire structure is passed using the normal call-by-value method. Of
course, this means that any changes made to the contents of the parameter inside the function do not affect the structure passed as
the argument.
When using a structure as a parameter, remember that the type of the argument must match the type of the parameter. For
example, in the following program both the argument arg and the parameter parm are declared as the same type of structure.
#include <stdio.h>
/* Define a structure type. */
struct struct_type {
int a, b;
char ch;
};
void f1(struct struct_type parm);
int main(void)
{
struct struct_type arg;
arg.a = 1000;
f1(arg);
return 0;
}
void f1(struct struct_type parm)
{
printf(''%d", parm.a);
}
As this program illustrates, if you will be declaring parameters that are structures, you must make the declaration of the structure
type global so that all parts of your program can use it. For example, had struct_type been declared inside main( ), it would not
have been visible to f1( ).

When a structure is a member of another structure, it is called a nested structure. For example, the structure address is nested
inside emp in this example:
struct emp {
struct addr address; /* nested structure */
float wage;
} worker;
Here, structure emp has been defined as having two members. The first is a structure of type addr, which contains an employee's
address. The other is wage, which holds the employee's wage. The following code fragment assigns 93456 to the zip element of
address.
worker.address.zip = 93456;

4.7 Unions
A union is a memory location that is shared by two or more different types of variables. A union provides a way of interpreting the
same bit pattern in two or more different ways. Declaring a union is similar to declaring a structure. Its general form is
union tag {
type member-name;
type member-name;
type member-name;
.
.
.
} union-variables;
For example:
union u_type {
int i;
char ch;
};
This declaration does not create any variables. You can declare a variable either by placing its name at the end of the declaration
or by using a separate declaration statement. To declare a union variable called cnvt of type u_type using the definition just
given, write
union u_type cnvt;
In cnvt, both integer i and character ch share the same memory location. Of course, i occupies 2
bytes (assuming 2-byte integers), and ch uses only 1.
When a union variable is declared, the compiler automatically allocates enough storage to hold the largest member of the union.
For example, (assuming 2-byte integers) cnvt is 2 bytes long so that it can hold i, even though ch requires only 1 byte.

74
To access a member of a union, use the same syntax that you would use for structures: the dot and arrow operators. If you are
operating on the union directly, use the dot operator. If the union is accessed through a pointer, use the arrow operator. For
example, to assign the integer 10 to element i of cnvt, write
cnvt.i = 10;

4.8 Enumerations
An enumeration is a set of named integer constants. Enumerations are common in everyday life. For example, an enumeration of
the coins used in the United States is penny, nickel, dime, quarter, half-dollar, dollar.
Enumerations are defined much like structures; the keyword enum signals the start of an enumeration type. The general form for
enumerations is
enum tag { enumeration list } variable_list ;
Here, both the tag and the variable list are optional. (But at least one must be present.) The following code fragment defines an
enumeration called coin:
enum coin { penny, nickel, dime, quarter, half_dollar, dollar};
The enumeration tag name can be used to declare variables of its type. The following declares
money to be a variable of type coin:
enum coin money;
Given these declarations, the following types of statements are perfectly valid:
money = dime;
if(money==quarter)
printf(''Money is a quarter.\n");
The key point to understand about an enumeration is that each of the symbols stands for an integer value. As such, they can be
used anywhere that an integer can be used. Each symbol is given a value one greater than the symbol that precedes it. The value of
the first enumeration symbol is 0. Therefore,
printf("%d %d", penny, dime);
displays 0 2 on the screen.
You can specify the value of one or more of the symbols by using an initializer. Do this by
following the symbol with an equal sign and an integer value. Symbols that appear after an
initializer are assigned values greater than the preceding value. For example, the following code
assigns the value of 100 to quarter:
enum coin { penny, nickel, dime, quarter=100, half_dollar, dollar};
Now, the values of these symbols are
penny 0
nickel 1
dime 2
quarter 100
half_dollar 101
dollar 102

4.9 Strings
The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array.
Character arrays are many a time also called strings.
A string constant is a one-dimensional array of characters terminated by a null ( \0 ). For example,
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
Each character in the array occupies one byte of memory and the last character is always \0. \0 is called null character. A string
not terminated by a \0 is not really a string, but merely a collection of characters.
/* Program to demonstrate printing of a string */
main( )
{
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( i <= 7 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
And here is the output...
Klinsman
Can we write the while loop without using the final value 7? We can; because we know that each character array always ends with
a \0. Following program illustrates this.
main( )
{

75
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( name[i] != `\0' )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
And here is the output...
Klinsman

Here is another version of the


same program; this one uses a pointer to access the array elements.
main( )
{
char name[ ] = "Klinsman" ;
char *ptr ;
ptr = name ; /* store base address of string */
while ( *ptr != `\0' )
{
printf ( "%c", *ptr ) ;
ptr++ ;
}
}

The %s used in printf( ) is a format specification for printing out a string. The same specification can be used to receive a string
from the keyboard, as shown below.
main( )
{
char name[25] ;
printf ( "Enter your name " ) ;
scanf ( "%s", name ) ;
printf ( "Hello %s!", name ) ;
}
And here is a sample run of the program...
Enter your name Debashish
Hello Debashish!

Note that the declaration char name[25] sets aside 25 bytes under the array name[ ], whereas the scanf( ) function fills in the
characters typed at keyboard into this array until the enter key is hit. Once enter is hit, scanf( ) places a \0 in the array.
While entering the string using scanf( ) we must be cautious about two things:
a) The length of the string should not exceed the dimension of the character array. This is because the C compiler doesnt perform
bounds checking on character arrays. Hence, if you carelessly exceed the bounds there is always a danger of overwriting
something important, and in that event, you would have nobody to blame but yourselves.
b) scanf( ) is not capable of receiving multi-word strings. Therefore names such as Debashish Roy would be unacceptable. The
way to get around this limitation is by using the function gets( ). The usage of functions gets( ) and its counterpart puts( ) is
shown below.

main( )
{
char name[25] ;
printf ( "Enter your full name " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
}
And here is the output...
Enter your name Debashish Roy
Hello!
Debashish Roy
unlike printf( ), puts( ) places the cursor on the next line.

4.10 Pointers and Strings

76
Suppose we wish to store Hello. We may either store it in a string or we may ask the C compiler to store it at some location in
memory and assign the address of the string in a char pointer. This is shown below:
char str[ ] = "Hello" ;
char *p = "Hello" ;
There is a subtle difference in usage of these two forms. For example, we cannot assign a string to another, whereas, we can assign
a char pointer to another char pointer. This is shown in the
following program.
main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Also, once a string has been defined it cannot be initialized to another set of characters. Unlike strings, such an operation is
perfectly valid with char pointers.

main( )
{
char str1[ ] = "Hello" ;
char *p = "Hello" ;
str1 = "Bye" ; /* error */
p = "Bye" ; /* works */
}

4.11 Standard Library String Functions


With every C compiler a large set of useful string handling library functions are provided. Figure 9.2 lists the more commonly
used functions along with their purpose.
Function Use
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of
another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
strcmpi Compares two strings without regard to case ("i" denotes
that this function ignores case)
stricmp Compares two strings without regard to case (identical to strcmpi)
strnicmp Compares first n characters of two strings without regard to case
strdup Duplicates a string
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string
strset Sets all characters of string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses string

Out of the above list we shall discuss the functions strlen( ), strcpy( ), strcat( ) and strcmp( ), since these are the most commonly
used functions.

strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the following program.
main( )
{
char arr[ ] = "Bamboozled" ;
int len1, len2 ;
len1 = strlen ( arr ) ;
77
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13

Note that in the first call to the function strlen( ), we are passing the base address of the string, and the function in turn returns the
length of the string. While calculating the length it doesnt count
\0. Even in the second call,
len2 = strlen ( "Humpty Dumpty" ) ;
what gets passed to strlen( ) is the address of the string and not the string itself. Can we not write a function xstrlen( ) which
imitates the standard library function strlen( )? Let us give it a try...

/* A look-alike of the function strlen( ) */


main( )
{
char arr[ ] = "Bamboozled" ;
int len1, len2 ;
len1 = xstrlen ( arr ) ;
len2 = xstrlen ( "Humpty Dumpty" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}
xstrlen ( char *s )
{
int length = 0 ;
while ( *s != '\0' )
{
length++ ;
s++ ;
}
return ( length ) ;
}
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13

strcpy( )
This function copies the contents of one string into another. The base addresses of the source and target strings should be supplied
to this function. Here is an example of strcpy( ) in action...
main( )
{
char source[ ] = "Sayonara" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Sayonara
target string = Sayonara

Let us now attempt to mimic strcpy( ),via our own string copy function, which we will call xstrcpy()
main( )
{
char source[ ] = "Sayonara" ;
char target[20] ;
xstrcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
78
xstrcpy ( char *t, char *s )
{
while ( *s != '\0' )
{
*t = *s ;
s++ ;
t++ ;
}
*t = '\0' ;
}
The output of the program would be...
source string = Sayonara
target string = Sayonara
Note that having copied the entire source string into the target string, it is necessary to place a \0 into the target string, to mark its
end.

strcat( )
This function concatenates the source string at the end of the target string. For example, Bombay and Nagpur on
concatenation would result into a string BombayNagpur. Here is an example of strcat( ) at work.
main( )
{
char source[ ] = "Folks!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Folks!
target string = HelloFolks!

strcmp( )
This is a function which compares two strings to find out whether they are same or different. The two strings are compared
character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. If the two strings
are identical, strcmp( ) returns a value zero. If theyre not, it returns the numeric difference between the ASCII values of the first
non-matching pairs of characters. Here is a program which puts strcmp( ) in action.
main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
And here is the output...
0 4 -32
In the first call to strcmp( ), the two strings are identicalJerry and Jerryand the value returned by strcmp( ) is zero. In the
second call, the first character of Jerry doesn't match with the first character of Ferry and the result is 4, which is the numeric
difference between ASCII value of J and ASCII value of F. In the third call to strcmp( ) Jerry doesnt match with Jerry
boy, because the null character at the end of Jerry doesnt match the blank in Jerry boy. The value returned is -32, which is
the value of null character minus the ASCII value of space, i.e., \0 minus
, which is equal to -32.

4.11 Two-Dimensional Array of Characters/ Array of Strings


In Array of Strings each row is used to hold a separate string.
Our example program asks you to type your name. When you do so, it checks your name against a master list to see if you are
worthy of entry to the palace. Heres the program...

#define FOUND 1
#define NOTFOUND 0
main( )
{
79
char masterlist[6][10] = {
"akshay",
"parag",
"raman",
"srinivas",
"gopal",
"rajesh"
};
int i, flag, a ;
char yourname[10] ;
printf ( "\nEnter your name " ) ;
scanf ( "%s", yourname ) ;
flag = NOTFOUND ;
for ( i = 0 ; i <= 5 ; i++ )
{
a = strcmp ( &masterlist[i][0], yourname ) ;
if ( a == 0 )
{
printf ( "Welcome, you can enter the palace" ) ;
flag = FOUND ;
break ;
}
}
if ( flag == NOTFOUND )
printf ( "Sorry, you are a trespasser" ) ;
}
And here is the output for two sample runs of this program...
Enter your name dinesh
Sorry, you are a trespasser
Enter your name raman
Welcome, you can enter the palace
The order of the subscripts in the array declaration is important. The first subscript gives the number of names in the array, while
the second subscript gives the length of each item in the array. Instead of initializing names, had these names been supplied from
the keyboard, the program segment would have looked like this...
for ( i = 0 ; i <= 5 ; i++ )
scanf ( "%s", &masterlist[i][0] ) ;

80
Questions
1. Write a program in C to read a (54) matrix using array and to calculate the following:

i) Sum of the elements of the third row of the matrix.


ii) Sum of all the elements of the matrix.
2. Write algorithm and function program to sort an array of integer into descending order, where the size of array is input by
user.
3. Define a structure called cricket that will describe the following information:
player name
team name
batting average
Using cricket, declare an array player with 50 elements and write a program to read the information about all the 50
players and print a team-wise list containing names of players with their batting average.
4. Write a program which will read a string and rewrite it in the alphabetical order. For example the word STRING should
be written as GINRST.

5. List the differences between structure and union.


6. Explain in detail about 1-Dimensional and 2-Dimensional array declaration, accessing elements, initialization with
suitable examples. Write a program to multiply two NN matrix.
7. Discuss String handling function.
8. Write a program in C that accepts the Rollno and name of 60 students in a class along with their marks in Physics,
9. Chemistry and Mathematics. Print the roll no. and name of top 10 students on the sum of marks obtained in the three
subjects.
10. Write a program to define a structure named employee having empid, name and designation. Use this structure to store
the data in a file named employee.dat. Once all the records are entered display the employee details stored in a file.
11. Write a program to create an integer array of n elements, pass this array as an argument to a function where it is sorted
and displayed.
12. Two matrices of real numbers of size 4 4 is given. Write the functions sum_matrix() and multiply_matrix() for
displaying the addition and multiplication of the given matrices in C language.
13. Create a suitable structure in C language for keeping the records of the employees of an organization about their Code,
Name, Designation, Salary, Department, City of posting. Also write a program in C to enter the records of 200 employees
and display the names of those who earn greater than Rs 50,000. (Make suitable assumptions for data types).
14. The marks of the N students in a given subject (Minimum mark 0 and Maximum mark 100) is awarded. Write a program
in C language to store these marks in an array and calculate the average mark obtained by all the students and then
display the deviation of mark for each student from average.
15. What do you mean by sorting. Write an algorithm to sort the given elements in ascending order.

16. Declare and initialize three dimensional array.


17. Write different between structure and array. Write a program in C to find the largest element of a 3 3 matrix.
18. Define Union. Write a program in C to find the record of student having maximum marks from the list of 10 records.
Each record has roll no, name, class and marks fields.
19. Write a program in C to multiply the two matrices of M N.

20. Write a C program to find the multiplication of two matrices.


21. How to declare an array? Explain about various operations of an array.
22. What is enumerated data type? Write a C program to display months in the year using union.
23. Differentiate structure and union in C. Write a C program to store the students details using union.

81
Unit 5

5.1 An Introduction to Pointers

Consider the following declaration:

int number; // step 1

Here we declare that we will have an integer valued variable named number. On the computer each variable is stored in some
memory location. You can visualize the memory layout of a computer as a consecutive set of cells, each of which has an
address. A cell is typically a byte. Say your computer has 64 KB of memory. What this means is that it has 64 X 1024 = 65536
bytes available. (1 KB is 1024 bytes.) On computer each memory location will have an address. For instance, the first location
could have the address of 0 and the last location could have the address of 65535. Size of an integer variable depends on the
architecture of a computer, but 4 bytes is typical for an integer value. Lets say your computer represents an integer in a 4 -byte
memory location. The declaration above can be visualized as in Figure 1 below.

Address Address + 1 Address + 2 Address + 3

Figure 1. An integer is represented as a consecutive set of 4 bytes.

A pointer is a variable that contains the address of another variable.

With the definition of a pointer on mind, consider the following declaration:

int* pointerToNumber; // step 2

What this declares is a variable that holds the address of an integer variable, in other words, it is a pointer to an integer . To link
the pointer variable to the variable whose address it will hold, the following initialization is necessary:

pointerToNumber = &number; // step 3

The & sign in front of a variable defines the address of that variable. Note that in steps 1, 2, and 3 we defined an integer
variable, a pointer to an integer variable, and assigned the pointer to the address of the integer variable. This is a typical set of
steps. See Figure 2 below for the relation between the two visually.

Now, lets say you want to use the value represented by integer variable number in an arithmetic expression. There is a direct
way by using the variable itself as we are accustomed to- and an indirect way by using the pointer to the variable. Lets say you
want to calculate the divide the number by 10:

Direct way:
k = number / 10;
Indirect way:
k = *pointerToNumber / 10;

The notation *pointerToNumber means the value held in the address pointed by pointerToNumber variable. The notation
*pointerToNumber (star sign in front of a pointer) is also called dereferencing a pointer; it yields the value held in the pointed
address.

82
You might be asking yourself why we need pointers. Being able to have access to the address of any given variable (and later you
will see access to the functions) is very powerful: primarily, this will allow us to change values of function arguments within
functions and handle dynamical memory management. Remember the matrix multiplication example from the previous lecture or
the homework you worked on to calculate the average and standard deviation of a given set of numbers. In these exercises we had
to keep the size of arrays constant. In other words, we had to specify the number of array elements; we could not determine the
number of elements at run-time dynamically. Now that we have introduced pointers, we can dynamically allocate memory for any
number of elements. First, we need to learn the relationship between arrays and pointers.

83
Arrays and Pointers

In C there is a strong relationship between arrays and pointers.


Remember that an array is a consecutive set of elements in memory. For instance,
int a[10];
declares 10 integer elements in memory. Consider an integer pointer p defined as
int* p;

Pointer p can be used to access elements of array a if one initializes p as follows:

p = &a[0];

Note that what we do here is to set p to point to the address of the first element of array a. See Figure 3 below. (An
alternative way to set p to the first element of array a is to just state p=a; in other words, array variables
themselves are pointers in C.)

Now, consider the following:

i = *p;

This is equivalent to

i = a[0];
This is because p points to a[0] and *p refers to the value held in a[0].

Another example:

Say you set p as follows:

p = &a[5];
and
i = *p;

What i is set to now is the 5th element of array a.


Pointer arithmetic

If you use a pointer to access the elements of an array, there is a powerful way of traversing the arrays elements.

Consider
int* p; int a[10];
p = &a[0];

which set pointer p to the first element (indexed by 0) of array a. Now, say you want to refer to element i of array
a. You can do this directly as
a[i];
or indirectly by using the pointer p as
*(p + i);

Note that in the indirect way (p+i) takes you to the address of element i and *(p+i) gives you the value stored in
address (p+i).

Important note: Adding i to a pointer does not mean adding i bytes to the address held by the pointer. If the size
of the variable maintained in the address is k, what this means is to add i * k to the address maintained by the
pointer. For instance, if you are pointing to an integer array and your machine represents integers in 4 bytes, *(p +
3) means the 3rd element of the array and the address is calculated internally as

84
address of element 0 + 3 * 4

In other words, the expression *(p+3) will take you to element 3 by jumping 12 bytes from the beginning address of
the array. We will see more examples of this later when we cover structures.

5.2 Application of Pointer

Pointer is used for different purpose. Some of the pointer application is listed below:
1. Call by Reference
2. Accessing Array element
3. Dynamic Memory allocation
4. Some other pointer application in different data structure, such as tree, such as linked list, tree, graph etc.

5.2.1 Call by Reference (Pointer application)

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("-------Call By Reference---------");
printf("\nEnter the value of a and b");
scanf("%d%d",&a,&b);

printf("\nBefore swapping the values are\n");


printf("a=%d\nb=%d",a,b);

swap(&a,&b);

printf("\nAfter swapping the values are\n");


printf("a=%d\nb=%d",a,b);
getch();
}
swap(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
printf("\nIn function the values are\n");
printf("a=%d\nb=%d",*a,*b);
}

5.2.2 Accessing Array element (Pointer application)

#include<stdio.h>
void sendarr(int [],int n);
void main()
{
int a[5]={4,5,3,2,6};
int i,n=5;

sendarr(a,n);

}
void sendarr(int a[],int n)

85
{
int i;
for(i=0;i<5;i++)
printf("%d\t",*(a+i));
}

5.2.3 Dynamic Memory allocation (Pointer application)


#include<conio.h>
#include<alloc.h>
void main()
{
int *aptr,n,i,m;
clrscr();
printf("how many number you want=") ;
scanf("%d",&n) ;

aptr=(int *) malloc(n*sizeof(int)) ;
if(aptr==NULL)
{
printf("memory not avialable\n");
}

printf("enter the element");


for(i=0;i<=n-1;i++)
{

scanf("%d",(aptr+i));
}

printf("\n Array elements are below\n");


for(i=0;i<=n-1;i++)
{
printf("%3d",*(aptr+i));
}
printf("\n how many more element you wat to store =");
scanf("%d",&m);

aptr=(int *)realloc(aptr,m*sizeof(int));
if(aptr==NULL)
{
printf("memory not avialable\n");
exit(1);
}
printf("printf enter %d more elements\n",m) ;
for(i=n;i<=n+m-1;i++)
scanf("%d",(aptr+i));

printf("\n Elements are below\n\n");


for(i=0;i<=n+m-1;i++)
{
printf("%3d",*(aptr+i));
}
getch();
}

5.3 File Handling

86
In this topic you will come to know, how C programmers can create, open, close text or binary files for their data
storage.
A file represents a sequence of bytes, does not matter if it is a text file or binary file. C programming language
provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices.
This chapter will take you through important calls for the file management.

Opening Files
You can use the fopen( ) function to create a new file or to open an existing file, this call will initialize an object of
the type FILE, which contains all the information necessary to control the stream. Following is the prototype of this
function call:

FILE *fopen( const char * filename, const char * mode );

Here, filename is string literal, which you will use to name your file and access mode can have one of the
following values:

Mode Description

Access
r mode Open an existing file for reading only.
w Open a file for writing only. If the file does not exist create a new one. If the file exists it will
be overwritten.
a Open a file for appending only. If the file does not exist create a new one. New data will be
added to the end of the file.
r+ Open an existing file for reading and writing
w+ Open a new file for reading and writing
a+ Open a file for reading and appending. If the file does not exist create a new one.
If you are going to handle binary files then you will use below mentioned access modes instead of the above
mentioned:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function actually,
flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The
EOF is a constant defined in the header file stdio.h.

There are various functions provide by C standard library to read and write a file character by character or in the
form of a fixed length string. Let us see few of the in the next section.
Writing a File
Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the
written character written on success otherwise EOF if there is an error. You can use the following functions to write
a null-terminated string to a stream:

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

The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on
success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char
*format, ...) function as well to write a string into a file. Try the following example:

Make sure you have /tmp directory available, if its not then before proceeding, you must create this directory on
your machine.
#include <stdio.h>

87
main()
{
FILE *fp;

fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines
using two different functions. Let us read this file in next section.

Reading a File
Following is the simplest function to read a single character from a file:
int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or
in case of any error it returns EOF. The following functions allow you to read a string from a stream:

char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string
into the buffer buf, appending a null character to terminate the string.

If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum
number of characters, then it returns only the characters read up to that point including new line character. You can
also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after
the first space character encounters.

#include <stdio.h>

main()
{
FILE *fp;
char buff[255];

fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("3: %s\n", buff );
fclose(fp);

When the above code is compiled and executed, it reads the file created in previous section and produces the
following result:
1 : This

2: is testing for fprintf...

3: This is testing for fputs...

Let's see a little more detail about what happened here. First fscanf() method read just This because after that it
encountered a space, second call is for fgets() which read the remaining line till it encountered end of line. Finally

88
last call fgets() read second line completely.

Binary I/O Functions


There are following two functions, which can be used for binary input and output:
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Both of these functions should be used to read or write blocks of memories - usually arrays or structures.

C program to write a File


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char fname[20];
int ch;
clrscr();

printf("Enter File name:");


scanf("%s",fname);

fp=fopen(fname,"w");

if(fp==NULL)
{
printf("File can not open\n");
}
else
{
printf("\nEnter text:\n");
while((ch=getchar())!=EOF)
{
fputc(ch,fp);
}
printf("File created Successfully.....\n");
}
fclose(fp);

getch();
}

C program to Read a File

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char fname[20];
int ch;
clrscr();

printf("Enter File name:");


scanf("%s",fname);

fp=fopen(fname,"r");

89
if(fp==NULL)
{
printf("File can not open\n");
}
else
{
while((ch=getc(fp))!=EOF)
{
printf("%c",ch);
}
printf("File Opened Successfully.....\n");
}
fclose(fp);

getch();
}

Questions

90
1. Define double pointer with example.

2. Write short note on Macros with suitable example.

3. Explain the following: Preprocessor, Conditional Operator.

4. Write a program in C to copy content from one file to another file.

5. Write the difference between call by value and call by reference with suitable example.

6. What is pointer arithmetic? Write advantage and disadvantage of using pointer variable.

7. Write short notes on: Macros, Linked List, and Mathematical Function.

8. Dynamic memory allocation.

9. Macros. How they are different from C variables. Advantage of macro. Explain conditional compilation
and how does it help the programmers.

10. Pointers. Declare, initialize. Swap program.

11. File program: Odd number in ODD file and even number in EVEN file.

12. What is dynamic memory allocation? Explain malloc() with example.

13. Write a program in C that takes ten integers from a file and write square of these integers into another file

14. How macros are defined and called in C? Explain with example.

15. What do you understand by pointer arithmetic? Explain.

16. What are pointers in 'C' ? How is a pointer initialized? Explain with a suitable example.

17. Using pointer, write a function that receives a character string and a character as argument and deletes all
occurrences of this character in this string. Function should return the corrected string without space.

18. Write a C-program to display the address and the content of a pointer variable.

19. Discuss different modes in which a file can be opened by giving suitable examples.

20. Differentiate between: int abc [5] [10] and int * b [5];

21. Write a 'C' program using pointer to read in line of text, store it in memory and print the line backward.

22. Write a 'C' program to search and replace in a string using pointer and functions provided by the 'C'
library.

91

You might also like