0% found this document useful (0 votes)
46 views133 pages

Computer Concepts and C Programming UNIT-1 Chapter-1:: System Unit (CPU) Screen

Uploaded by

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

Computer Concepts and C Programming UNIT-1 Chapter-1:: System Unit (CPU) Screen

Uploaded by

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

COMPUTER CONCEPTS AND C PROGRAMMING

UNIT-1

CHAPTER-1: Computer Fundamentals

Computer: - A Computer can be defined as an electronic device, which can process large
volumes of data using pre-defined instructions set by a human being.

Monitor
System Unit
(CPU)
Screen

Speaker

Keyboard
Mouse

Data: -Data is a collection of facts, figures, statistics that can be processed to produce
meaningful information.

Information: - Information is nothing but the processed data.

Human beings supply data to the computer, which are required to be processed. Not only that,
one has to supply the instructions required to process the data. The computer remembers both
the data and instructions, does the processing when asked to and gives us the result in the
specified form.

Advantages of a computer

 Very high speed: -Allthe operations in a computer are caused by electrical pulses.
We all know that electricity travels at the speed of light, computers too can perform
innumerable operations in just 1 sec. The processing speed of a computer is generally
measured in nanoseconds.
 Largestorage and retrieval capacity:- Computers have very large storage capacity.
The contents of around two hundred sheets of A4 size paper can be stored on a small
floppy disk, which is not even half the size of one sheet of paper.
 Accuracy in calculation: - Computers have many check circuits built in and so
normally they do not make mistakes. Errors in computing are generally due to human
negligence rather than technological faults.
 Diligence: - Computers, being machines, do not suffer from fatigue and lack of
concentration. If five million calculations have to be performed, a computer can
perform the five millionth calculations with same accuracy and speed as it performed
the first calculation.
 Versatility in application: - Computers can perform a wide range of jobs with speed,
accuracy and diligence.

Disadvantages of Computer

 Cannot think
 Cannot learn by experience
 Cannot take independent decisions, requires human instruction to take a decision.

History of Computers

The evolution of computer has passed through different stages before it reached the present
state of development. The evolution probably started from the 3500 BC when human being
first started to learn to calculate with a calculating machine named Abacus. Thus, the
evolution of counting system from Abacus to modern Microcomputer is the result of
continuous human effort in search of a more versatile and efficient machine.

Abacus: - Abacus seems to be the earliest calculating machine, which was developed by the
Chinese. Abacus consists of beads, which can move, in wires. The wires represented the
column. The right most columns represented the unit, the next for ten and so on. Numbers
were represented by moving the beads at appropriate column. Abacus could perform simple
addition and subtraction.

Pascal’s Mechanical Calculator: - Blaise Pascal, the French mathematician, laid the
foundation of automatic computing. Blaise Pascal used his adding machine (1662)simply for
addition and subtraction. The machine consisted of gears, wheels and dials. With this
calculation could be performed by dialling these series of wheels carrying the number 0 to 9
around their circumference. The wheel was arranged in such a manner that each wheel had 10
segments and when a wheel completed one rotation the next wheel would move by one
segment. This machine was later improved by Gottfried (Germany) to perform multiplication
and division.

Charles Babbage’s Differential Engine: - Charles Babbage, a professor of mathematics at


Cambridge University, invented a machine called Differential Engine- which could evaluate
accurately algebraic expression and mathematical tables- correct up to 20 decimal places.
Later, he developed analytical machine, which could perform addition at the rate of 60 per
minute.

For technical limitations of that age, Charles Babbage could not see his invention operational.
However, and surprisingly enough, today‟s computer has building blocks, similar to what
was proposed by him. For this reason, Charles Babbage is remembered as the father of
computing. With him, his disciple and co-worker, Lady Lovelace is remembered with
reverence as the first programmer of the world.

Mark I: - In 1934, Harvard professor H. Eiken developed an automatic calculating machine,


which was called Mark-I digital computer. Its internal operation was automatically
controlled.

The basic drawbacks of the mechanical and electromechanical computers were:

 The speed was limited due to the friction/inertia generated by the movement of
components.
 The data movement was quite difficult and unreliable.

The designers were looking for better switching devices, storing of the mechanism and
reducing moving mechanical parts. With the advent of triode vacuum tubes, a better
switching device of earlier years, designers shifted to designing electronic computer.

Electronic Numeric Integrator and Calculator (ENIAC): - While Mark-I was the first
electromechanical computer, the first electronic general purpose computer was built in 1946
by a team of professors at Moore school of university of Pennsylvania and was called
ENIAC. The ENIAC ushered in era of what is known as first generation computer. It was a
bulky machine consisting of 18,000 vacuum tubes, 70,000 resistors, 10,000 capacitors,
60,000 switches and a large size occupying 1500 Sq. Feet of space. It was a very fast machine
as compared to its ancestors and could perform 5000 additions or 350 simple multiplications
in just one second.

The main features of ENIAC can be summarized as: -

 ENIAC was a general purpose computing machine where vacuum tube technique was
used.
 ENIAC was based on decimal arithmetic.

Universal Automatic Computer(UNIVAC): -In the year 1946, Eckert and Mauchly
founded their own company and began to work on the University Automatic Computer, or
UNIVAC. In 1949, Remington Rand acquired the Eckert-Mauchly Computer Corporation,
and in early 1951 the first UNIVAC-1 became operational at the Census Bureau. It was
followed by EDVAC (Electronic Discrete Variable Automatic Computer) which had a
storage capacity of 1024 words or 44 bits each.

Computer Generations

The word “Generation” – for computers, indicates a step in technology. Every step includes a
major change in the components used for constructing a computer. Originally, the term
„generation‟ was used to distinguish between varying hardware technologies(in some cases
software also).

First generation(1942-1955): - The computers produced between 1942-1955 are called the
first generation computers. They were extremely large with low reliability. They used
vacuum tubesin their circuitry which were fairly large and generated considerable heat
needed lot of space to install and required special air conditioning system. Storage technique
and the use of punched cards for input output were primitive.

Disadvantages

 Too bulky in size.


 Unreliable for excessive heat generation.
 Air conditioning requirement was too much due to heat generation.
 Non-portable.

Second generation (1955-1964): -The second Generation computers used a more advanced
technology by replacing the vacuum tubes with transistors. A transistors is a two state device
made from silicon. These components were smaller in size, easier to manufacture, less power
consuming, cheaper and more durable. The processing capacity and the speed of operation of
the components built from transistor were considerably increased.

Advantages

 Smaller in size as compared to first generation computers


 More reliable
 Less heat generated
 Faster computational speed

Disadvantages

 Air conditioning required.


 Frequent maintenance required.
 Commercial production was difficult and costly.

Third Generation (1964-1975): - The third generation computers employed integrated


circuits in which all the elements of an electronic circuit were contained in a tiny silicon
wafer. The Integrated Circuits (IC) based on the small, medium and Large-Scale Integration
(LSI) technology replaced the individual transistors in the third generation computers. Each
Large-Scale Integrated circuit had hundred or more components packed into an assembly.

Advantages

 Smaller in size as compared to previous generation computers


 Even more reliable than second generation
 Lower heat generated than second generation
 Reduce computational times
 Low maintenance cost
 Comparatively portable
 Less power consumption
 Commercial production easier and cheaper

Fourth generation (1975-1984): -Fourth generation machines appeared in the 1970‟s,


utilizing still newer electronic technology, which enabled them to be even smaller and faster
than those of 3rd generation. The fourth generation computers used VLSI (Very Large Scale
Integration) technology. The VLSI devices have thousands of more components packed into
an assembly.

Advantages

 Low cost machine


 High speed
 Large memory
 Small size
 Less power consumption
 Floppy disk is used as storage device
 Hardware failure is negligible
 Heat generated is negligible
 Cheapest among all generations

Fifth Generation (1984-1990): -Scientists are now at work with the fifth generation of
computers. The world is moving towards the development of what one can call „Super Scale
Integration‟ – which in turn will compliment and improve speed, miniaturization and cost
reduction. Development of artificial intelligence to make computer function and take
decisions almost like human being, implementation of expert systems, robots, intelligent
programs, speech synthesizers as well as the use of video disks and tapes for external storage
media, are included in the fifth generation of computer innovation.

year Generation Number Type of Technology


1940 1 Valves (Vacuum Tubes)
1950 2 Transistor
1960 3 IC (Integrated Circuit) with LSI (Large Scale
Integration)
1970 4 Microprocessor with VLSI (Very Large Scale
Integration)
Late 1980‟s 5 Hardware and Software technology AI (Artificial
Intelligence)

Hardware: - Hardware refers to the physical components of a computer.


Software: - Software consists of sequence of instructions, in the form of a program to
perform a particular task on a computer.

Classification of Computers

A computer can be classified in the following methods:

 Computational method
1. Digital: - A digital computer can count and accept numbers and letters
through various input devices. The input devices convert the data into
electronic pulses and perform arithmetical operations on numbers in discrete
form. In addition to performing arithmetical operations, they are also capable
of:
 Storing data for processing
 Performing logical operations
 Editing or deleting the input data
2. Analog: - Analog computer process data input in a continuous form. Data
such as voltage, resistance or temperature are represented in the computer as a
continuous, unbroken flow of information, as in engineering and scientific
applications, where quantities to be processed exit as waveforms or
continually rising and falling voltages, pressure and so on.
3. Hybrid: - Computer can also be built using some parts employing digital
computations and some parts based on analog principles. Such computers are
called hybrid computer.
 Size and capability
1. Super: - These are the largest and fastest computers available but are
typically not used for commercial data processing. Instead they are used in
specialized areas such as in defense, aircraft design, computer generated
movies, weather research etc. The first super computer was the ILLIAC IV
made by Bur roughs. Other suppliers of supercomputer are CRAY, CDC,
FUJITSU, NEC etc. A supercomputer CRAY-1 is considered the most
powerful computer today. Supercomputers can process 64 bits or more at a
time. Their processing speed ranges from 10.000 million instructions per
sec(MIPS) to 1.2 billion instructions per sec. They can support 10.000
terminals at a time. They have huge numbers of storage and other devices
connected to them.
2. Mainframe: - Mainframes are less powerful and cheaper than super
computers. However, they are big general purpose computers capable of
handling all kinds of scientific and business applications. Mainframes can
process several million instructions per second. More than 1,000 remote
terminals can be supported by a mainframe. Mainframes have large on-line
secondary storage capacity.
3. Mini: - This type of computer performs data processing activities in the same
way as the mainframe but on a smaller scale. The cost of minis is lower. As
the name, a minicomputer is small compared with a mainframe and may be
called a scaled down mainframe as the processor and the numbers of
peripherals are physically smaller. A mini computer can typically support 10
to 12 terminals. The most popular minicomputers or minis are Nova, Dec,
PDP_II and IBM series.
4. Micro: - This is the smallest category of computers, consisting of a
microprocessor and associated storage and input/output devices. These are
also called personal computer systems. Microcomputers were first available
for widespread use in the 1970‟s, when it becomes possible to put the entire
circuitry of computers(CPU) into a small silicon chip.

Functional Units of a Computer (Block Diagram)

Memory Unit

Input Unit Control Unit Output Unit

Arithmetic Logic
Unit
Components of a Computer

Classify the hardware components into the following two types.

1. Central Processing Unit (CPU)


2. Peripheral Devices (Connected to and controlled by the CPU)

Central Processing Unit (CPU): -A CPU controls the execution of programs and performs
the calculations. The CPU is also called as the brain of the computer. This is because
execution of any task by a computer is controlled entirely by the CPU. The CPU activities
include ensuring- all instructions for a program are executed and in the proper sequence, the
calculations and logical operations are performed correctly and the instructions and data are
available for successfully executing a task.

For executing its job the CPU mainly uses two main interactive components.

 Arithmetic and Logic Unit (ALU)


 Control Unit (CU)

Arithmetic and Logic Unit: -Arithmetic and logic unit (ALU) does the operations on the
data stored in the memory. This part of the CPU contains a large number of electronic circuits
used to carry out arithmetical and logical computations. These computations are carried out
with the help of special purpose storage locations, called the registers.

There are basically three types of registers in an ALU:

1. Storage registers,
2. Accumulator,
3. Arithmetic and logic operation unit.

Storage registers: - Temporarily holds data during execution of programs. These are
helpful in getting work done by a computer. For example, suppose data stored in two
locations are needed to be interchanged. Then a third entity is required to hold the data
temporarily. If the two locations are named x and y, then one can temporarily fetch x and
keep the data in z. Then y may be fetched and transferred to x. In the third step, z may be
copied to y. This third entity z may be a third location or a storage register. In a typical
computer, storage register operations are faster than memory operation. That is the reason
why storage registers become handy.

. Page 9
Accumulator: - Holds the result of the calculations until needed later on. Operations are
mostly carried out in two operands like we say, add x to y. Here x and y are operands. If
in a computer instruction, always two operands are provided, then there will be a
requirement of more number bits to express two operands. Computers are normally
provided with a register called accumulator, so that in all operands this accumulator is
assumed by the ALU as the default location for one of the operands. For example, add x
and y may be specified as load accumulator with x, and y. The accumulator holds x and
the adding of y and x takes place in accumulator. The result is also held in accumulator.

Arithmetic and logic operation unit: - Receives the data from two or more sources,
performs the arithmetic or logic operation unit and transfers the result to the accumulator.

The adder is an important component in ALU. In any case, a computer performs all
operations (subtraction, multiplication and division) through additions. Subtraction is
done by a complimentary addition (a-b = a+ (-b)), multiplication may be done by repeated
addition and in some cases division may also be done by repeated subtraction.

Control Unit: -The control unit contains that portion of the CPU, which controls each
operation while a program is being executed. You must have noticed that many times you
keep a book open with your eyes fixed on it, but you do not read a single word. This is
because the control unit of your brain was not allowing your eyes to give any input at that
time. Possibly the control unit of your brain was processing something else.

Control unit synchronizes and sequences operations of the CPU for ensuring correct
execution of programs (sequence of instructions to the computer to perform various tasks). In
other words, this unit acts as the central nervous system for various components of the
computer, without as such performing the actual processing.

Control unit has a special register called the program counter, which contains the address of
the next instruction to be fetched from the primary memory. In order to sequence the
instructions, the control unit goes through the following sequence of steps:

 Retrieve the instruction from the processor memory addressed by the program
counter
 Increment program counter
 Determine what action is being requested by the instruction

. Page 10
 Retrieve the appropriate data from the processor memory
 Direct the CPU components to perform the operation indicated by the instruction
 Determine if the operation was carried out properly
 If not, flag the error message to the user, through the output device
 Else, store the result in the CPU memory, for further processing
 Determine the location of the next instruction to be retrieved

