Computer Concepts and C Programming UNIT-1 Chapter-1:: System Unit (CPU) Screen
Computer Concepts and C Programming UNIT-1 Chapter-1:: System Unit (CPU) Screen
UNIT-1
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.
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.
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.
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.
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
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
Disadvantages
Advantages
Advantages
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.
Classification of Computers
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.
Memory Unit
Arithmetic Logic
Unit
Components of a Computer
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: -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.
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:
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.
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.
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.
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.
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
. 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.
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.
. 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.
Pre-processor directives
Global declarations;
Main ()
Declarations;
Statements;
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.
. 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.
Example:
#include<stdio.h>
#include<conio.h>
void main()
getch();
Output:
HELLO WORLD
Page 20
C PROGRAMMING PRELIMINARIES
CHARACTER SET:
Lowercase letters a to z
Digits 0 to 9
IDENTIFIERS:These are names given to program elements like variables, arrays, functions
and structures. Basically identifiers are the sequence of alphabets and digits.
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.
Rules for naming a variable – same as rules for forming an identifier name
. 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:
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
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.
. 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
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.
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:
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
et 1. scanf() 5. gets()
2. printf() 6. puts()
3. getchar() 7. getch()
4. putchar() 8. getche()
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.
Example:- scanf(“%d%d”,&a,&b);
scanf(“%c%d%f”,&ch,&a,&r);
FORMATTED OUTPUT:
C provides the printf() function to display the data on the monitor.
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.
Syntax: putchar(ch_var);
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.
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
. 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;
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.
. Page 37
~ Tilde 1‟s complement
<< Double less than Left shifting of bits
>> Double greater than Right shifting of bits
. 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
Y= 1 0 0 0 0 0 0 0
g. 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
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
Page 41
Logical Expression: The expression that result into 1 (true) or 0 (false) are called logical
expressions they use logical operators.
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:
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;
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.
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;
. 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:
}
Statement_n+1;
. 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;
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.
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.
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};
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:
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};
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:
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];
C O M P U T E R \0
name [0] [1] [2] [3] [4] [5] [6] [7] [8]
OR
READING A STRING:
scanf (“%s”,name);
There is a problem with scanf () function while reading a string data. Consider the
following program.
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.
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
Note:To use all the string operations in C you must include string.h library header file in the
program
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);
#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:
#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));
#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:
#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
#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:
#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:
#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:
#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);
#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.
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]
. Page 80
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.
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.
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.
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.
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:
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:
. Page 89
void main()
{
void Our_address();
clrscr();
Our_address();
getch();
}
void Our_address()
{
printf(“\n NIE FGC”);
printf(“\n Mysore”);
}
Output:
. 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:
. 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:
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:
Data_type member n;
}struct_var_name;
Example: struct item
int rno[5]; {
int rno;
char name[50];
}itm;
. 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:
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;
Structure members can be accessed using member operator '.' . It is also called as 'dot
operator' or 'period operator'.
Syntax: structure_variable_name.member_name
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:
Page 97
Way 1: Declare and Initialize.
struct student
{
char name[20];
int roll;
Float marks;
}std1={“prakash”,67,78.5};
struct student
{
char name[20];
int roll;
float marks;
}
std1={“prakash”,67,78.5};
std2={“ramesh”,75,86.4};
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
#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 :
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:
#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 :
#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 :
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:
data_type *var_name;
Example:
int *p;
char *ch;
double *dp;
float *fp;
. Page 104
clrscr();
ptr=#
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=#
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:
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:
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:
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.
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:
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
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:
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.
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
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.
#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:
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
. Page 121
%lf Double float point number
%i Integer number
. Page 122
Enter Name
Akash
Enter class studying
PUC
Enter fees paid
21500.00
#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
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
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);
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
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