Peripheral Devices: - Peripherals are the devices that permit a computer system to
communicate with outside world. The peripheral devices allow the computer to receive data
and instructions from the outside world and give the information to the outside world. These
peripheral devices consist of:

1. The input devices (accept input data)


2. The external storage devices (stores data)
3. The output devices (displays data)

Input Devices: - The input devices are used to input data and instruction. Data and
instructions must be entered into the memory of the computer to perform computation. This
task is carried out by the input devices.

Example: keyboard, Mouse, Joystick and tracker ball, scanner

Output Devices: - The job of an output device is to bring out the result of computation to the
outside world. As you already know, the result in computer memory is in binary form. So the
binary values are converted to human acceptable forms, with the help of interface electronics
and the output device.

The following functions may be attributed to the output device:

1. It accepts data in binary form from the computer, which are normally not
understandable by human beings.
2. Converts the coded data to human acceptable form.
3. Outputs the converted result to the outside world.

Example: video display unit, printer, plotter

External Storage Devices: -These are several devices used as secondary memory for
computers and they can store and retrieve data in machine-readable forms. These are useful

. Page 11
for storing results temporarily, or for transporting data to other computers, or for storing data
for a long period of time. The commonly used secondary devices are floppy diskette,
magnetic disk, Hard drive, CD-ROM, DVD ROM, Flash drive etc.

Primary Storage Section / Main Memory: - Memory is the storage place where data and
instructions can be stored into, and retrieved from, whenever required by other functional
blocks of a computer.

Primary storage section, also called as main memory, is that portion of the computer where
data and instructions get stored when a program is being executed.

The main memory is used to:

 Hold data received from input devices and keep them ready for processing
 Hold data being processed and the intermediate results being generated therein
 Hold the finished results of processing until released to the output devices
 Hold the system software and application software in use

Units of Storage: - A computer memory is provided with locations where the data can be
stored each memory location is identified by a unique address. The locations store the data in
the form of bits [BIT- Binary Digit (0‟s and 1‟s)].

8 bits = 1byte
1024 bytes (210) = 1KB (Kilo byte)
1024 KB(220) = 1MB (Mega byte)
1024 MB (230) = 1GB (Giga byte)
1024 GB (240) = 1TB (Tera byte)
Memory is broadly classified in two types:
1. Random Access Memory (RAM)
2. Read Only Memory (ROM)
Random Access Memory(RAM)
The memory where both reading and writing can take place is called Random Access
Memory (RAM). RAM may be of two types, these are: -
Static RAM: - Static RAM elements, once set to their values, do not loose them if the power
supply does not go off. Once some value is stored, it will remain in the main memory till the
power is on. These elements are costly and have a fast access.

. Page 12
Dynamic RAM: - In Dynamic RAM the memory elements have less retention period and
loose its value unless it is refreshed. Refreshing is a process where the RAM is read and
rewritten. This kind of RAM requires extra circuits for refreshing. These are relatively slow
but less costly compared to static RAMs. This kind of memory is therefore used in mass
scale.
Both of these are volatile i.e., the moment power goes off all contents of RAM are lost.
Read Only Memory (ROM)
There are portions in the computer memory where no writing is allowed. The contents are
pre-written and can only be read. Such memories are called Read Only Memory (ROM). It is
used for micro programs not available to normal programmers. The term read only means
that the storage cannot be altered by regular program instructions.
ROM can be classified into 2 types:
Programmable ROM: -PROM are those in which the user can insert the contents of choice
only once. Once the PROM is written, it can only be read and never be rewritten.
Erasable Programmable ROM: - EPROM is another kind. As the name suggests, it can be
written many times by a special process. These are very useful for design and development.
Speed of Memory: - The fastness of main memory is expressed by memory access time. It is
the time taken by the memory to read from or write in a single location of the memory. Speed
is expressed in nano or micro seconds.
Other Memory Elements: - Other than the main memory, there are different memory
elements used in different parts of the computer. They are:
 Cache
 Register
Cache: -Cache is a very fast memory placed in between the main memory and the CPU.
We know that each instruction is to be fetched by CPU from main memory. Main
memory is comparatively slower than cache, so it holds cache whenever CPU refers to
memory. Cache memory acts as a buffer and fetches chunk of contents from main
memory to be used by CPU. Cache memory is very fast and very expensive, so amount of
cache memory in any system is usually much smaller than the main memory.
Register: - Registers are temporary storage places and hold data, addresses etc., for doing
operations on them for data transfer. Most of the registers are built inside the CPU.
However, other blocks also use registers for their operations. There are many registers
spread through the computer. Some of the most important registers in CPU are Program

. Page 13
Counter (PC) for storing the address of the current instruction being executed,
accumulator (AC) for storing one of the operands being used and also for storing the
result of the operation.
Evolutional of Computer Languages
Language is a means of communication between two people. We can communicate with the
computer using a language called programming language.
All computer languages can be classified into following categories:
1. Low level languages
a. Machine level language
b. Assembly level language
2. High level languages
a. Specific purpose languages
b. General purpose languages
Machine languages: - Or machine code or „absolute language‟. It is considered as first
generation language.
 Instructions are written using binary 1‟s and 0‟s (ON and OFF)
 Computer can directly understand the instructions
 It is difficult for the user to read, write, modify, and understand such instructions.
An instruction in the machine language has two parts
1. OPCODE (operation code)
2. OPERAND (address/ location)
Operation code denotes the operation such as add, multiply, delete etc. More number
of operations the more powerful is the computer. The power of computer is
determined by the number of operations. The operand code gives the specific location
or address of the data.
For example a typical program in machine language to add two numbers may look
like
0000011100000001111001111` Load the data
1110000001111100000011100 Add the contents
0011111011000000001100000 Store the result
0000000001110000011000110 Print the result
0000000000000000000000000 Stop

. Page 14
Advantages of machine language:
 Machine language makes efficient use of storage.
 Instructions are directly understood by the computer and immediately executed. There
is no need for translators.
 Instructions can be used to manipulate the individual bits in a byte of computer
storage.
Disadvantages of machine language:
 They are machine dependent. (program written on one machine cannot be run on
another as the op-code is different for different computers)
 It is difficult to remember the operation codes for all operations and difficult to
remember the address of data and instructions.
 It is difficult to check for errors, correct or modify the written program.
Assembly language:Or Symbolic language Or the second generation languages.
 Instructions are written using mnemonics/symbols/codes.
 Computer cannot understand these instructions; a translator called „Assembler’isused.
Assembler is system software. It translates the assembly code to machine code and
also assembles the machine code into, main memory of the computer execution.
A typical program in assembly language to add two numbers may look like.
STA A Load the data to accumulator
ADD B Add contents of B to accumulator
STR C Store the results in location c
PRT C Print the results
HLT Stop

Advantages of Assembly language


 It is not required to remember the op-codes and operand addresses.
 Easier to read, write, understand, modify and debug the instructions.
 Programs can be written with fewer instructions.
Disadvantages of assembly language:
 Programs are machine dependent.
 Computer needs „assembler‟ for translation.

. Page 15
High level languages:
 Instructions are written using English words and mathematical symbols.
 Computer can understand high level language instructions using the translator-
compiler/interpreter.
A program in high level language to add two numbers may look like
INPUT A, B
C=A+B
OUTPUT C
END
Advantages of high level language:
 Machine independent : A high level language program written on one machine can be
run on any machine without any modifications in the program
 Easy to learn and use: Programs are written using familiar English words and
mathematical symbols. It is easy to read, write, understand, modify and correct errors
in programs.
 Better documentation: Documentation is writing explanation about the program in the
form of comments and remarks. High level languages are self documenting.
 Writing a program in high level language does not require the knowledge of the
internal structure of the computer or any machine instructions. The programmer need
not learn anything about the computer he is using. No need of thinking about how to
store data, where to store them and what to do with them.
Disadvantages of high level languages:
 Lack of flexibility: An assembly language provides access to all the special features
of the machine. Certain machine level operations can be easily performed in assembly
language which is impossible in high level language. Automatic features of the high
level languages are not under the control of the programmer, they are less flexible
than assembly languages.
 Slower execution / lower efficiency: Execution is slow due to generality of the
statements. Programs in high level languages take more time to run and require more
main storage.
 Requires a translator or compiler: High level language instructions can be understood
by the computer using the translator like compiler or interpreter. These translators
occupy space in memory.

. Page 16
Classification of Higher level languages:
 General purpose languages: These are used in teaching, training business, art,
science etc.
Example: BASIC (Beginners All Purpose Symbolic Instruction Code)
Pascal (Named after French mathematician Blaise Pascal)
C (Next version of BCPL-Basic compiled Programming Language)
 Specific purpose languages: These are used only in particular applications
Example: COBOL (Common Business Oriented Language)- used in business
FORTRAN (FORmula TRANslation) – used in scientific applications
C++ (New version of c)- used in Object Oriented Programming
JAVA- Used in Internet Programming.

Compiler: -A Compiler converts human readable instructions into computer readable


instructions one time. It takes longer as it rearranges or optimizes the object code.

Interpreter: -An interpreter converts human instructions into machine instructions each time
the program is run. An interpreter starts interpreting each instruction immediately and
produces result more quickly but is slower overall.

Compiler V/S Interpreter

Compiler takes entire program as input Interpreter takes single instruction as


input
Intermediate object code is generated No intermediate object code generated
Conditional control statements are Conditional control statements are
executes faster executes slower
Memory requirement more Memory requirement less
Program need not be compiled every time Every time higher level program is
converted into lower level program
Errors are displayed after entire program Errors are displayed for every instruction
is checked. interpreted (if)
Ex: c compiler Eg: BASIC

. Page 17
Unit 2:
INTRODUCTION TO C LANGUAGE
C is a programming language developed at AT & T‟s Bell laboratories of USA in 1972. It
was developed by Dennis Ritchie.
Characteristics of C:
 C is a general purpose programming language.
 It is a structured programming language (It allows modularization process of dividing
problems into sub-problems and C has structured statements like sequence, selection
and iteration)
 C is a middle level language (C is a high level language but also incorporates features
of low-level languages like manipulation of bits, bytes, words and addresses.)
 Helps in development of system software ( C is used for writing application programs
and since it has low level languages features it can be used in development of system
software)
 Has rich set of operators and data types and built-in functions.
 Provides compact representation for expressions. This makes the language simple,
orderly and easy to learn.
 No rigid format. Any number of statements can be typed in a single line.
 Portability: any C program can be run on different machines with little or no
modifications.
 Less number of reserved words
 Pointer arithmetic and pointer manipulation
 Ability to extend itself by adding functions to its library.
History of C:
year Language Developed by Remarks
1960 ALGOL International committee Too general, to abstract
1963 CPL Cambridge Difficult to learn and implement
University(CU)
1967 BCPL Martin Richards at CU Could deal with only specific problems
1970 B Ken Thomson at AT & T Could deal with only specific problems
1972 C Dennis Ritchie at Restored the lost generality of BCPL
AT & T and B

. Page 18
Applications of C:Because of its portability and efficiency, C is used to develop the
system as well as application software. Some important system programs include operating
systems, compilers, interpreters, assemblers, editors, linkers and loaders.
Being a structured language, it is useful in developing application programs like database
systems, word processors, spreadsheets, graphics packages, CAD/CAM applications, office
automation tools, scientific and engineering applications, animation and games.

Basic structure of a C program or Syntax:


Every C program includes the following components
 Pre-processor directives
 Main()
 A pair of flower brackets { }
 Declaration and statements
 User created sub-programs or functions.

Pre-processor directives

Global declarations;

Main ()

Declarations;

Statements;

User created sub-programs or functions

Pre-processor directives: these statements begin with # symbol. They direct the C pre-
processor to include header files and symbolic constants into a C program.

E.g.: #include<stdio.h> : For the standard input, output function

#include<conio.h> : For the Console input, output function

# define NULL 0 : For defining symbolic constant, NULL=0

. Page 19
Global declarations:Variables or functions whose existence is known in the main () function
and other user defined functions, are called the global variables or functions. Their
declarations should be made before main ().

Main(): This is the main function of every C program. Execution of a C program starts with
Main (). No C program is executed without the main () function. It should be written in
lowercase letters and should not be terminated with semicolon. It calls other library functions
and user defined functions. There must be one and only one main () function in any C
program.

A pair of flower brackets: The flower brackets indicate body of the program, which
includes instructions to perform the required task. { indicates beginning of the main ()
function and } indicates end of the main() function.

Declarations:It is the part where all the variables, arrays, functions etc., used in the C
program are declared and may be initialized with their basic data types.

Statements:Theseare instructions to perform certain operations like input, output,


assignment, arithmetic statements, control statements and other statements. They also include
comments. Comments are explanatory notes on some instructions. The statements to be
commented must be enclosed within /* and */. The comment lines are not compiled and
executed.

User created sub-programs or functions:These are sub-programs created by the user to


perform certain common functions. They may be written before or after main ().

Example:

/* C program to display hello world */

#include<stdio.h>

#include<conio.h>

void main()

printf(“\n HELLO WORLD”);

getch();

Output:

HELLO WORLD

Page 20
C PROGRAMMING PRELIMINARIES

CHARACTER SET:

Alphabets Uppercase letters A to Z

Lowercase letters a to z

Digits 0 to 9

Special Characters blank , ; : “ + - * / { } ? ! # _= | ^ ~ <> \ () []@...etc.

IDENTIFIERS:These are names given to program elements like variables, arrays, functions
and structures. Basically identifiers are the sequence of alphabets and digits.

Rules for forming identifier names:

1. The first character must be an alphabet (upper or lowercase) or an underscore.


2. All succeeding characters must be either letters or digits but no other special
character or punctuation symbols allowed.
3. Uppercase and lowercase identifiers are different in C. (E.g.: SUM, sum and
sum are different identifiers.)
4. No two successive underscores are allowed.
5. Keywords should not be used as identifiers.
6. Identifiers should be single words. That is, blank spaces cannot be included in
identifiers.
E.g.: valid identifiers: - sum, emp_name, stu_address, number, age

Invalid identifiers: - father‟s-name, while, @total, do-it, 3by2.

VARIABLES:

An identifier/ quantity that change its value during program execution are called
„variable‟. A variable is an object or element that may take on any value of a specified type.
Variables represent named storage locations, whose value can be manipulated during
program execution.

E.g.:- sum, area, m1, length, sname, age, city etc.

Rules for naming a variable – same as rules for forming an identifier name

Valid variables Invalid variables


Marks 8ab
TOTAL_MARK TOTAL-MARK
Gross_salary_2004 Gross-salary-2004
Area_of_circle Area-of-circle
Num[20] Num(20)

. Page 21
CONSTANTS: It refers to fixed values that do not change during the execution of the
program. C supports several types of constants.

1. Numeric Constants
a. Integer constant
b. Float (real) constant
2. Character constants
a. Single character constants
b. String constants
3. Symbolic constants
4. Backslash constants
1. Numeric Constants
a. Integer constants: All whole numbers are integer constants. They are
sequence of digits without decimal point
E.g.: Decimal constants : 134,9000,3567,-987
Octal constant : 06, 034,0677,-07867
Hexadecimal constant : 0x20, 0xA, 0x1AB
b. Float (Real) constant: Numbershavingdecimal point are floating point
constants. They can contain both an integer part and a fractional part in the
number. They are stored differently from integers. They may be represented
either in decimal form or in the exponent form.
E.g.: Valid decimal constants: - 18.5, .18, 5. , -25.67
Valid exponent constants: - 5.3E-5, -6.79E3, 34e-8
Here the number before „E‟ / „e‟ is called mantissa and
mantissa can be either real or integer, the number after „E‟/‟e‟ is called
exponent and exponent should be an integer.
2. Character constants
a. Single character: It isa letter or any symbol enclosed in single quotes.
Character constants can be used in assignment statements or in symbolic
constant definitions.
E.g.: ch=‟h‟ ;
#define PERIOD „.‟
b. String constant: A sequence of characters enclosed between double
quotes is called string constant.
E.g.: “C programming is fun”
“Enter two numbers”
3. Symbolic constants
It is a name that substitutes a numeric, character or a string constant.
E.g.:#define PI 3.1415 (Here we substitute PI for numeric constant)
#define PLACE “MYSORE”
#define FOUND 1
#define NUM 023 /* indicates octal number */
#define VALUE 0x20 /*0x indicates hexadecimal */

Page 22
4. Backslash constant
They are also called „escape sequences‟ and are used in the output statements. A
backslash constant is a combination of two characters in which the first character is
always the backslash (\) and the second character can be any one of a, b, f, n, r, t, v.
Backslash constant Meaning
„\a‟ System alarm
„\b‟ Back space
„\f‟ Form feed
„\n‟ New line
„\r‟ Carriage return
„\t‟ Horizontal tab
„\v‟ Vertical tab
„\”‟ Double quote
„\‟‟ Single quote
„\0‟ Null character
„\\‟ Back slash character

KEYWORDS(Reserved words): These are predefined words that have special meaning and
these meanings cannot be changed. They can be used only for the purpose for which they
have been defined. All keywords must be written in lowercase letters.

Example:

auto double int struct

break else long static

case enum register switch

char extern return typedef

const float short union

continue for signed unsigned

default goto sizeof void

do if while volatile

DATA TYPES:

Data type indicates the type of data a variable can have. Data type defines set of
values, which can be stored in the variable along with certain operations that may be
performed on those values.

. Page 23
There are three classes of data types

 Primary (or fundamental) data types:- int, float, char, double


 Derived data types:- arrays, functions, structures, pointers
 User-defined data types:- typedef, enum

Primary Data types:

int: Means that the variable is an integer. An integer needs two bytes of space. Range of
values that can be stored in two bytes is -32768 to +32767. The operations that can be
performed on an integer value are addition, subtraction, multiplication, division and
remainder.

char: Means that the variable is a character. A character needs one byte of storage space. If
unsigned, the range of values is 0 to 255. The possible operations are input and output.

float: Means that the variable is a real number. Four bytes or 32 bits are allocated in memory,
this includes 7 significant digits after the decimal point. The range of values is 3.4E-38 to
3.4E+38.

double: Means that that variable is a double precision float type. Eight bytes or 64 bits of
storage space and range of values is 1.7E-308 to 1.7E+308.

Void: the void type has no values. This is usually used to specify the type of functions. The
type of a function is said to be void when it does not return any value to the calling function.

Size and Range of data types

Type Size (bits) Range


Char or signed char 8 (1 byte) -128 to 127
Unsigned char 8 (1 byte) 0 to 255
int or signed int 16 (2 bytes) -32,768 to 32,767
Unsigned int 16 (2 bytes) 0 to 65535
Short int or signed short int 8 (1 byte) -128 to 127
Unsigned short int 8 (1 byte) 0 to 255
Long int or signed long int 32 (4 bytes) -2,147,483,648
to2,147,483,647
Unsigned long int 32 (4 bytes) 0 to 4,294,967,295
float 32 (4 bytes) 3.4E-38 to 3.4E+38
double 64 (8 bytes) 1.7E-308 to 1.7E+308
Long double 80 (10 bytes) 3.4E-4932 to 1.1E+4932

Declaration (definition) of variables:


Syntax: data_type variable list;
Variables must be separated by comma and declaration statement must end with a semicolon.
Example: int a, b, c; float sum, average;

. Page 24
Assigning values to variables:
Method 1: values can be assigned to variables at the time of declaration
E.g.: int sum=0;
float val=3.14159;
char ans=‟y‟;
Method 2: values can be assigned using an assignment statement
E.g.: sum=0;
Val=3.14159;
Ans=‟y‟;
Example: C program to compute area and circumference of circle
#include<stdio.h>
#include<conio.h>
#define PI 3.1415
void main()
{
int r;
float a, c;
clrscr();
printf(“enter the radius of the circle\n”);
scanf(“%d”,&r);
a=PI*r*r;
c=2*PI*r;
printf(“area of the circle=%f\n”,a);
printf(“circumference=%f\n”,c);
getch();
}
Output:

Page 25
User-defined type declaration

 Type definition: -Thatallows users to define an identifier that would represent an


existing data type.
Syntax: typedef type identifier;
Example:
#include<stdio.h>
#include<conio.h>
typedef int units;
units b1=10,b2=30;
void main()
{
clrscr();
printf("\nthe definition of unit b1=%d",b1);
printf("\nthe definition of unit b2=%d",b2);
getch();
}

Output:

 Enumeration:-The enum keyword is used to declare an enumeration, a distinct type.


Consisting of a set of named constants called enumerator list.
Syntax: enum identifier {value1,value2,. .................... valuen};
Example:
#include<stdio.h>
#include<conio.h>
enum days {mon=1,tue,wed,thu,fri,sat,sun};
enum days week_st,week_end;
void main()
{
clrscr();
week_st=mon;
week_end=fri;
printf("\n%d",week_st);
printf("\n%d",wed);
printf("\n%d",week_end);
getch();
}
Output:

Page 26
STORAGE CLASS

This class of variables provides information about the scope of the variable and how
long a variable retains its value.

Four Storage class specifiers

1. auto: -Local variable known only to the function in which it is declared.


Note:
 default is auto
 The variable is limited to only the function in which it has been defined.
 Declared inside the function.
 They are created when the function is called and destroyed automatically
when the function is exited.
 Undefined variable values it will take garbage value

Example:
#include<stdio.h>
void main()
{
auto int count=10;
clrscr();
printf("%d\n",count);
getch();
}

Output:

2. Static:- Local variable which exists and retains its value even after the control is
transferred to the calling function.
Note:
 Declared within a function
 Static variable is initialized only once
 Same as that of automatic variables.
 All static variables are automatically initialized to zero‟s
 Only constants should be used to initialize

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
static int sn;

Page 27
clrscr();
sn=sn+23;
printf("%d",sn);
getch();
}

Output:

3. Extern: - Global variable known to all functions in the file.


Note:
 Declared outside the function
 This is both alive and active throughout the entire program.
 Automatically initialized to zero.
Example:
#include<stdio.h>
extern int first=10,last=20;
int main()
{
clrscr();
printf("%d\n%d",first,last);
getch();
return 0;
}
Output:

4. Register: - Local variable which is stored in the register.


Note:
 Faster than a memory access.
 Faster execution of programs
 Undefined variable values it will take garbage value

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
register char ch='A';
clrscr();
printf("%c Stored in register",ch);

Page 28
getch();
}
Output:

INPUT-OUTPUT STATEMENTS

C is a functional programming language. To perform input-output operations C


provides a library of functions. This library is called a standard input-output library. It is
denoted by stdio. The header file containing such library functions is called stdio.h
Some of the standard I-O functions in C are

et 1. scanf() 5. gets()
2. printf() 6. puts()
3. getchar() 7. getch()
4. putchar() 8. getche()

There are two types of input-output statements

1. Formatted I/O statements


2. Unformatted I/O statements

Input statements Output statements


Formatted scanf() printf()
Unformatted getchar() getche() getch() putchar() puts()
gets()

FORMATTED I/O STATEMENTS:

They allow the input read from the keyboard or the output displayed on VDU to be
formatted as per our requirements i.e., where this output will appear on screen, how many
spaces between two values, number of decimal places etc. Can be controlled using formatted
I/O statements.

FORMATTED INPUT:
scanf() statement is used to input the numeric, character and string type of data.

Syntax:- scanf(“control string”, address_list);

Example:- scanf(“%d%d”,&a,&b);
scanf(“%c%d%f”,&ch,&a,&r);

% indicates that a conversion specification.


Control String Meaning
%c Read a single character
%d Read a decimal integer
%e or %f or %g Read a floating-point number
%h Read a short int
%I Read a decimal or hexadecimal or octal number
%o Read on octal number
%p Read a pointer
%s Read a string
%u Read an unsigned integer
%x Read a hexadecimal number

FORMATTED OUTPUT:
C provides the printf() function to display the data on the monitor.

Syntax: printf(“control string”, varlist);


E.g.: printf(“%d”,num);
printf(“ result=%f\n”,res);
printf(“ area=%6.2f, circumference=%6.2f\n “,ar,ci);

Format specifiers for integers:


printf(“%d”,6789);
6 7 8 9
printf(“%8d”,1239);
1 2 3 9
printf(“%-8d”,1239);
1 2 3 9
printf(“%08d”,1239);
0 0 0 0 1 2 3 9
Format specifiers for floating point numbers:
printf(“%f”,num);
1 2 3 4 . 6 7 8 0 0 0
printf(“%10.2f”,num);
1 2 3 4 . 6 8
printf(“%-10.2f”,num);
1 2 3 4 . 6 8
printf(“%10.2e”,num);
1 . 2 3 E + 0 3
Format specifiers for characters:
printf(“%c”,”A”);
A
printf(“%4c”,”A”);
A
printf(“%-4c”,”A”);
A
Example program 1:
#include<stdio.h>
#include<conio.h>
void main()
{
int val=63;
clrscr();
printf(“\n val is %d”,val);
printf(“\n val is %2d”,val);
printf(“\n val is %4d”,val);
printf(“\n val is %6d”,val);
printf(“\n val is %-6d”,val);
getch();
}
Output:

Example Program 2:
#include<stdio.h>
#include<conio.h>
void main()
{
int num=126;
clrscr();
printf(“ number is=%d\n”,num);
printf(“ octal equivalent of %d=%o\n”,num,num);
printf(“ hexadecimal equivalent of %d=%x\n”,num,num);
printf(“hexadecimal equivalent of %d=%X\n”,num,num);
getch();
}
Output:

UNFORMATTED INPUT:
These statements are primarily concerned with reading the character type data from
keyboard.
getchar() function :This function reads a single character from the standard input
device.
Syntax: ch_var=getchar();

Page 31
gets() function: This function reads in everything you enter from the keyboard until the
ENTER key is pressed i.e., it reads a string of all printable ASCII characters.

Syntax: gets(string);

UNFORMATTED OUTPUT:
These statements are mainly concerned with displaying or printing the character type
data on the monitor.

putchar() function:- Thisfunction prints a single character on the screen.

Syntax: putchar(ch_var);

puts() function:-This function prints a string of characters on screen.

Syntax: puts(string);

Example 1:
#include<stdio.h>
#include<conio.h>
void main()
{
char letter;
clrscr();
letter=getchar();
putchar(letter);
getch();
}
Output:

Example 2:
#include<stdio.h>
#include<conio.h>
void main()
{
char mesg[20];
clrscr();
printf(“enter the message to be displayed\n”);
gets(mesg);
puts(mesg);
getch();
}

Page 32
All data transfer operations in C are carried out using functions available in the
standard library. These functions are known as the standard I/O library. These operations can
be classified into two types.
i. Buffered Input/output
ii. Unbuffered Input/output
Buffered Input:
 Buffer is a temporary storage in the memory. The characters entered at the keyboard
are stored in the buffer until the ENTER key is pressed and then made available to the
program as a block of characters.
 Input-output operations take less time on a buffered system.
 If any mistake is done while entering the data before ENTER key is pressed, can be
corrected.
E.g.: scanf() and getchar() are buffered input function.

Unbuffered Input:
Here, the character which is entered at the keyboard is made available to the program
immediately. It is useful in some interactive programs and to read and write binary data.

E.g.: getch() and getche() are unbuffered input function.

STANDARD MATHEMATICAL FUNCTIONS


Mathematical functions such as cos, sqrt, log, etc, are frequently used in analysis of
real life problems. Most of the C compilers support these basic math
functions[#include<math.h>].
Note : x and y should be declared as double.

Function Meaning
acos(x) Arc cosine of x
asin(x) Arc sine of x
atan(x) Arc tangent of x
atan2(x,y) Arc tangent of x/y
cos(x) Cosine of x
sin(x) Sine of x
tan(x) Tangent of x
cosh(x) Hyperbolic cosine of x
sinh(x) Hyperbolic sine of x
tanh(x) Hyperbolic tangent of x
ceil(x) X rounded up to the nearest integer
exp(x) E to the x power (ex)
fabs() Absolute value of x

. Page 33
floor(x) X rounded down to the nearest integer
fmod() Remainder of x/y
log(x) Natural log of x, x>0
log 10(x) Base 10 log of x, x>0
pow(x,y) X to the power y (xy)
sqrt(x) Square root of x, x>0

Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int x,y,p,z;
clrscr();
printf("enter x value\n");
scanf("%d",&x);
printf(“enter power\n”);
scanf(“%d”,&p)
y=sqrt(x);
z=pow(x,p);
printf("\n %d square root is=%d",x,y);
printf("\n %d power of %d=%d",x,p,z);
getch();
}
Output:

. Page 34
OPERATORS AND EXPRESSIONS

OPERATORS:
Operators are tools for manipulating data. Data items on which operators act are
called operands. Some operators act on only one operand. Such operators are called unary
operators. Similarly binary and ternary operators are there depending on the number of
operands on which they act.
Operators in C
 Arithmetic operators
 Assignment operator
 Relational operators
 Logical operators
 Conditional operators
 Bitwise operators
 Special operators
a. Arithmetic operators:
They are used to perform numerical manipulations in C.
Binary arithmetic operators
OPERATOR PURPOSE
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder of division
E.g.: sum=num1+num2;
Val=a-b-c;
Unary arithmetic operators
OPERATOR PURPOSE
- Unary minus
++ Increment
-- Decrement

E.g.: value=-6;
Z=-x+y;
Num=++i;
++int_var indicates pre increment. That is, the value of int_var must be incremented before it
is used (increment and use)
int_var++ indicates post increment. That is, use the value of int_var first and then increment
it (use and increment).
For example, a=++b;
This is equal to
b=b+1;
a=b;
Similarly, a=b++;

. Page 35
This is equal to
a=b;
b=b+1;
b. Assignment operator:
It is used to assign value to an identifier.
Syntax: variable=value or expression;
E.g.: num=20;
C allows users to combine assignment operators with arithmetic operators. Such
operators are called as compound assignment operators/ shorthand assignment operator.
Let num1=10, num2=13, f1=7.8 and f2=4.2
Assignment statement Equivalent Result
Num1=num1+50; Num1+=50; 60
Num1=num1*2; num1*=2; 20
num2=num2*10+20; num2*=10+20; 150
f1=f1/1.3; f1/=1.3; 6.0
num2=num2%5; num2%=5; 3
f1=f2+f1; f2+=f1; 12.0

c. Relational operators:
They are used to relate two quantities in conditional statements (if -statement)
Relational operator Meaning
== Equal to
!= Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
E.g.: if x=5, y=2 and z=0;
Then x > y + z evaluates to 5>2+0=1(true)
x + z <= y evaluates to 5+0<=2=0(false)
Differences between = and == signs
== is a relational operator
= is an assignment operator
== Sign does not change the value of the identifier, it only checks if one value is
equal to another value and gives the answer true or false
= sign assigns the value of the identifier on its left.
d. Logical operators:
The logical operators && and || are used when we want to test more than one
condition and make decisions.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

E.g.: if (age>55 && salary<1000)

. Page 36
if (number<0|| number>100)
if(num!=0)
e. Conditional operators:
It is also called ternary operator, as it operates on three operands.
Syntax: result=exp1? exp2:exp3;
E.g.1: c=a<b? a: b;
That is,
If a<b
c=a;
else
c=b;

E.g.2: C program to find biggest of two numbers.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,big;
clrscr();
printf(“\n enter two numbers”);
scanf(“ %d%d”,&a,&b);
printf(“%d,%d\n”,a,b);
big=a>b?a:b;
printf(“\n bigger is %d\n”,big);
getch();
}

Output:

f. Bitwise operators:

All data are stored in the computer as a sequence of bits (0‟s and 1‟s), and some
applications need the manipulation of these bits. Manipulation of individual bits is possible in
machine and assembly languages. But c provides operators to manipulate bits. Bitwise
operators can be applied only on integers and characters but not on float.

Operator Symbol name Meaning


& Ampersand Bitwise AND
| Pipeline Bitwise OR
^ Caret Exclusive-OR (XOR)

. Page 37
~ Tilde 1‟s complement
<< Double less than Left shifting of bits
>> Double greater than Right shifting of bits

For an 4-bit binary representation of numbers


Decimal Binary
Number
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
10 1010

For example consider a=4, b=3


4(10)=0100(2) and 3(10)=0011(2)
The result of bitwise AND of a and b The result of bitwise OR of a and b
a=0100 a=0100
b=0011 b=0011
a&b =0000 a|b=0111
The result of bitwise Exclusive-OR
a=0100
b=0011
a^b =0111 ( XOR gives output 1 if bits are different (1 and 0), if bits are same i.e., either
0 and 0 or 1 and 1 it gives output 0.)
The result of 1‟s complement
C = ~a
C = ~ (0100)
=1011

Left and right shift operators.


Syntax: <variable><shift operator><number of bits to be shifted>
Ex: Right shift operator Left shift operator
num=110011110 then ch=11010111 then
num>>1 gives 011001111 ch<<1 gives 10101110
num>>3 gives 000110011 ch<<3 gives 10111000
num>>5 gives 000001100 ch<<5 gives 11100000

. Page 38
Example: C program to illustrate bitwise operators.
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int x,y;
clrscr();
x=128; y=32;
x=x>>1;
printf(“\n After right shifting by 1,x=%d”,x);
y=y<<2;
printf(“\n After left shifting by 2,y=%d”,y);
getch();
}
Output:

27 26 25 24 23 22 21 20

128 64 32 16 8 4 2 1
X= 1 0 0 0 0 0 0 0
Y= 0 1 0 0 0 0 0 0

The result after shifting the bits


X= 0 1 0 0 0 0 0 0

Y= 1 0 0 0 0 0 0 0

g. Special operators:

C supports the following special operators.

1) Comma operator
2) Sizeof() operator
3) Pointer operators-> * dereferencing operator, & address operator
4) Member selection operators->dot (.) operator, -> arrow operator

Comma operator: It is basically associated with for statement. It is used to link the
related expressions together, it is used as statement separator to simplify some code.
Ex 1: sum=(a=10, b=15, a+b); 2) b=(a=20, a+10);
Equal to: a=10; equal to:
b=15; a=20;
sum=a+b; b=a+10;

. Page 39
sizeof() operator: It returns the size i.e., number of bytes of the operand. The operand
may be a constant, a variable or a datatype.
Syntax: sizeof(operand);
Variable declaration Expression Value
int num sizeof(num) 2
long num sizeof(num) 4
float num sizeof(num) 4
char ch sizeof(ch) 1
double num sizeof(num) 8
int a,b sizeof(a+2*b) 2

Example: C program to illustrate sizeof() operator.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,e;
float b,f;
double c,g;
char d,h;
clrscr();
e=sizeof(a);
f=sizeof(b);
g=sizeof(c);
h=sizeof(d);
printf(“\nsize of a=%d”,e);
printf(“\nsize of b=%f”,f);
printf(“\nsize of c=%f”,g);
printf(“\nsize of d=%d”,h);
getch();
}
Output:

Page 40
EXPRESSIONS:
An expression in c consists of a syntactically valid combination of operators and
operands that computes a value.

E.g.: 2+5*10 here + and * are operators and 2, 5 and 10 are operands.
An expression in c can be of the following types.
a. Arithmetic expression
b. Relational expression
c. Logical expression

Arithmetic expression:An expression that use arithmetic operators along with numeric or
character operands is called arithmetic expression.
i. Integer mode expressions: These are formed using integer type constants, variables,
functions and operators.
Operator Expression Result
+ 10+3 13
- 10-3 7
* 10*3 30
/ 10/3 3
% 10%3 1

ii. Real mode expressions: These are formed using real mode quantities constants,
variables functions and operators.
Operators Expression Result
+ 1.5+6.7 8.2
- 6.7-1.5 5.2
* 1.5*6.3 9.45
/ 6.4/3.2 2

iii. Mixed mode expressions: C permits mixing of integer and real quantities in an
expression.
Expression Result
1.5*10+6.7 21.7
7%5+10.0*10/4 27.0

Relational Expression: Ameaningful combination of operands and relational operators.

Operator Expression Result


== 7==8 false
!= 4/3!=7-5 True
< 8<19 True
<= 3*3<=3*4 True
> 9>23 False
>= 3*2>=3*4 False

Page 41
Logical Expression: The expression that result into 1 (true) or 0 (false) are called logical
expressions they use logical operators.

Operator Meaning Value Expression Result


! negation Num=3 !num False
&& AND m=69 (m>=35)&&(m<=100) True
|| OR ch=‟h‟ (ch>=‟a‟ || ch<=‟z‟) true

TYPE CONVERSIONS:
C can perform conversion between different data types, but a programmer should take
care with these conversions.
i. Implicit type conversion
ii. Explicit type conversion
i. Implicit type conversion:
When we perform arithmetic manipulation on operands belonging to different
data types, they may undergo type conversion automatically before evaluating the
final value.
Example 1:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5;
float b;
clrscr();
b=a;
printf("\n the value of a=%f",b);
getch();
}
Output:

Example 2:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
float b=45.67;
clrscr();
a=b;
printf("\n the value of a=%d",a);
getch();

Page 42
}
Output:

ii. Explicit Conversion (Type casting):


An explicit type conversion is user-defined that forces an expression to be of
specific type. Variable may be converted explicitly by type casting.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5;
float x;
clrscr();
x=(float)a;
printf("\n the value of x=%f",x);
getch();
}
Output:

Evaluation of Arithmetic expression:


The operators in C are evaluated in a specific order. This is known as precedence
(hierarchy) of operators.
Precedence Level Operators Associativity
1 ( ) Left to right
2 ++ -- Left to right
3 % * / Left to right
4 + - Left to right

BODMAS Rule:
 Brackets will have the first precedence
 Of operator will have the second precedence
 Division operator will have the third precedence
 Multiplication operator will have the fourth precedence
 Addition operator will have the fifth precedence
 Subtraction operator will have the sixth precedence

Example1: 6*(2+3)/5
=6*5/5
=6*1
=6

. Page 43
Example 2: x=a-b/3+c*2-1 let a=9, b=12 and c=3
X=9-12/3+3*2-1
=9-4+3*2-1
=9-4+6-1
=5+6-1
=11-1
=10
Example 3: C program to illustrate the use of variables in expressions and their
evaluation.
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c,x,y,z;
clrscr();
a=9; b=12; c=3;
x=a-b/3+c*2-1;
y=a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
printf(“x=%f\n”,x);
printf(“y=%f\n”,y);
printf(“z=%f\n”,z);
getch();
}
Output:

. Page 44
CONTROL STRUCTURE
Structured high level languages such as C contain statements that can alter the flow of
a sequence of instructions. These statements are called as control statements.
There are 3 types of statements
A. Sequence: It is step-by-step procedure to solve a given problem.
B. Selection statement
C. Looping statement Conditional control statements
D. Jumping statement Unconditional control statements
Selection statement:
It is the ability of a programming language to allow the user to decide on the
execution of a certain set of statements based on a requirement or condition. These constructs
are also called conditional constructs.
They are used to indicate decision in a program
Selection structure can be used to implement the following statements
1) Simple-if 2) if-else 3) Nested-if 4) if- else if 5) switch
1. Simple-if:
The if statement is the simplest form of selection statement. It is very frequently used
in decision making and altering the flow of program execution.
Syntax:if (test condition)
Statement;
Action: 1. Test condition is checked.
2. if test condition true, statement is executed
Example: C program to print bigger of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,big;
clrscr();
printf(“\n Enter two numbers”);
scanf(“%d%d”,&a,&b);
big=a;
if(b>big) big=b;
printf(“bigger of %d and %d is=%d\n”,a,b,big);
getch();
}
Output:

. Page 45
2. If-else:
Syntax: if (test condition)
Statement A;
else
Statement B;

Action: 1. Test condition is checked.


2. If test condition is true, statement A is executed.
3. If test condition is false A is skipped, statement B is executed.
Example: C program to check the given number is even or Odd.
#include<stdio.h>
#include<conio.h>
void main()
{

int num;
clrscr();
printf(“\n Enter a number”);
scanf(“%d”,&num);
if(num%2==0)
printf(“\n Number is Even”);
else
printf(“\n Number is Odd”);
getch();

Output:

3. Nested-if:
The if statement may itself contain another if statement is known as nested if.
Syntax: if (test condition 1)
if(test condition 2)
Statement A;
else
Statement B;
else
if (test condition 3)
Statement C;
else
Statement D;

. Page 46
Action: 1. Test condition 1 is checked.
2. If condition 1 is true, condition 2 is checked. If condition 2 is true, statement
A is executed if condition 2 is false, statement B is executed.
3. If condition 1 is false, condition 3 is checked. If condition 3 is true,
statement C is executed if condition 3 is false, statement D is executed.

Example:C program to find the biggest of three numbers.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,big;
clrscr();
printf(“\n Enter 3 numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
if(a>c)
big=a;
else
big=c;
else
if(b>c)
big=b;
else
big=c;
printf(“biggest of %d, %d and %d is %d\n”,a,b,c,big);
getch();
}
Output:

4. If else-if:
Syntax: if (test condition 1)
Statement A;
else if (test condition 2)
Statement B;
else if (test condition 3)
Statement C;
else

. Page 47
Statement D;

Action: 1. Test condition 1 is checked, if it is true A is executed.


2. if condition 1 is false, condition 2 is checked, if condition 2 is true B is
executed.
3. if condition 2 is false, condition 3 is checked, if condition 3 is true C is
executed.
4. if all the conditions are false, statement D is executed.
Example:C Program to find the grade of the student marks.
#include<stdio.h>
#include<conio.h>
void main()
{
int marks;
clrscr();
printf(“\n Enter marks”);
scanf(“%d”,&marks);
if(marks<35)
printf(“fail”);
else if(marks<50)
printf(“pass class”);
else if(marks<60)
printf(“second class”);
else if(marks<70)
printf(“first class”);
else
printf(“Distinction”);
getch();
}
Output:

5. Switch: (Multiple-selection statement)


Syntax:
Switch (control expression)
{
Case value 1: {statement A;
Break;
}
Case value 2: {Statement B;
Break;
}

. Page 48
Case value n :{ statement C;
Break;
}
Default: {default statement;
}
}
Action: 1. Control expression may be integer or character. This is compared with the
case value 1, case value 2 etc in the given order.
2. If control expression=case value 1 then statement A is executed.
3. If control expression= case value 2 then statement B is executed.
4. If control expression is not equal to any of the case values 1,2,3,...n then
default statement is executed.
Example:C program to perform arithmetic operations.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int a,b,c,ch;
clrscr();
printf("\n enter two numbers");
scanf("%d%d",&a,&b);
printf("1.add\n2.sub\n3.mul\n4.div\n5.exit");
printf("\n enter u r choice");
scanf("%d",&ch);
switch(ch)
{
case 1: c=a+b;
printf("\n sum=%d",c);
break;
case 2: c=a-b;
printf("\n sub=%d",c);
break;
case 3: c=a*b;
printf("\n mul=%d",c);
break;
case 4: c=a/b;
printf("\n div=%d",c);
break;
case 5: exit(0);
default: printf("\n enter proper choice");
}

. Page 49
getch();
}

Output:

Looping Statement:
The concept of loops is fundamental to structured programming. A loop is a program
construct that causes a statement to be executed again and again. The process of repeating the
execution of a certain set of statements again and again is termed as looping.
C has several such statements that can be used to form loops they are.
i. while statement
ii. do-while statement
iii. for statement
i. while statement:
This structure is also called as the “pre-tested” looping statement.
Syntax: while (test condition)
{
Statement 1;
Statement 2;
...........
}
Statement n+1;
Example: C program to find sum of the digits using while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,count=1;
clrscr();
while(count<=10)
{
sum=sum+count;
count++;
}
printf(“Total sum=%d”,sum);
getch();
}

. Page 50
Output:

ii. do-while statement


This structure is also called as the “post-tested” looping statement.
Syntax: do
{
Statements 1;
Statements 2;
..........
} while(test condition);
Statements n+1;
Example: C program to find product of the digits using do-while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int prod=1,count=1;
clrscr();
do
{
prod=prod*count;
count++;
}while(count<=10)
printf(“Total product=%d”,prod);
getch();
}
Output:

iii. for statement


for statement is also called as the “fixed execution” looping structure.
Syntax: for(Expression_1;Expression_2;Expression_3)
{
Statements_1;
Statements_2;

}
Statement_n+1;

1. Expression_1 represents the initialization expression.


2. Expression_2 represents the expression for the final condition.
3. Expression_3 represents the increment of decrement expression.

. Page 51
Example: C program to print the n elements using for loop.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
clrscr();
printf(“\n Enter n value”);
scanf(“%d”,&n);
for(i=0;i<=n;i++)
printf(“%d\n”,i);
getch();
}
Output:

Jumping statement:
The jump statements unconditionally transfer program control within a function.
There are 5 types of jumping statement
 goto
 break
 continue
 exit()
 return
1. goto statement:
The goto statement is a simple statement, used to transfer control from one
point in a program to any other point in that program.

Example:
goto label;
.................
.................
label: statement;

. Page 52
Example: C program to demonstrate the working of goto statement.
# include<stdio.h>
#include<conio.h>
void main()
{
float num,average,sum;
int i,n;
clrscr();
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump;
sum=sum+num;
}
jump: average=sum/(i-1);
printf("Average: %.2f",average);
getch();
}
Output:

2. break statement:
The break statement is used to terminate loops. It can be used within a while,
do-while or for statement.
Example: while( .... )
{
..........
..........
break;
..........
}
Next statement;

Example: C programto demonstrate the working of break statement.

Page 53
# include<stdio.h>
#include<conio.h>
void main()
{
float num,average,sum;
int i,n;
clrscr();
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break;
sum=sum+num;
}
average=sum/(i-1);
printf("Average: %.2f",average);
getch();
}
Output:

3. continue statement:
In some programming situation we want to take the control back to the beginning
of the loop, bypassing the statements inside the loop, which have not yet been executed.
Example:
while( ..... )
{
...........
...........
Continue;
...........
}
Next statement;

Page 54
Example: C program to find the product of 4 integers entered by a user. If user enters
0 skip it.

# include<stdio.h>
#include<conio.h>
void main()
{
int i,num,product;
for(i=1,product=1;i<=4;++i)
{
printf(“Enter num%d:”,i);
scanf(“%d”,&num);
if(num==0)
continue;
product*=num;
}
printf(“\n Product=%d”,product);
getch();
}
Output:

4. exit() function:
exit() is a standard library function that comes ready-made with the C compiler.
Its purpose is to terminate the execution of the program.

5. return statement:
The return statement is used to return from a function.

Page 55
ARRAYS
An array is defined as an ordered list of homogenous data elements stored in
consecutive memory locations.
OR
An array is a collection of similar type of elements stored in consecutive memory
locations.

Need for Arrays:


If a large amount of data is to be stored, it would be a long and tedious task to think of
a separate variable name for each datum, and then to type the declaration for each one of
these variables. Arrays are the solution to this problem. They are such an important part of
the art of programming that they are included in every high level language.
 To reduce program length.
 Easy to access.
 Make faster execution.
 To store large volume of data for similar type.
Index
Array Representation:
Array name
A[0] 2 A[7] 5
A[1] 3 A[6] 3
A[2] 4 A[5] 4
A[3] 5 A[4] 6
A[4] 6 A[3] 8
A[5] 7 A[2] 9
A[6] 8 A[1] 1
A[7] 9 A[0] 8
a) Vertical representation b) Building representation

23 45 90 35 40 22 85 65 48 50 59 60 65

A[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] a[12]
c) Horizontal representation

. Page 56
Types of Arrays:
Arrays are of different types-
i. One-dimensional array: A structured collection of elements, all of the same type
that is given a single name. Each element is accessed by an index that indicates
the components position within the collection.
ii. Two-dimensional array: A two dimensional array is a collection of elements, all
of the same type, structured in two dimensions. Each element is accessed by a pair
of indices that represent the elements position in each dimension.
iii. Multi-dimensional array: A collection of elements, all of the same type, ordered
on N dimensions (N>=1). Each element is accessed by N indices, each of which
represents the elements position within that dimension.

One-dimensional array (1D):


A one-dimensional array is astructured collection of elements that can be accessed
individually by specifying the position of an element with a single index value.

Declaration of array (1D):


Data_type Array_name[size];
Example: int a[20];
float height[5];
char name[30];

Array Initialization:
Thereare two types of array initialization.
i. Compile time initialization
ii. Run time initialization
Compile time initialization:
We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared.
Syntax: type array_name [size] = {list of values};
Example: int num[5]={2,5,6,4,6};

Run time initialization:


An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays.

Example: int x[3];


scanf(“%d%d%d”,&x[0],&x[1],&x[2]);

Will initialize array elements with the values entered through the keyboard.

Page 57
Example 1: C program to read and print one-dimensional array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i,n;
clrscr();
printf(“\n Enter size of elements”);
scanf(“%d”,&n);
printf(“\n Enter array elements”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n entered elements are\n”);
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
getch();
}
Output:

Example 2: C program to find the largest element in an array and position of its occurrence.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[100];
int large,pos,num,i;
clrscr();
printf(“\n enter number of elements”);
scanf(“%d”,&num);
for(i=0;i<num;i++)
scanf(“%d”,&a[i]);
large=a[0];

Page 58
pos=0;
for(i=1;i<num;i++)
{
if(large<a[i])
{
large=a[i];
pos=i;
}
}
printf(“\n Largest element in the array is %d\n”,large);
printf(“\n largest elements position in the array %d\n”,pos+1);
getch();
}
Output:

Two-dimensional array (2D):


A two dimensional array is used to represent elements in a table with rows and
columns, provided each element in the table is of the same type.

Two-dimensional array declaration:

Data_type array_name[row size][column size];


Example: int A[10][10];
A is a two dimensional array which contains 10 rows and 10 columns.

Two-dimensional array initialization


Similar to the one dimensional array, we can initialize a two-dimensional array either
by initializing it in its declaration or by using assignment statements.

Page 59
Example:
int matrix[2][3]={1,2,3,4,5,6};
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
Unsized: int sales[][4]={1,2,3,4,6,1,4,5,3,4,5,6};

Accessing elements of an array:


Initializing an array in its declaration is impractical if the array is large. For a 100-row
by 100-column array, it is very difficult to list 10,000 values. If the values are all different,
input them into array at runtime.
Consider the following declaration:
int a[3][3];
Read the 2D array and store them in the array a.
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
Print the 2D array and store them in the array a.
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d”,a[i][j]);
}
}
Example 1:C program to read and display a square matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],m,n,i,j;
clrscr();
printf(“\n Enter order of the matrix”);
scanf(“%d%d”,&m,&n);
printf(“\n enter matrix elements”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}

Page 60
}
printf(“matrix A is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“%d\t”,a[i][j]);
printf(“\n”);
}
getch();
}

Output:

Example 2: Program to add and subtract two MxN matrices


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;
clrscr();
printf("Enter m and n for matrix size\n");
scanf("%d%d",&m,&n);
printf("Enter the First Matrix : ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("Enter the Second Matrix : ");
for(i=0;i<m;i++)
{

Page 61
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
}
printf("\nThe Sum of Matrices is : \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t ",c[i][j]);
}
printf("\n");
}
printf("\n\nThe Difference of Matrices is : \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]-b[i][j];
printf("%d\t ",c[i][j]);
}
printf("\n");
}
getch();
}
Output:

Page 62
Example 2: Program to multiply two MxN matrices
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n;
clrscr();
printf("Enter the size of the matrix \n");
printf("as m*n\n");
scanf("%d",&m);
scanf("%d",&n);
printf("Enter the First matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the Second matrix\n");
for(i=0;i<m;i++)

Page 63
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("The First matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
}
printf("\nThe Second matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t",b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}

Page 64
}
}
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t",c[i][j]);
}
}
getch();
}
Output:

Multi-dimensional array:
Syntax: type array_name[s1][s2][s3] ..... [sm];
Where si is the size of the ith dimension.
Example:
int p[2][3][3][5];

Page 65
Unit-3
STRING HANDLING
String:
A string is a sequence of characters.
Declaration of string arrays:
Syntax: char variable_name [size];
Example: char name [20];

STRING ARRAY INITIALIZATION


Once you declare an array, you can enter its value using scanf () or gets ().You can
also assign the array initial values when you declare it.
Example:consider the following string initialization.
Case 1: char name [9] =”COMPUTER”;

C O M P U T E R \0

name [0] [1] [2] [3] [4] [5] [6] [7] [8]

Case 2: char name []=”Computer”;

OR

Case 3: char name [9] = {‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’\0’};

READING A STRING:

To read a string, we use a standard I-O library function scanf().Scanf () reads


formatted input from the standard input device, which is usually the keyboard. We can read
values into a string with scanf () function using %sformatting code:

scanf (“%s”,name);

There is a problem with scanf () function while reading a string data. Consider the
following program.

Program 1:A C program to read a string using scanf () function.


#include <stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
printf(“Enter a string\n”);

Page 66
scanf(“%s”,name);
printf(“\n Entered string was %s”, name);
getch();
}
Output:

The input string was sri nagar but the output result is sri, this is because of
the blank space. The scanf () function accepts characters one at a time until it encounters a
blank space or newline character. To avoid such error, c provides another function called
gets(). The gets() function accepts an entire line of input from the standard input device.

Program 2:A C program to read a string using gets() function.


#include <stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
printf(“Enter a string\n”);
gets(name);
printf(“\n Entered string was %s”, name);
getch();
}
Output:

WRITING (PRINTING) A STRING:

puts() and printf() functions are used to display a string on the standard output device.

Program 2:A C program to read and write a string using gets()and puts() function.
#include <stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
puts(“Enter a string\n”);
gets(name);
puts(“\n Entered string is:”);

Page 67
puts(name);
getch();
}
Output:

STRING OPERATIONS:

The C library supports a large number of string handling functions that can be used to
carry out many of the string manipulations such as

 Length (number of characters in a string)


 Concatenation (Adding two or more strings)
 Comparing two strings
 Substring (Extract substring from the given string)
 Copy (copies one string over another)

Note:To use all the string operations in C you must include string.h library header file in the
program

STRING HANDLING FUNCTIONS:

FUNCTION DESCRIPTION
Strcat() Adds the characters of one string to another.
Strcmp() Compares two strings considering case.
Strcmpi() Compare two strings; not case sensitive.
Strcpy() Copies one string or string literal, to another.
Strlen() Calculates the string length.
Strlwr() Converts a string to lowercase.
Strupr() Converts a string to uppercase.
Strchr() Returns the position of a specified character in the string.
Strcspn() Returns the position of a character in the string from a specified character
set.
Strncat() Appends specified characters from one string to another.
Strncmp() Compares specified characters of two strings.
Strncpy() Copies specified characters from one string to another.
Strnset() Changes specified characters in a string to another character.
Strrev() Reverses the characters in a string.
Strstr() Finds one string within another.

1. strlen() FUNCTION

This function counts and returns the number of characters in a string. The length does not
include the NULL character.

Page 68
Syntax: n=strlen(string);

Where n is an integer variable which receives the value of the length of


the string.

Example1: write a c program to find the length of a string.

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char name[100];
int length;
clrscr();
printf(“enter a string\n”);
gets(name);
length=strlen(name);
printf(“\n Number of characters in the string is %d”,length);
getch();
}

Output:

Example2: write a c program to find the frequency of occurrence of a specified character.

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char text[100],ch;
int length,i,count=0;
clrscr();
printf(“enter a string\n”);
gets(text);
puts(“Enter a character to be searched”);
scanf(“%c”,&ch);
length=strlen(text);
for(i=0;i<length;i++)

. Page 69
if(text[i]==ch) count++;
if(count)
printf(“\n %c occurs %d times”,ch,count);
else
printf(“\n %c does not exist in the text”,ch);
getch();
}
Output:

Example3: write a c program to find the length of a string without using strlen().

#include<stdio.h>
#include<conio.h>
void main()
{
char str[25];
int len=0;
clrscr();
printf(“enter a string\n”);
gets(str);
while(str[len]!=‟\0‟)
len++;
printf(“\n Number of characters in the string is %d”,len);
getch();
}
Output:

2. strcpy() FUNCTION:
C does not allow you to assign characters to a string directly, as in the
statement
char name[30];
name=”NIE”;
Instead, use the strcpy() function found in most compilers. The syntax of the function
is illustrated below:
Syntax: strcpy(string1,string2);

. Page 70
Assign the contents of string2 to string1. String2 may be a character
array variable or a string constant.
Example: strcpy(name,”NIE”);
Example1: write a c program to copy one string to another.

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char name[100], city[100];
clrscr();
printf(“enter a string\n”);
gets(name);
strcpy(city,name);
printf(“\n copied string is %s”,city);
getch();
}
Output:

Example2: write a c program to copy one string to another without using strcpy().
#include<stdio.h>
#include<conio.h>
void main()
{
char src[25], dest[25];
int i=0;
clrscr();
printf(“enter a string”);
gets(src);
do
{
dest[i]=src[i];
}while(src[i++]!=‟\0‟);
printf(“\n copied string is %s”,dest);
getch();
}
Output:

. Page 71
3. strcat() FUNCTION:
When you combine two strings, you add the characters of one string to the end of
another string. The process is called concatenation. The strcat() function joins two strings
together.
Syntax: strcat(string1,string2);
Example: strcpy(st1,”sri”);
strcpy(st2,”nagar”);
printf(“%s”,strcat(st1,st2));

Example1: write a c program to concatenate two strings.

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char st1[100], st2[100];
clrscr();
printf(“enter a string1\n”);
gets(st1);
printf(“enter a string2\n”);
gets(st2);
printf(“\n concatenated string is %s”,strcat(st1,st2));
getch();
}
Output:

Example1: write a c program to concatenate two strings without using strcat().

#include<stdio.h>
#include<conio.h>
void main()
{
char str1[25], str2[25];
int i=0,j=0;
clrscr();
printf(“enter a string1”);

. Page 72
gets(str1);
printf(“enter a string2”);
gets(str2);
while(str1[i]!=‟\0‟)
i++;
while(str2[j]!=‟\0‟)
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]=‟\0‟;
printf(“\n concatenated string is %s”,str1);
getch();
}
Output:

4. strcmp() FUNCTION:
In C you cannot directly compare the value of two strings in a condition
Like this:
If(st1==st2)
Instead, use the strcmp() function found in most compilers. The syntax of the function
is illustrated below:
Syntax: strcmp(string1,string2);
String1 and string2 may be string variables or string constants. Some
compilers return a negative if the string1 is alphabetically “less than” the second, and a
positive number if the first string is greater than the second.
Example1: strcmp(“MYSORE”,”MYSORE”)will return 0 because two strings are
equal

Example2: strcmp(“their”,”there”)will return -9 which is the numeric difference


between ASCII “i” and ASCII “r”.
Example3: strcmp(“there”,”their”)will return 9 which is the numeric difference
between ASCII “r” and ASCII “i”.
Example4: strcmp(“THE”,”the”)will return -32 which is the numeric difference
between ASCII “T” and ASCII “t”.
Example5: write a c program to compare two strings.

#include<stdio.h>

. Page 73
#include<string.h>
#include<conio.h>
void main()
{
char st1[100], st2[100];
int n;
clrscr();
printf(“enter a string1\n”);
gets(st1);
printf(“enter a string2\n”);
gets(st2);
n=strcmp(st1,st2);
printf(“\n Numeric difference between ASCII value is %d”,n);
getch();
}
Output:

Example6: write a c program to compare two strings without using strcmp().

#include<stdio.h>
#include<conio.h>
void main()
{
char str1[25], str2[25];
int dif,i=0;
clrscr();
printf(“enter a string1”);
gets(str1);
printf(“enter a string2”);
gets(str2);
while(str1[i]!=‟\0‟ || str2[i]!=‟\0‟)
{
dif=(str1[i]-str2[i]);
if(dif!=0)
break;
i++;
}
if(dif>0)
printf(“%s comes after %s”,str1,str2);
else

. Page 74
{
if(dif<0)
printf(“%s comes after %s”,str2,str1);
else
printf(“Both the strings are same”);
}
getch();
}
Output:

5. strcmpi() FUNCTION
This function is same as strcmp(), which compares two strings, but is not case
sensitive.
Example1: write a c program to compare two strings using strcmpi().

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char st1[100], st2[100];
int n;
clrscr();
printf(“enter a string1\n”);
gets(st1);
printf(“enter a string2\n”);
gets(st2);
n=strcmpi(st1,st2);
printf(“\n Numeric difference between ASCII value is %d”,n);
getch();
}
Output:

. Page 75
6. strlwr() FUNCTION:
This function converts all uppercase characters in a string to lowercase
Syntax: strlwr(string);
Example1: write a c program to convert uppercase character to lowercase character.

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char name[100];
clrscr();
strcpy(name,”COMPUTER”);
printf(“\n Converted string is %s”,strlwr(name));
getch();
}
Output:

Example2: write a c program to convert uppercase character to lowercase character


without using strlwr().

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str[25];
int i;
clrscr();
printf(“Enter a string”);
gets(str);
for(i=0;i<=strlen(str);i++)
{
if(str[i]>=65 && str[i]<=90)
str[i]=str[i]+32;
}
printf(“\n Converted string is %s”,str);
getch();
}

. Page 76
Output:

7. strupr() FUNCTION:
This function converts all lowercase characters in a string to uppercase
characters.
Syntax: strupr(string);
Example1: write a c program to convert lowercase character to uppercase character.

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char name[100];
clrscr();
strcpy(name,”computer”);
printf(“\n Converted string is %s”,strupr(name));
getch();
}
Output:

Example2: write a c program to convert lowercase character to uppercase character without


using strupr().

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str[25];
int i;
clrscr();
printf(“Enter a string”);
gets(str);
for(i=0;i<=strlen(str);i++)
{
if(str[i]>=97&& str[i]<=122)
str[i]=str[i]-32;

. Page 77
}
printf(“\n Converted string is %s”,str);
getch();
}
Output:

8. strrev() FUNCTION:
This function reverses the characters in a string.

Syntax: strrev(string);

Example1: write a c program to check whether a given word is palindrome or not.

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char st1[100], st2[100];
clrscr();
printf(“Enter a string”);
scanf(“%s”,st1);
strcpy(st2,st1);
strrev(st2);
if(strcmp(str1,str2)==0)
printf(“%s is a palindrome”,st1);
else
printf(“%s is not a palindrome”,st1);
getch();
}
Output:

Example2: write a c program to reverse the given string without using strrev().

#include<stdio.h>
#include<string.h>
#include<conio.h>

. Page 78
void main()
{
char str[100],temp;
int i,j=0;
printf(“enter the string:”);
gets(str);
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf(“\nReverse string is :%s”,str);
getch();
}
Output:

ARRAY OF STRINGS
An array of strings is a two-dimensional array. The size of first index (rows)
determines the number of strings and the size of second index (columns) determines
maximum length of each string.

Example:consider the following array declaration


char name[8][20];
Declares an array of 8 strings, each of which can hold maximum of 20 characters.
An array of strings appears in memory as shown in figure.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
D H A R W D \0
G U L B A R G A \0
S H I M O G A \0
C H I K A M A G A L U R \0
M Y S O R E \0
B A N G A L O R E \0
K A R A W A R \0

. Page 79
name[0] H A S S A N \0
.
.
.
.
.
.
.
.
.
Name[7]

Example: A C program to arrange N names in alphabetical order.


#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char name[10][20];
char tempname[20];
int n,i,j;
clrscr();
printf(“Enter number of names\n”);
scanf(“%d”,&n);
printf(“Enter list of names\n”);
for(i=1;i<n;i++)
gets(name[i]);
for(i=1;i<n;i++)
for(j=0;j<n-i;j++)
if(strcmp(name[j],name[j+1])>0)
{
strcpy(tempname,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],tempname);
}
printf(“\n Sorted names”);
for(i=0;i<n;i++)
printf(“\n%s”,name[i]);
getch();
}
Output:

. Page 80
FUNCTIONS

MODULE: A self contained collection of steps that solves a problem or sub-problem.

Large programs can be made manageable by dividing it into smaller sub-programs or


modules. These sub-programs are called as functions.

OR
A function is a named unit of a group of program statements designed to perform a
specific task and returns a single value.

C supports two types of functions. They are


i. Built-in or library functions.
ii. User defined functions.

i. Built-in or library functions:


A function defined by the C compiler.
Example: sqrt(), strcpy(), pow(), cos() and so on.
ii. User defined functions:
A function defined by the user.
Example:sum(), mul(), search(),read() and so on.
NEED OF FUNCTIONS:
i. Repetition: If there is a portion of the program, which is to be repeated in a number
of places in the program, a function may be used to avoid rewriting the same sequence
of code at two or more, locations in the program. This is especially useful if the code
involved is long or complicated.
ii. Universal use: Some tasks might be needed in more than one program or a large
group of programmers may need the same task. By writing a function and making it
available to others the duplication of effort can be avoided.

Page 81
iii. Modularity: A program for complex problems can be developed in a modular fashion
by dividing the problem into modules, or functions, each function performing a
definite task. Since the functions are independent of each other, each one of them can
be developed and tested without worrying about the details of the other modules.
iv. Teamwork: If a program is divided into sub-programs, a number of members can
form a team and each person in the team can develop a separate sub-program, rather
than having a single person work on the complete program.

USE OF FUNCTIONS:
 Programs with functions are compact thus decreasing the number of lines of code to a
very large extent.
 Debugging the code is much simpler because errors can be localized and corrected
easily.
 Functions increase the readability of the program and helps in proper and good
documentation.
 Many other programs may use a function, thus helping us to create our own libraries.

FUNCTION DEFINITION OR SYNTAX

Return_type_specifier function_name (type arg1, type arg2. .......... )


{
Local variable declarations;
Statement 1;
Statement 2;
.......................
.......................
Statement n;
Return (Expression);
}

Body of the function Argument list with declaration

i. Return_type_specifier

The return_type_specifier identifies the type of value, which will be sent back
after the function has performed its task. The return_type_specifier can include the
normal data types such as int, float, char the data type void is used if the function does
not return a value.

ii. Function_name
The function_name thus helps us to uniquely identify and call a function.
iii. Argument list with declaration

Page 82
The argument list identifies the set of values, which are to be passed to the
function from either the main program or a sub-program.

iv. Body of the function

The body of the functions first includes the identification of those components,
which will be used only within the function and not outside it. Thus those components are
declared as local variables.

Next a function contains a set of executable statements, which will perform the
required task for the user. The last executable statement of the function is the word
“return” with an expression, which contains the value that has to be sent back to the
main program.

FUNCTION CALL:

A statement that transfers control to a function. In c, this statement is the name of the
function, followed by a list of arguments.

A function can be called by simply using the function name in a statement. A function
call has the following syntax.

Variable=function_name (arg1, arg2 ...);

Values are passed on to a sub-program by copying values from the actual paramenters
(function call) to the formal parameters (function header)

Formal parameter: A variable declared in a function heading is also called formal argument
or formal parameter.

OR

The definition of a function or the function body also includes a set of parameters or
arguments these arguments are called as formal arguments or dummy arguments.

Actual Argument: A variable or expression listed in a call to a function is also called actual
argument or actual parameter.

OR

Page 83
A function call includes the function name with some parameters or arguments, these
arguments are known as actual arguments.

Function prototypes:

A function prototype is a declaration of the function that tells the program about the
type of the value returned by the function and the number and type of arguments.
Syntax: return_type_specifier function_name();
OR
Return_type_specifier function_name(type1,type2,. );
Example 1:C program to find the sum of the digits of a number until the resulting value is a
one digit number.
#include<stdio.h>
#include<conio.h>
void main()
{
int sum_of_digits(int); function prototype
int num,sum,n;
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&num);
n=num;
while(n>=9) calling function
{
sum=sum_of_digits(n); n is an actual argument
n=sum;
}
printf(“the number is=%d\n”,num);
printf(“sum of digits until one digit=%d\n”,sum);
getch();
}
int sum_of_digits(int n) n is a formal argument
{ Called function
int d,s=0; Local declaration
while(n>0)

Page 84
{
d=n%10;
n=n/10;
s=s+d;
}
return(s); returns value
}

Output:

LOCAL AND GLOBAL VARIABLES:


Local variable: A variable declared within a block and not accessible outside of the block
Example:
Function(int m, int n)
{
int a,b; a and b are local variables

Global variable: A variable declared outside of all the functions in a program.


Example:

int a,b; a and b are global variables


main()
{
int p,q; p and q are local variables

Example 2: C program to find the largest of two numbers using the global variable
declaration.
#include<stdio.h>
#include<conio.h>
int num1,num2,lar; Global declaration
void main()
{
int largest(); Function prototype
clrscr();
printf(“enter two numbers”);
scanf(“%d%d”,&num1,&num2);
printf(“Largest of %d and %d is %d”,num1,num2,largest());
getch(); Calling function
}
int largest() Called function or definition of the function
{
lar=(num1>num2)?num1:num2;
return(lar);
}
Output:

CALL BY VALUE:
A parameter that receives a copy of the value of corresponding argument.
Example 1: C program to illustrate the function using call by value mechanism.
#include<stdio.h>
#include<conio.h>
void main()
{
void function(int,int);
int a=20,b=30;
clrscr();
printf(“a=%d b=%d before function call \n”,a,b);
function(a,b);
printf(“a=%d b=%d after function call\n”,a,b);
getch();
}
void function(int x,int y) call by value function
{
x=x+x;
y=y+y;
}

Output:

The corresponding formal parameter represents a local variable in the called function.
The current value of the corresponding actual parameter becomes the initial value of the
formal parameter. The value of formal parameter may then change in the body of the
subprogram by assignment or input statements. This will not change the value of the actual
parameter.

CALL BY REFERENCE:
A parameter that receives the memory address of corresponding argument.
Example 2:C program to illustrate the function using call by reference mechanism.
#include<stdio.h>
#include<conio.h>
void main()
{
void function(int *,int *);
int a=20,b=30;
clrscr();
printf(“a=%d b=%d before function call \n”,a,b);
function(&a,&b);
printf(“a=%d b=%d after function call\n”,a,b);
getch();
}
void function(int *x,int *y) call by reference function
{
*x=*x+*x;
*y=*y+*y;
}
Output:

Example 3: C program to exchange the contents of the two variables using call by value and
call by reference.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap_val(int,int);
void swap_ref(int *,int *);
clrscr();
printf(“Enter two numbers\n”);
scanf(“%d%d”,&a,&b);
printf(“a=%d b=%d before function call\n”,a,b);
swap_val(a,b);
printf(“a=%d b=%d after function call using call by value\n”,a,b);
swap_ref(&a,&b);
printf(“a=%d b=%d after function call using call by reference\n”,a,b);
getch();
}
void swap_val(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void swap_ref(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Output:

TYPES OF FUNCTIONS OR CATEGORIES OF FUNCTION:


i. Functions with no arguments and no return values.
ii. Functions with arguments and no return values.
iii. Functions with arguments and with return values.
iv. Recursive functions.

i. Functions with no arguments and no return values:


In this type of function the first function calls the second function. However no
arguments are passed to the second function. The second function performs its
calculations but no value is sent back to the first function.
Calling Function Action Called Function
Function1() Function2()
{ No arguments {
----------------
----------------
Function2(); ----------------
} No return values
}

Example: C program to illustrate a function with no arguments and no return values.


#include<stdio.h>
#include<conio.h>

. Page 89
void main()
{
void Our_address();
clrscr();
Our_address();
getch();
}
void Our_address()
{
printf(“\n NIE FGC”);
printf(“\n Mysore”);
}
Output:

ii. Functions with arguments and no return values:


In this type of function the first function calls the second function by passing some
arguments or values to the second function. The second function performs its
calculations but no value is sent back to the first function.
Calling Function Action Called Function
Function1() Function2(a)
{ Arguments {
----------------
----------------
Function2(x); ----------------
} No return values
}

Example: C program to find the type of character entered using functions.


#include<stdio.h>
#include<conio.h>
void main()
{
void char_type(char);

. Page 90
char ch;
clrscr();
printf(“enter a character\n”);
scanf(“%c”,&ch);
char_type(ch);
getch();
}
void char_type(char c)
{
if((c>=‟a‟)&&(c<=‟z‟))
printf(“%c is a lower case alphabet\n”,c);
else if((c>=‟A‟)&&(c<=‟Z‟))
printf(“%c is an upper case alphabet\n”,c);
else if((c>=‟0‟)&&(c<=‟9‟))
printf(“%c is a digit\n”,c);
else
printf(“%c is a special character\n”,c);
}
Output:

iii. Functions with arguments and with return values:


In this type of function the first function calls the second function by passing some
arguments or values to the second function. The second function performs its
calculations and returns the answer or a value back to the first function.
Calling Function Action Called Function
Function1() Function2(a)
{ Arguments {
----------------
----------------
Function2(x); ----------------
} Return values return(e);
}

. Page 91
Example:C program to find lcm and gcd using function.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,g,l;
int gcd(int,int);
clrscr();
printf(“Enter the numbers a and b\n”);
scanf(“%d%d”,&a,&b);
g=gcd(a,b);
l=(a*b)/g;
printf(“GCD of %d and %d=%d\n”,a,b,g);
printf(“LCM of %d and %d=%d\n”,a,b,l);
getch();
}
int gcd(int x,int y)
{
while(x!=y)
if(x>y)
x=x-y;
else
y=y-x;
return(x);
}
Output:

iv. Recursive functions:


Functions that call itself directly or indirectly again and again is called recursive
function.

Function1(a)
OFESSOR
{ IN CS DEPT. Page 92
Example:C program to find the factorial of the given number using recursive function.

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
int fact(int);
clrscr();
printf(“enter any non-negative integer\n”);
scanf(“%d”,&n);
if(n<0)
printf(“Invalid Input”);
else
printf(“factorial of %d is=%d\n”,n,fact(n));
getch();
}
int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}

Output:

FUNCTIONS AND ARRAYS:


We can pass an entire array from one function to another. To pass an entire array to a
function we will have to just pass the name of the array as the actual argument. When we
pass a normal variable other than an array, c makes a copy of the data and places it in a
memory location associated with the receiving variable.
Example:C program to sort in ascending order using a function.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100];
int i,num;
void output(int *,int);
void selection_sort(int *,int);
clrscr();
printf(“Enter number of element in the array\n”);
scanf(“%d”,&num);
printf(“Enter Array elements \n”);
for(i=0;i<num;i++)
scanf(“%d”,&a[i]);
printf(“Unsorted array\n”);
output(a,num);
selection_sort(a,num);
printf(“\n sorted array\n”);
output(a,num);
getch();
}
void output(int b[],int n)
{
int i;
for(i=0;i<n;i++)
printf(“%d\t”,b[i]);
}
void selection_sort(int b[],int n)
{
int i,j,min,pos;
for(i=0;i<n-1;i++)
{
min=b[i];
pos=i;
for(j=i+1;j<n;j++)
if(b[j]<min)
{
min=b[j];
pos=j;
}
b[pos]=b[i];
b[i]=min;
}
}
Output:

STRUCTURES AND UNIONS


STRUCTURE:
C provides a way to collect different types of data together into one entity,
called a structure.
OR
It is a group of logically related data items of same type or different types.

DIFFERENCE BETWEEN ARRAY AND STRUCTURE:


Array Structure
Array is a collection of homogeneous data Structure is a collection of heterogeneous
data
Array elements are referred by subscript Structure elements are referred by unique
name
Array elements are accessed by its position Structure elements are accessed by its objects
or subscript as „.‟ Operator
Array is a derived data type Structure is user defined data type
Syntax: struct structure_name
{
Data_type array_name[size]; Data_type member1;
Data_type member2;

Data_type member n;
}struct_var_name;
Example: struct item
int rno[5]; {
int rno;
char name[50];
}itm;

DEFINITION AND DECLARATION OF A STRUCTURE OR SYNTAX:

. Page 95
struct structure-name
{
Data_type member_name_1;
Data_type member_name_2;
Data_type member_name_3;
...................................................
Data_type member_name_n;
};

DECLARATION OF A STRUCTURE:

Syntax: Struct structure_name variable;

Instance 1:

struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
}emp;

Instance 2:

struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
};
struct emp_info emp;

ACCESSING THE ELEMENTS OF A STRUCTURE:

Structure members can be accessed using member operator '.' . It is also called as 'dot
operator' or 'period operator'.

Syntax: structure_variable_name.member_name

Example:C program to show the use of structures.

Page 96
#include<stdio.h>
#include<conio.h>
void main()
{
struct item
{
char name[20];
float price;
};
struct item i1,i2,i3,i4,i5;
clrscr();
printf(“Enter the name and prices of four items\n”);
scanf(“%s%f”,i1.name,&i1.price);
scanf(“%s%f”,i2.name,&i2.price);
scanf(“%s%f”,i3.name,&i3.price);
scanf(“%s%f”,i4.name,&i4.price);
scanf(“%s%f”,i5.name,&i5.price);
printf(“The data entered is \n”);
printf(“%s\t%.2f\n”,i1.name,i1.price);
printf(“%s\t%.2f\n”,i2.name,i2.price);
printf(“%s\t%.2f\n”,i3.name,i3.price);
printf(“%s\t%.2f\n”,i4.name,i4.price);
printf(“%s\t%.2f”,i5.name,i5.price);
getch();
}

Output:

INITIALIZING STRUCTURE VARIABLE IN C:

1. Memory is not allocated for un-initialized variable.


2. Let us discuss very familiar example of structure student, we can initialize structure
variable in different ways

Page 97
Way 1: Declare and Initialize.

struct student
{
char name[20];
int roll;
Float marks;
}std1={“prakash”,67,78.5};

Way 2: Declaring and Initializing multiple variables.

struct student
{
char name[20];
int roll;
float marks;
}
std1={“prakash”,67,78.5};
std2={“ramesh”,75,86.4};

STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES):


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

struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;

struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;

Page 98
}outer_struct_var;

Example :

struct stud_Res
{
int rno;
char nm[50];
char std[10];

struct stud_subj
{
char subjnm[30];
int marks;
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a
structure with two members. Structure stud_Res is called as 'outer structure' while stud_subj
is called as 'inner structure.' The members which are inside the inner structure can be
accessed as follow :
result.subj.subjnm
result.subj.marks

Example 1: Program to demonstrate nested structures.

#include <stdio.h>
#include <conio.h>

struct stud_Res
{
int rno;
char std[10];
struct stud_Marks
{
char subj_nm[30];
int subj_mark;
}marks;
}result;

void main()
{
clrscr();
printf("\n\t Enter Roll Number : ");

Page 99
scanf("%d",&result.rno);
printf("\n\t Enter Standard : ");
scanf("%s",result.std);
printf("\n\t Enter Subject Code : ");
scanf("%s",result.marks.subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\n\t Roll Number : %d",result.rno);
printf("\n\n\t Standard : %s",result.std);
printf("\n\n\tSubject Code : %s",result.marks.subj_nm);
printf("\n\n\t Marks : %d",result.marks.subj_mark);
getch();
}
Output :

Example 2: C Program to illustrate the use of nested structures.


#include<stdio.h>
#include<conio.h>
void main()
{
struct date
{
int year;
int month;
int day;
};
struct student
{
int reg_no;
char name[20];
struct date dob;
}std1;
clrscr();

Page 100
printf(“Enter student Reg_no and name\n”);
scanf(“%d%s”,&std1.reg_no,std1.name);
printf(“Enter date of birth of the student\n”);
scanf(“%d%d%d”,&std1.dob.day,&std1.dob.month,&std1.dob.year);
printf(“Student Information\n\n”);
printf(“Reg-no : %d\n”,std1.reg_no);
printf(“Name: %s\n”,std1.name);
printf(“%d/%d/%d”,std1.dob.day,std1.dob.month,std1.dob.year);
getch();
}

Output:

STRUCTURE WITH ARRAY:


We can create structures with array for ease of operations in case of getting multiple same
fields.

Example:Program to demonstrate Structure with Array.

#include <stdio.h>
#include <conio.h>

struct emp_info
{
int emp_id;
char nm[50];
}emp[2];

void main()
{
int i;
clrscr();
for(i=0;i<2;i++)
{
printf("\n\n\t Enter Employee ID : ");
scanf("%d",&emp[i].emp_id);
printf("\n\n\t Employee Name : ");

Page 101
scanf("%s",emp[i].nm);
}
for(i=0;i<2;i++)
{
printf("\n\t Employee ID : %d",emp[i].emp_id);
printf("\n\t Employee Name : %s",emp[i].nm);
}
getch();
}

Output :

UNION:

Union is user defined data type used to stored data under unique variable name at single
memory location.
Union is similar to that of structure. Syntax of union is similar to structure. But the
major difference between structure and union is 'storage.' In structures, each member has
its own storage location, whereas all the members of union use the same location. Union
contains many members of different types; it can handle only one member at a time.
To declare union data type, 'union' keyword is used.

Union holds value for one data type which requires larger storage among their members.

Syntax:

union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;

. Page 102
Example:

union techno
{
int comp_id;
char nm;
float sal;
}tch;

In above example, it declares tch variable of type union. The union contains three members
as data type of int, char, float. We can use only one of them at a time.

* MEMORY ALLOCATION :

Fig : Memory allocation for union

To access union members, we can use the following syntax.


tch.comp_id
tch.nm
tch.sal

Example: Program to demonstrate union.

#include <stdio.h>
#include <conio.h>
union techno
{
int id;
char nm[50];
}tch;
void main()
{
clrscr();
printf("\n\t Enter developer id : ");
scanf("%d", &tch.id);
printf("\n\n\t Enter developer name : ");
scanf("%s", tch.nm);

. Page 103
printf("\n\n Developer ID : %d", tch.id);//Garbage
printf("\n\n Developed By : %s", tch.nm);
getch();
}
Output :

An array is a collection of memory locations

POINTERS
A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a pointer
before you can use it to store any variable address.

POINTER DECLARATION:

variable typepointer variable name

data_type *var_name;

A asterisk denotes a pointer

Example:
int *p;
char *ch;
double *dp;
float *fp;

Program 1: A C program to show the creation of a pointer variable.


#include<stdio.h>
#include<conio.h>
void main()
{
int num=5;
int *ptr;

. Page 104
clrscr();
ptr=&num;
printf(“Address of the variable num=%u\n”,&num);
printf(“value of the variable num=%d\n”,num);
printf(“Address present in the pointer variable ptr=%u\n”,ptr);
getch();
}
Output:

POINTER OPERATOR:

Page 105
Page 106
Program 2:To illustrate pointer declaration.

#include<stdio.h>
#include<conio.h>
void main()
{
int *ptr;
int num;
clrscr();
num=45;
ptr=&num;
printf(“value of Num is %d\n”,num);
printf(“Address of Num is %u”,&num);
printf(“The contents of ptr is %u\n”,ptr);
printf(“Value of num is %d”,*(&num));
printf(“Value pointed by ptr %d\n”,*ptr);
printf(“The address of pointer is %u”,&ptr);
getch();

Page 107
Output:

POINTER EXPRESSIONS AND POINTER ARITHMETIC:

C pointer is an address, which is a numeric value. Therefore, you can perform


arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic
operators that can be used on pointers: ++, --, +, and -

To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic
operation on the pointer:
ptr++;
Now, after the above operation, the ptr will point to the location 1004 because each
time ptr is incremented, it will point to the next integer location which is 4 bytes next to the
current location. This operation will move the pointer to next memory location without
impacting actual value at the memory location. If ptr points to a character whose address is
1000, then above operation will point to the location 1001 because next character will be
available at 1001.
Program 3:To illustrate the pointer expression and pointer arithmetic.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,x,y,z;
int *ptr1,*ptr2;
clrscr();
a=30;
b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+*ptr2-6;
y=6-*ptr1/*ptr2+30;

Page 108
printf(“\nAddress of a=%u”,ptr1);
printf(“\nAddress of b=%u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
*ptr1=*ptr1+70;
*ptr2=*ptr2*2;
printf(“\na=%d,b=%d”,a,b);
getch();
}
Output:

POINTERS AND FUNCTIONS:


Pointers are used very much with functions. Also sometimes complex function
can easily be represented and accessed only with a pointer. Arguments can be passed to one
of the following methods.
1. Passing values of the arguments(call by value)
2. Passing the addresses of the arguments (call by reference)

CALL BY VALUE:
A parameter that receives a copy of the value of corresponding argument.
Example 1: C program to illustrate the function using call by value mechanism.
#include<stdio.h>
#include<conio.h>
void main()
{
void function(int,int);
int a=20,b=30;
clrscr();
printf(“a=%d b=%d before function call \n”,a,b);
function(a,b);

Page 109
printf(“a=%d b=%d after function call\n”,a,b);
getch();
}
void function(int x,int y) call by value function
{
x=x+x;
y=y+y;
}

Output:

The corresponding formal parameter represents a local variable in the called function.
The current value of the corresponding actual parameter becomes the initial value of the
formal parameter. The value of formal parameter may then change in the body of the
subprogram by assignment or input statements. This will not change the value of the actual
parameter.

CALL BY REFERENCE:
A parameter that receives the memory address of corresponding argument.
Example 2:C program to illustrate the function using call by reference mechanism.
#include<stdio.h>
#include<conio.h>
void main()
{
void function(int *,int *);
int a=20,b=30;
clrscr();
printf(“a=%d b=%d before function call \n”,a,b);
function(&a,&b);
printf(“a=%d b=%d after function call\n”,a,b);
getch();
}
void function(int *x,int *y) call by reference function

Page 110
{
*x=*x+*x;
*y=*y+*y;
}
Output:

Example 3: C program to exchange the contents of the two variables using call by value and
call by reference.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap_val(int,int);
void swap_ref(int *,int *);
clrscr();
printf(“Enter two numbers\n”);
scanf(“%d%d”,&a,&b);
printf(“a=%d b=%d before function call\n”,a,b);
swap_val(a,b);
printf(“a=%d b=%d after function call using call by value\n”,a,b);
swap_ref(&a,&b);
printf(“a=%d b=%d after function call using call by reference\n”,a,b);
getch();
}
void swap_val(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;

Page 111
}
void swap_ref(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Output:

POINTER AND ARRAYS:

An array is a name given to a set of memory locations of the same type of data. It is a
very popular data type especially when we are working with large amounts of data.

Let us note a few points about pointers:

1. called by the same name and holding the same type of data and accessed with the help
of a subscript.
2. Before using an array it must be declared.
Example: char name[20];
3. The accessing of elements at any location is done with the help of the name of the
array.
Loc[i] =Address of first location + Subscript value * size of data type

Program:To display the contents of an array using name and also a pointer.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[100];
int i,n;

Page 112
int *ptr;
clrscr();
printf(“Enter number of elements in the array\n”);
scanf(“%d”,&n);
printf(“Enter array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
ptr=a;
printf(“\n Array elements are\n”);
for(i=0;i<n;i++)
{
printf(“value using array name a[%d]=%d”,i,a[i]);
printf(“value using pointer a[%d]=%d\n”,i,*(ptr+i));
}
getch();
}
Output:

POINTERS AND STRINGS:


Similar to the way where a large amount of data is stored in an integer array, a
group of characters should be stored in a character array. Character arrays are also known as
strings. A string constant is a one-dimensional character array where the last element is
terminated by „\0‟.
Program:A C program to find the length of a string using pointer variable.
#include<stdio.h>
#include<conio.h>

Page 113
void main()
{
char str[10];
char *sptr;
int length;
clrscr();
printf(“enter a string”);
scanf(“%s”,str);
sptr=str;
printf(“\nEntered string”);
while(*sptr!=‟\0‟)
{
printf(“%c”,*sptr);
sptr++;
}
length=sptr-str;
printf(“\nLength of the string=%d”,length);
getch();
}
Output:

ARRAY OF POINTERS:
An array of pointer would be nothing but a collection of address. The address present
in the array of pointers can be or can be addresses of isolated variables or addresses of array
elements or any other address.
Program:A C program to illustrate an array of pointers.
#include<stdio.h>
#include<conio.h>
void main()
{
int *arrptr[5];

Page 114
int i=80,j=34,k=97;
int l=76,m=56,n;
clrscr();
arrptr[0]=&i;
arrptr[1]=&j;
arrptr[2]=&k;
arrptr[3]=&l;
arrptr[4]=&m;
for(n=0;n<=4;n++)
printf(“value %d stored at address %u\n”,*(arrptr[n]),arrptr[n]);
getch();
}
Output:

Page 115
FILES
The unit of storage in a computer system is a file. A file is normally used to store
logically related information.
OR
A named area in secondary storage that is used to hold a collection of data.

Hard Disk

File

File processing activity may include the following:

1. Creating a file.
2. Adding records or data to the file.
3. Modifying the contents of the existing data or records.
4. Merging two files or combining records of two or more files into one.
5. Deleting unwanted records for a file.
6. Generate reports or required outputs from a file.

FILE PROCESSING:

Syntax: FILE *file_pointer;

The keyword FILEtells the system that we are pointing to a file structure. The
definition for the file structure is present in the header file stdio.h.

File pointer: A file pointer is a pointer to a structure containing information about the
associated files such as the file descriptor, pointer to buffer, next character position, number
of characters left in the buffer and flag describing modes of operation.

Syntax: file_pointer = fopen(file name, mode);

Page 116
MODE ACTION
w Create a new file for writing
r Open an existing file for reading
a Open a file for appending data or create a new file
w+ Create a new file for read or write
r+ Open an existing file for read or write
a+ Open for read or write or create a new file
wb Create a new file for writing in binary form
rb Open binary file for read in binary form
ab Open a binary file for read or write or create new file
w+t Create a text file for read or write
r+t Open a text file for read or write
a+t Open or create a text file for read or write
wt Create a text file for writing
rt Open text file for read
at Open a file to append to text file or create new file

Program 1:Program to create a text file.


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
FILE *fp;
fp=fopen(“input.txt”,”w”);
if(fp==NULL)
{
printf(“Error in Opening the file”);
exit(1);
}
ch=getche();

Page 117
while(ch!=‟\r‟)
{
putc(ch,fp);
ch=getche();
}
fclose(fp);
}
Output:

In the above program the function fopen() is used to open the file “input.txt” in the
write mode. If there is any problem in opening of the file a NULL value will be returned to
the file pointer. If a NULL value is returned then an error message is displayed.

Program 2: A C program to write data in a file until enter key is pressed.

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“input.txt”,”w”);
if(fp==NULL)
{
printf(“Error in Opening the file”);
exit(1);
}
ch=getc(stdin);
while(ch!=‟\n‟)
{
putc(ch,fp);
ch=getc(stdin);
}

Page 118
fclose(stdin);
fclose(fp);
}
The standard input file pointer “stdin” is used. The “stdin” directly interacts with the
keyboard buffer. When we open a file, a buffer is created in the system memory and data is
transferred from or into the file with the help of it. When we close the file, the remaining data
contained in this buffer are transferred to the opened file in the storage device. If we do not
close the file then there may be some loss of data. However this may not happen every time.

Program 3: A C program to read characters from a data file the keyboard and display it on
the screen.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
FILE *fp;
fp=fopen(“input.txt”,”r”);
if(fp==NULL)
{
printf(“Error in Opening File”);
exit(1);
}
printf(“\n”);
ch=getc(fp);
while(!feof(fp))
{
putch(ch);
ch=getc(fp);
}
fclose(fp);

Page 119
}

Output:

Program 4: A C program to copy the contents of a file to another backup file.


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
void main()
{
char infile[13],outfile[13];
char ch;
FILE *in_file, *out_file;
clrscr();
printf(“Enter the source File\n”);
gets(infile);
in_file=fopen(infile,”r”);
if(in_file==NULL)
{
printf(“Error in opening the file”);
exit(1);
}
strcpy(outfile,infile);
strcat(outfile,”.BAK”);
out_file=fopen(outfile,”w”);
if(out_file==NULL)
{
printf(“Error in opening the file”);
exit(1);
}
ch=getc(in_file);

Page 120
while(!feof(in_file))
{
putc(ch,out_file);
ch=getc(in_file);
}
printf(“File successfully Copied\n”);
fclose(in_file);
fclose(out_file);
}
Output:
Enter the source file
Input.txt
File successfully copied

FORMATTED FILE OPERATION


Syntax:
File-operation-function(file pointer, data formats, list of variables);
Some of the functions which help in performing format based operations are:
fscanf()- function to accept formatted data from a file
fprintf()- function to write formatted data to a file.
The data formats that can be used with the file pointers is given in the table below.
DATA FORMATS ACTION
%d Integer Number
%f Floating point number
%c Character data
%s String data
%x Hexadecimal number
%o Octal number
%ud Unsigned integer
%uf Unsigned floating point number
%uc Unsigned character
%e Scientific notation of number
%ld Long integer

. Page 121
%lf Double float point number
%i Integer number

Program 6: To show the use of formatted data in files.


#include<stdio.h>
#include<conio.h>
#include<io.h>
void main()
{
char name[30];
char class[10];
float fees;
FILE *fp;
fp=fopen(“Student”,”wb+”);
if(fp==NULL)
{
printf(“\nStudent”);
printf(“Error in opening file”);
exit(1);
}
printf(“Enter Name\n”);
scanf(“%s”,name);
printf(“Enter class studying\n”);
scanf(“%s”,class);
printf(“Enter fees paid\n”);
scanf(“%f”,&fees);
fprintf(fp,”%s”,name);
fprintf(fp,”%s”,class);
fprintf(fp,”%f”,fees);
fflush(fp);
fclose(fp);
}
Output:

. Page 122
Enter Name
Akash
Enter class studying
PUC
Enter fees paid
21500.00

Program 7: A C program to create a student database file.

#include<stdio.h>
#include<conio.h>
#include<io.h>
#include<string.h>
#include<process.h>
void main()
{
char file[13];
int count=0;
char ch;
char name[20];
char class[10];
float fees;
FILE *fp;
printf(“Enter the name of the file\n”);
scanf(“%s”,file);
fp=fopen(file,”w”);
if(fp==NULL)
{
printf(“%s\n”,file)
printf(“Error in opening file”);
exit(1);
}
printf(“Enter choice(Y/N)\n”);

Page 123
ch=getche();
ch=toupper(ch);
while(ch==‟Y‟)
{
count++;
printf(“Enter Name\n”);
gets(name);
printf(“enter class studying\n”);
gets(class);
printf(“Enter fees paid\n”);
scanf(“%f”,&fees);
fprintf(fp,”\n%d”,count);
fprintf(fp,”\n%s”,name);
fprintf(fp,”\n%s”,class);
fprintf(fp,”\n%f”,fees);
printf(“Enter Choice (Y/N)\n”);
ch=getche();
ch=toupper(ch);
}
fclose(fp);
printf(“File successfully written\n”);
}
Output:
Enter the name of the file
Student
Enter Choice(Y/N)
Y
Enter name
Ranjith
Enter class studying
PUC
Enter fees paid
22000.00

Page 124
Enter Choice(Y/N)
N
File successfully written

Program 8 : To display the contents of a student database file.


#include<stdio.h>
#include<conio.h>
#include<io.h>
#include<string.h>
#include<process.h>
void main()
{
char file[13];
int count=0;
char ch;
char name[20];
char class[10];
float fees;
FILE *fp;
printf(“Enter the name of the file\n”);
scanf(“%s”,file);
fp=fopen(file,”r”);
if(fp==NULL)
{
printf(“%s\n”,file)
printf(“Error in opening file”);
exit(1);
}
while(!feof(fp))
{
fscanf(fp,”%d”,&count);
fscanf(fp,”%s”,name);
fscanf(fp,”%s”,class);

Page 125
fscanf(fp,”%f”,&fees);
printf(fp,”Record No=%d”,count);
printf(fp,”Name=%s”,name);
printf(fp,”Class=%s”,class);
printf(fp,”Fees=%f”,&fees);
}
printf(“File Successfully read\n”);
fclose(fp);
}
Output:
Enter the name of the file
Student
Record No=1
Name=Ranjith
Class=PUC
Fees=22000.00
Record No=2
Name=Akash
Class=PUC
Fees=23000.00
File successfully read

FILES AND STRUCTURES


fread() – To read a structure from a data file
fwrite() – To write a structure to a data file
with the help of these functions, we can perform read or write operations with
files for one record at a time, not a single field of the record.

Syntax:
fread(&name of struct, sizeof(struct struct_name),1,file pointer);

Page 126
Example:
struct student
{
char name[20];
char class[10];
float fees;
};
struct student s;
FILE *fp;
fread(&s, sizeof(struct student),1,fp);
Program 9 : A C program to show the use of freadfunction
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
char class[10];
float fees;
};
void main()
{
struct student s;
char file[13];
FILE *fp;
clrscr();
printf(“Enter the filename\n”);
scanf(“%s”,file);
fp=fopen(file,”rb+”);
if(fp==NULL)
{
printf(“File %s\n”,file);
printf(“Error in opening file”);
exit(1);

Page 127
}
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
printf(“Name:%s\n”,s.name);
printf(“Class:%s\n”,s.class);
printf(“Fees:%f\n”,s.fees);
fread(&s,sizeof(s),1,fp);
printf(“Press any key”);
getch();
}
fclose(fp);
}
Output:
Enter the filename
Student
Name: Mohan
Class: PUC
Fees: 23000.00
Press any key

Let us see the use of the fwrite function. The syntax of usage of this function is:
Syntax:
fwrite(&name of struct, sizeof(struct struct_name),1,file pointer);
Example:
struct employee
{
char name[20];
char desg[10];
float sal;
}
struct employee e;

Page 128
FILE *fp;
fwrite(&e,sizeof(struct employee),1,fp);

Program 10: A C program to show the use of fwrite function.


#include<stdio.h>
#include<conio.h>
#include<string.h>
struct employee
{
char name[20];
char desg[10];
float sal;
};
void main()
{
struct employee e;
char file[13];
FILE *fp;
char ch;
printf(“Enter the filename\n”);
scanf(“%s”,file);
fp=fopen(file,”wb+”);
if(fp==NULL)
{
printf(“File %s\n”,file);
printf(“Error in opening file”);
exit(1);
}
printf(“Enter Choice(Y/N)\n”);
ch=getche();
ch=toupper(ch);
while(ch==‟Y‟)
{

Page 129
printf(“Enter Name\n”);
gets(e.name);
printf(“Enter designation\n”);
gets(e.class);
printf(“Enter salary\n”);
scanf(“%f”,&e.sal);
fwrite(&e,sizeof(e),1,fp);
clrscr();
printf(“Enter Choice(Y/N)\n”);
ch=getche();
ch=toupper(ch);
}
fclose(fp);
printf(“File successfully written\n”);
}
Output:
Enter the filename
Employee
Enter Choice(Y/N)
Y
Enter Name
Pooja
Enter designation
CEO
Enter salary
15000.00

FILES AND STRINGS


fgets() – read a string of a certain size to a string variable
fputs() – writes a string of a certain size to a data file
The fgets() is used to read a string constant of a certain size to a string
variable from the data file. The syntax of the fgets() function is as follows

Syntax: fgets(string variable, size , file pointer);

Page 130
Example: fgets(str, size, fp);
Program 11: A C program to show the use of fgets function.
#include<stdio.h>
#include<conio.h>
void main()
{
char file[13];
FILE *fp;
char str[100];
scanf(“%s”,file);
fp=fopen(file,”rb+”);
if(fp==NULL)
{
printf(“File %s\n”,file);
printf(“Error in opening file”);
exit(1);
}
while(!feof(fp))
{
if(fgets(str,100,fp))
printf(“%s\n”,str);
}
fclose(fp);
}
Output:
Enter the filename
Family
Akash
Ranjith

The fputs() is used to write a string constant of a certain size to a data file.
The syntax of the fputs() function is as follows
fputs(string variable, size, file pointer);

Page 131
For Example:
fputs(str, size, fp);
Program 12: A C program to show the use of fputs function.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char file[13];
FILE *fp;
char str[100],ch;
printf(“Enter the file name\n”);
scanf(“%s”,file);
fp=fopen(file,”wb+”);
if(fp==NULL)
{
printf(“File %s\n”,file);
printf(“Error in opening file”);
exit(1);
}
printf(“Enter Choice(Y/N)\n”);
ch=getche();
ch=toupper(ch);
while(ch==‟Y‟)
{
printf(“Enter Name\n”);
gets(str);
fputs(str,100,fp);
clrscr();
printf(“Enter Choice(Y/N)\n”);
ch=getche();
ch=toupper(ch);
}

Page 132
fclose(fp);
}
Output:
Enter the filename
Family
Enter Choice(Y/N)
Y
Enter Name
Bindu
Enter Choice(Y/N)
Y
Ashwini
Enter Choice(Y/N)
N

Page 133

You might also like