Uploaded by Mahendhar raj

C language full

advertisement
Notes Prepared For
B.Sc Computer Science
I Year
Under CBCS Sytem
Which Effects From 2019-20
PROGRAMMING IN C
(SEMESTER-I)
With
PRACTICAL SOLUTIONS
BY
MOHAMMED WASEEM RAZA
Assistant Professor in Computers.
Contact: +91-739-668-5825
Email: waseemraza07@gmail.com
https://www.sucomputersforum.com
Downloaded from:
https://www.sucomputersforum.com
B.Sc. Computer Science
Programming in C (Semester-1)
Syllabus:
2
UNIT—I
Computer Fundamentals: Introduction of Computers, Classification of Computers,
Anatomy of a Computer, Memory Hierarchy, Introduction to OS, Operational Overview of a
CPU. Program Fundamentals: Generation and Classification of Programming
Languages, Compiling, Interpreting, Loading, Linking of a Program, Developing Program,
Software Development.
Algorithms: Definitions, Different Ways of Stating Algorithms (Step-form, Pseudo-code,
Flowchart), Strategy for Designing Algorithms, Structured Programming Concept.
Basics of C: Overview of C, Developing Programs in C, Parts of Simple C Program, Structure of
a C Program, Comments, Program Statements, C Tokens, Keywords, Identifiers, Data Types,
Variables, Constants, Operators and Expressions, Expression Evaluation—precedence and
associativity, Type Conversions.
UNIT—II
Input-Output: Non-formatted and Formatted Input and Output Functions, Escape
Sequences, Control Statements: Selection Statements — if if-else, nested if, nested if-else,
comma operator, conditional operator, switch; Iterative Statements: while, for, do-while;
Special Control Statement—goto, break, continue, return, exit.
Arrays and Strings: One-dimensional Arrays, Character Arrays, Functions from ctype.h,
string.h, Multidimensional Arrays.
UNIT—III
Functions: Concept of Function, Using Functions, Call-by-Value Vs Call-by-reference, Passing
Arrays to Functions, Score of Variables, Storage Classes, lane Functions, and Recursion.
Pointers: Introduction, Address of Operator (&), Pointer, Uses of Pointers, Arrays and Pointers,
Pointers and Strings, Pointers to Pointers, Array of Pointers, Pointer to Array, Dynamic Memory
Allocation.
UNIT — IV
User-defined Data Types: Declaring a Structure (Union) and its members, Initialization
Structure (Union), Accessing members of a Structure (Union), Array of Structures (Union),
Structures verses Unions, Enumeration Types.
Files: Introduction, Using Files in C, Working with Text Files, Working with Binary Files, Files of
Records, Random Access to Files of Records, Other File Management Functions.
Practical Question bank
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Programming in C - Lab
3
Practical: 3 Hrs/Week (1 Credits)
1. Write a program to Find the largest two (three) numbers using if and conditional operator
2. Write a program to print the reverse of a given number.
3. Write a program to Print the prime number from 2 to n where n is given by user.
4. Write a program to find the roots of a quadratic equation using switch statement. print a triangle
5. Write a program to stars as follows (take number of lines from user):
*
***
*****
*******
*********
6. Write a program to find largest and smallest elements in a given list of numbers.
7. Write a program to find the product of two matrices
8. Write a program to find the GCD of two numbers using iteration and recursion
9. Write a program to illustrate use of storage classes.
10. Write a program to demonstrate the call by value and the call by reference concepts
11. Write a program that prints a table indicating the number of occurrences of each alphabet in the
text entered as command line arguments.
12. Write a program to illustrate use of data type enum.
13. Write a program to demonstrate use of string functions string.h header file.
14. Write a program that opens a file and counts the number of characters in a file.
15. Write a program to create a structure Student containing fields for Roll No., Name, Class, Year
and Total Marks. Create 10 students and store them in a file.
16. Write a program drat opens an existing text file and copies it to a new text file with all lowercase
letters changed to capital letters and all other characters unchanged.
Note:
1. Write the Pseudo Code and draw Flow Chart for the above programs.
2. Recommended to use Open Source Software: GCC on Linux; DevC4-1- (or) Code Blocks on
Windows 10.
UNIT—I
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Computer Fundamentals: Introduction of Computers, Classification of Computers,
Anatomy of a Computer, Memory Hierarchy, Introduction to OS, Operational Overview of a
CPU.
Program Fundamentals: Generation and Classification of Programming Languages,
Compiling, Interpreting, Loading, Linking of a Program, Developing Program, Software
Development.
Algorithms: Definitions, Different Ways of Stating Algorithms (Step-form, Pseudo-code,
Flowchart), Strategy for Designing Algorithms, Structured Programming Concept.
Basics of C: Overview of C, Developing Programs in C, Parts of Simple C Program, Structure of
a C Program, Comments, Program Statements, C Tokens, Keywords, Identifiers, Data Types,
Variables, Constants, Operators and Expressions, Expression Evaluation—precedence and
associativity, Type Conversions.
4
A computer is defines as an electronic device it takes input from the users, it stores, process the
data and generates the required output as per the instructions given by the user.
A set of instructions that directs a computer to execute a particular task is called a program. To
direct the program the computer consists of three functions.
a) Input functions
b) Processing data
c) Output functions
Input functions help the user to enter the data. Processing helps the user to store the data solves the
numerical operations, arithmetic operators etc. To produce the desire results according to user’s
requirement.
The processed data is sent to the output devices such as monitor which is connected to the
computer.
Characteristics of a computer:The characteristics of a computer are given below:1) Accuracy: - The computer system always produces accurate results with valid data and
instructions. All the errors the computer produces in the output are due to the negligence of the user.
Errors also occur due to the entering of in accurate data and in-proper procedures made by the users.
2) Speed: - Computers can calculate at very high speed. Computers can process million of instructions
per second. The speed of computers is measured in terms of micro seconds (10 -6) nano seconds (10-9)
and even Pico seconds (10-12).
3) Versatility: - Computers are versatile machines. They can do variety of jobs or different types of
jobs variety of jobs or different types of jobs depending upon the hardware capabilities. Computers
can perform various activities ranging from simple calculations as well as complex simulations.
Computers help the user to edit a document a website and printing the text.
4) Storage capacity: - Computers have large amount of storage capacity in the memory. The
computers can store large amount of data and information on the secondary storage devices such as
hard disk and magnetic disk.
The information store in the memory can be retrieved (recall) for the future purpose.
5) Diligence: - Diligence means being constant. Human beings suffer from weakness and tiredness.
Lock of concentration, but computers do not suffer from fatigue and lack of concentration. They can
work for many hours and can perform number of calculations without the time limit.
Block diagram or Logical Architecture of Computer
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
5
- A computer is an electronic device which consists of different elements.
1) Hardware
2) Central processing unit (C.P.U.)
3) Input devices
4) Output devices
(1) Hardware: - Hardware is a set of internal devices as well as external devices which are connected
to the computer. The computer hardware has many parts which are mainly divided into four
categories.
A) Processor
B) Memory
C) Input/output devices
D) Storage devices
A) Processor: - The complex procedure that transforms the raw data into useful information is called
as processing.
Raw data → Processing → Information
Processor is like the brain of the computer which organizes and carries out instructions processor
usually consists of micro processor (MP). The micro processor’s are made up and silicon metal or
many other material with many tiny electronic circuits. The microprocessor is plugged into the circuit
board. This circuit board to which the microprocessor is connected called as mother board.
B) Memory: - Memory is computers electronic scratch pad programs are loaded into the memory and
run from the memory. The most common type of memory is Random Access Memory (RAM). The
memory is divided in the form of bytes. A byte is the amount of memory taken to store a single
character examples of bytes are given below.
 1 byte
= 8 bits
 1 kilobyte = 1024 bytes
 1 megabyte = 1024 kilobytes
 1 gigabyte = 1024 megabytes
 1 Terabyte = 1024 Gigabytes
C) Input and Output devices:- Input devices accepts the data from the user. The input devices are:(I) Keyboard
(II) Mouse
(III) Joystick
(IV) Light pen
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
6
(v) Track ball
(VI) Track pad
(VII) Scanners etc…
The output device displays the processed data or information to the users. The most common output
devices are monitor, printer and plotter.
D) Storage device: - Computer needs a place to store the data and program files whenever they are
not in use. The storage devices are made up of electorate cabinet. RAM is called as electronic work
table. For a single operation computer locates then with file cabinet and puts a copy on the work table.
The most common storage devices are magnetic and optical storage Devices. The storage devices are
round flat object that spins (rotate) a rounds its centre. The device that holds the disk is called as disk
drive. The examples of storage devices are floppy disk, hard disk, compact disk, and etc…
2) Central Processing Unit: - C.P.U. is called as brain of the computer. Data is manipulated in C.P.U.
The entire C.P.U. is contained on a tiny chip called as microprocessor C.P.U. is mainly divided into
three parts.
a) Control Unit
b) Memory Unit
c) Arithmetic Logical Unit
a) Control Unit: - The control unit manages all the computer resources. It is the logical hub (place) of
the computer. The instructions of the C.P.U. for carrying out the commands are built in to the C.P.U.
These instructions or set of instructions contained all the operations that C.P.U. can perform. Each
instruction is expressed in micro-code. There are series of basic directions that tells the C.P.U. to
execute complex operations. These operations are done by the computers at high speed translating
millions of instructions every second.
(b) Memory Unit: - Memory consists of chips which are located on the mother board. The small
electronic memory allows the C.P.U. to store and retrieve (recall) the data very quickly. There are two
type of built – in memory. They are permanent memory (ROM) and temporary memory (RAM).
(c) Arithmetic logical unit: - It performs two types of operations namely. Arithmetic and logical
operations. The following arithmetic operations are: + = Addition
 - = Subtraction
 * = Multiplication
 / = Division
The following logical operators are: && = And
 : : = Or
 ! = Not
INPUT DEVICES:
The most common input devices are:1) Keyboard: - Key board is the primary input device for entering the text is the primary input
device for entering the text and numbers. It is a simple device consisting of 101 Keys. The keyboards
for personal computers com in number of styles and also in different size and shape. The most
common keyboard layout used today was designed by IBM (International business machines). The
keyboard keys are arranged in 5 groups.
a) Alphanumeric keys: - The parts of the keyboard that look like a type writer machine are arranged
in a common manner. This arrangement is called “QWERTY” layout because the first 6 keys on the top
of letters are Q, W, E, R, T, and Y…
b) Modifier keys: - This key is used in combination with other keys. The modifier keys are Shift, Alt,
(Alternate), Ctrl (Control).
(c) Numeric pad: - This key is located on the right side of the keyboard. It looks like a adding machine
(calculator) with 10 digits and the mathematical operators like addition (+), subtraction (-),
multiplication (*), division (/),
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
7
(d) Function keys: - The functions are usually arranged on the top of the row of the keyboard. The
function keys are from F1 – F12. They allow the user to give the computer commands without having
to type long strings of the characters. The most common function key F1 is used to help in all the
programmes.
(e) Cursor movement keys:- This are the set of four keys which allows the user to change the
position of the cursor on the screen. The cursor movement keys of the cursor on the screen. The
cursor movement keys are right, left, top, and bottom.
↑
←
→
↓
2) Mouse: - A mouse is an input device that roles around a flat surface or on a desk and controls the
pointer. The pointer is on-screen object usually an arrow (↑) mark that is used to select the text,
access menus, moves files and interacts with other program files, or data that appear on the screen. A
mouse also allows the user to create graphic representations, drawing lines, curves and free handshapes. Clicking, double clicking, right clicking and dragging are the four major operations performed
with the help of mouse.
3) Track ball: - A track ball is a pointing device that works like a upside down mouse. The move the
cursor around the screen the user rolls the ball with the help of a thumb. The track balls such as
“Trackman” from the Logitech Company are not even attached to the computer. They act like a remote
controller for the pointer.
4) Track pad: - The track pad is a stationary pointing device. The movement of a finger across a small
touch surface is translated in to cursor movement on the computer screen. The surface is just 1.5 to 2
inches square and it is well suitable for the laptop computers and note book computers.
5) Light pen: - The light pen is also called as stylus. Pen – based systems uses electronic pen as their
primary input device. Pen is used to write or select the objects on a special pad or directly on to the
screen. Pen is also used as a pointing device like a mouse to select commands.
6) Touch screen: - The touch screens allow the user to point directly at the computer screen usually
to select the menu of choices which are displayed on the screen. The touch screens uses sensors in the
screens are mostly used of a finger. Touch screens are mostly used in ATM banks, Railway reservation
counters etc…
7) Barcode readers: - The barcode readers convert the barcode image into a number. It enters the
number into the computer. Barcode readers are used in super markets, departmental stores etc…
8) Image scanner and optical character recognition: - Image scanners can convert any image into
electronic form by using shining light (laser) on to image and sensing (reading intensity of the light at
every point of reflection. A Software is used to translate the image into text is called as optical
character recognition. Two types of scanners are available they are hand held and flat bed…
9) Game controller: - A game controller is an input device because a computer game is a program.
Joystick is used to play the games on the computer.
10) Microphone and voice recognition: - Sound is mostly used in multimedia applications. A sound
card is used to translate the electronic signals from microform into a digital form. The computers can
understand, store and process the sound with the help of voice recognition software.
Output devices
The output devices of a computer are:a) Monitor
b) Printer
c) Plotter
d) speakers
e) projectors
a) Monitor: - Monitor is a common output device. There are two types of monitors available in the
market they are:Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
8
1) Cathode ray tube (CRT)
2) Flat panel display
1) Cathode ray tube (CRT):- CRT can be monochrome (single color) displaying only one color against
a contracting background. In the monitor there is a electronic gun which shoots a beam of electrons
through a magnetic oil. It is coated with phosphorous which glow when they are struck by electronic
beam. The smallest number of phosphorus allots is called a “pixel”.
2) Flat panel display: - These monitors provide brightest and clearest picture. These monitors are
relatively low cost in maintenance. These monitors are becoming more popular because of their lightweight and in small size. There are several types of flat panel monitors. The most common liquid
crystal display (LCD). The L.C.D. monitors create images with special kind of liquid crystal that is
normally transparent. These monitors became opaque when electricity passes through them. The
L.C.D. are also used in calculators and digital watches and so on.
b) Printer: - Printers used to take the output on to a paper. The printers are divided into two
categories they are:(I) Impact printers: - It creates an image by pressing an inked ribbon against the paper by using pins
hammer is embraced consist with the shape of alphanumeric character. The shape is transferred
through the inked-ribbon on to the paper, resulting in a printed character. The most common impact
printers are dot matrix printer, line printers and band printer.
(II) Non impact printers:- These printers creates an image by using tiny nozzles to spray droplets of
ink on to the page. The non impact printers are inkjet printers and loser printers.
A) Dot matrix printers:- A dot matrix printer creates an image by using a mechanism called as print
head which contains a cluster (matrix) of shot pins arranged in one or more columns on receiving the
instructions from the CPU the printer pushes out the pins in various combinations then the print head
creates alphanumeric character. The pins strike the ribbon and the matrix is pressed onto a piece of
paper. When a single pin strikes the ribbon a single dot of ink is printed printer. The lowest resolution
of dot matrix printer has 24 pins. The dot matrix printers are commonly used in date processing
departments which produce large reports. The dot matrix printers are measured in character per
second (CPS). The shortest printer creates 70 characters per second and the highest printer creates
more than 500 characters per second.
B) Inkjet printers: - These printers create on image directly on the paper by spraying ink through
tiny nozzles. The print resolution of inkjet printers are 360 dots per ink.
These printers are less expensive and they are available in color as well as black and white.
These printers have low operating costs and also offer good quality and speed.
C) Laser printer: - Laser printers are more expensive than inkjet printer because quality is higher
and faster. A separate CPU is built into the printer to process the data that it receives from the
computer and also to control the laser printer.
The laser printer consists of a toner which is composed of tiny particles of opposite charge. The
ink sticks to the drum in the places where the laser has charged with pressure and heat. There are two
types of laser printers. They are single column (B/W) and multiple colors. The Single color prints 4 to
16 pages per minute and they have the resolution from 1200 to 1800. The color printer works faster
than the B/W printer at least 4 times much faster.
C) Plotter: - A plotter is a special kind of printer, which produces large drawings or images. It uses a
robotic arm to draw the images on the paper. The plotters are used to take the printer of large images
such as banners, wall posters and flex-boards etc…
d) Speakers:
Speakers are another type of output device, which allows you to listen to voice like music, and
conversation with people.
e) Projectors
A projector is an output device that can take images generated by a computer or Blu-ray
player and reproduce them by projection onto a screen, wall, or another surface. In most cases, the
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
9
surface projected onto is large, flat, and lightly colored. For example, you could use a projector to
show a presentation on a large screen so that everyone in the room can see it.
STORAGE DEVICES
The two main categories of storage devices are:(I) Magnetic storage devices.
(II) Optical storage devices.
(I) Magnetic storage devices: - The various types of magnetic storage devices are :A) Floppy disk
B) Hard disk
C) Magnetic disk and
D) Magnetic tapes
A) Floppy disk: - The magnetic media that helps to store the data on the floppy or read the data from
the floppy disk. It is small & flexible device. These are single sided or double sided and depends upon
the storage of the data. The floppy disk is divided into tracks and sectors which helps the user to store
the data. The storage capacity of each sector is 512 bytes. Floppy disks are available in two sizes such
as 5 ¼. Inches and 3 ½. Inches. The 3 ½. Inches floppy can store 1.4 MB of data and extra high
density floppy can store 2.88 MB of data.
There is a hole at the centre of the floppy which allows the floppy to rotate. There is write
protected notch. This is used to protect the valuable information present on the floppy disk. It also
saves the data from accidental damage. The notch is covered with sticker, the data cannot be allowed
into the floppy as well as the data can’t be deleted from the floppy. It also protects the virus from
entering into the floppy disk. The main advantage of floppy disk is transferable from one place to
another place and the data can be written and also deleted number of times.
B) Hard disk: - Hard disk is a non-removable magnetic media which is used to store large amount of
data. A hard disk includes one or more plotters present on a central spindle. Each plotter is made up of
aluminum metal and coated with magnetic oxide. The area of hard disk is divided into number of
tracks and sectors. The hard disk found in most personal computers rotate(spin) between 3,600 rpm
to 7,200 rpm. (Revolution per minute). The latest hard disk will rotate at the speed of 10,000 rpm. The
storage capacity of the hard disk is measured in bytes and the latest hard disk in bytes and the latest
hard disk available in the market can store up to 320 GB of data.
C) Magnetic disk: - The magnetic disk is a flat circular disk made up of aluminum metal & coated with
magnetic material like ferric oxide or chromium oxide. The circular plate will rotate at constant speed.
We can store the data in a magnetic disk either single side or double side. The surface of the magnetic
disk is divided into number of sectors. The storage capacity of a magnetic disk is around 100 MB to
250 MB.
D) Magnetic tapes: - The magnetic tape devices can provide only serial access and recording medium
in a plastic tape coated with magnetic material on one side. The recording can be done only on coated
side. The width of the tape is 1.27 cms and its length is 731.5 mts and the diameter of the tape is 25.4
mts. There is a write protected ring at the backside of the tape. A small portion of 3 to 5 mts of the
tape because we can’t record the information in that area. The reading or writing of information is
done through a mechanism called as ‘caps tom’ There are rollers present in caps tom’s which rotate at
constant speed. The storage capacity of magnetic tapes ranges from 650 MB to 700 MB of storage
area.
II) Optical storage device: - The most popular alternative devices available are optical storage
devices. The most widely used optical storage devices are compact disk (CD) the different types of
compact disk are:A). CD-Rom
B). CD-Readable
C). CD-Rewritable
D). DVD-Rom
E). Photo-CD
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
10
A). CD-Rom:- CD- Rom stands for compact disk read only memory. It is used to listen the music as
well as read the data which is present in the CD. Laser beam is used to read the data. Data is present in
O’s and I’s. A circular spot from the laser beam to the sensor is represented as ‘1’, and the ray which is
reflecting back to the sensor is represented as O’. The CD-Rom reads the data at the rate of 5 to 15 MB
per minute. The storage capacity of a CD-Rom is around 650 MB to 700 MB.
B). CD-Readable/Recordable: - CD-R stands for compact disk recordable memory. It is used to
record the data. CD-R drove allows the user to create our own CD-R disk that can read to any CD-Rom
drive after the information have been written on a CD, the information cannot be changed nor deleted.
The storage capacity of CD-R is 650 MB to 700 MB.
C) CD-Rewritable: - CD R/W stands for compact disk rewritable. The user can write the data or store
the data number of times. The data can be a text or music or graphics etc; the storage capacity of CDR/W is around 650 MB to 700 MB.
D) DVD-Rom: - DVD-Rom stands for digital video disk read only memory. It is a high density medium
and it is capable of storing a fuel length movie on a single disk. DVD-Rom also looks like a CD-Rom. We
can also store the data on one side or two sides. Each side of a standard DVD-Rom can store the data
up to 10 GB and on two sides. It can store the data up to 20 GB.
E) Photo-CD: - A photo-CD is popular form of recordable CD which is developed by Kodak Company
for storing the photographic images on a CD. Many film developing industries user the photo-CD to
store the photos.
TYPES OF COMPUTERS.
The computers are broadly classified into 4 categories based on their size and type:
 Microcomputers
 Minicomputers
 Mainframe computers
 Supercomputer.
MICROCOMPUTERS
Microcomputers are small, low-cost and single-user digital
computers. They consist of CPU, input unit, output unit, storage unit and
the software Microcomputers include desktop computers, notebook
computers or laptops, tablet computer, handheld computer, smart
phones.
MINICOMPUTERS
Minicomputers are digital computers, generally used in multi-user
systems. They have high processing speed and high storage capacity than
the microcomputers. Minicomputers can support 4–200 users
simultaneously. The users can access the minicomputer through their PCs or terminal. They are used
for real-time applications in industries, research centers, etc.
PDP 11, IBM (8000 series) are some of the widely used minicomputers.
MAINFRAME COMPUTERS
Mainframe computers are multi-user, multi-programming and high performance computers.
They operate at a very high speed, have very large storage capacity and can handle the workload of
many users.
The user accesses the mainframe computer via a terminal. The terminal has the input and
output device only. Mainframe computers are used in organizations like banks or companies, where
many people require frequent access to the same data.
Some examples of mainframes are CDC 6600 and IBM ES000 series.
SUPER COMPUTERS
Supercomputers are the fastest and the most expensive machines. They have high processing
speed compared to other computers. The speed of a supercomputer is generally measured in FLOPS
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
11
(FLoating point Operations Per Second). Some of the faster supercomputers can perform trillions of
calculations per second. Supercomputers are built by interconnecting thousands of processors that
can work in parallel.
Supercomputers are used for highly calculation-intensive tasks, such as, weather forecasting, climate
research (global warming), molecular research, biological research, nuclear research and aircraft
design.
Some examples of supercomputers are IBM Roadrunner, IBM Blue gene and Intel ASCI red. PARAM
Limitations of a computer
Computers are man-made machines and it only do the things which have been given by the
user. Computers don’t have common sense. It will do whatever we have told to do. Computers will
never experience human emotions or concepts. Computers will only provide us the foundation and
the software to allow the user to enter then into its system. But they will not process like the humans
do. Its limitations depends on how much memory it have.They get replaced very easily because as the
years passes, the technology and components gets better.
Operating system
An operating system is defined as an interface between the user and computer system,
operating system provides the user with the tools or commands that enables us to interacts with the
computers. Processor Management: - An operating system assigns the processors to different tasks
being performed by the computers system.
Functions of Operating Systems
a) Memory Management :- The operating system allocates main memory and other storage
areas to the system programs as well as user programs and data.
b) Resource Management: - The operating system manages all the resources such as memory,
processor, input and output devices and secondary storage devices.
c) Operating system protects the hardware, software and data from improper use.
d) Operating system handles errors when they occur and if also corrects the errors where ever
possible.
e) If provides the instructions of display on screen elements with which we can interact. These
elements are known as uses interface.
f) Its loads the programs such as word processor excel spread sheet into the computer’s memory
so that we can use them.
Types of Operating system
These are mainly 5 types of operating system.
Batch Processing: - It is one of oldest method of running programs that are used by many data
processing centers for processing their jobs.
 In a batch mode. Each user prepares his program off-line and submits it to the computer center.
 A computer operator collects the programs from each user and stores programs one after the
other in the stacks.
 The operator loads this batch of program into the computer and at a time these are executed one
after the other.
 Finally these programs are retrieved for taking the print out or storing in another disk.
Multi-Processing:- Two or more Independent processors are linked together in a coordinated
system.
 Instructions from different and independent programs can be processed at the same time by
different processors.
 Multiprocessing is used for major control applications such as Airlines management or Rail & Road
control.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
12
Parallel Processing (Multitasking): Multitasking means simultaneous data processing tasks for increasing the computational speed of
a computer system.
 Instructions are parallel processed in the A.L.U (Arithmetic logical unit), the next instructions can
be read from the memory.
 The computer system may have two or more processors and they may have be able to execute two
or more instructions at the same time.
 The amount of hardware also increases in the parallel processing and it also increases the cost of
the computer system.
 Parallel processing is very useful in long range weather forecasting, petroleum explorations dical
diagnosis, aerodynamics, space flight simulation, image processing etc.
On-line Processing (Time – sharing):- This system performs random and rapid input of transaction
& provides immediate access to the records.
 Each user is provided direct access to the C.P.U. on time sharing basis.
 In the time sharing system, C.P.U. switches rapidly from once uses to another user, while it is
actually one computer shared by many processors and users.
 This type of processing makes it possible for several processors to share the resources of the
computer.
Real time Processing:- It is basically On-line systems with the time special micro processor.
 The response of the system to the enquiry itself is used to control the activity of the processor.
 Processing method is used to control the environment by receiving the data, processing them and
taking action or returning the results very quickly. Real time processing systems are useful in.
a) Airlines, to know the available seats.
b) Whole sale suppliers and manufacturers, to known the availability of stock level.
c) Real time systems usually operator in multiprogramming and multiprocessing these systems
increase both the availability & reliability of the system.
Types of Operating system based on Users:
Operating systems are mainly divided into two types.
They are: 1) Single user Operating system and 2) Multiuser Operating system.
1. Single user Operating system: - Dos is a best example of single operating system. It stands for
disk operating system.
*DOS is a single tasking operating system.
*DOS user character, user interface (CUI).
*DOS will not support many advanced features like networking.
2. Multi user Operating system: - Windows is one of the best examples of multi user operating
system.
*Windows is a multi tasking operating system.
*Windows uses Graphical user interface
(GUI)
*Windows operating system supports many advanced features such as networking
*Multitasking and multi programming.
Booting Process
The process of switching “ON” the computer is referred as the “Booting of the computer”. When
the user switches “ON” the computer, it gets ready for further action. It is also called as “to start up the
computer”.
The disk from which start up or Booting is done is called as bootable disk or start up disk or
system disk. The disk is used to load the set of programs from the ROM into RAM so that it creates on
environment for the execution of commands or further processing.
TYPES OF BOOTING: There are mainly two types:
1. Cold booting: when the personal computer is switched “ON” it loads the bootable Dos program
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
13
from the disk to the memory. This type of start up or booting of the P.C is slow process. It can be done
only from the “ON”/”OFF” switch button on the cabinet, so it is called as switch booting.
2. Hot booting: This is also called as warm booting. It is faster than cold booting.
If the computer hangs or halts or cashers due to some reason, it may be necessary to reset it present
on the C.P.U or by pressing Ctrl + Del keys from the keyboard. The computer gets restarted and the
booting of this type is called as hot booting and it is also called as resetting.
PROGRAMMING FUNDAMETALS
GENERATIONS AND CLASSIFICATIONS OF PROGRAMMING LANGUAGES
Programming languages have been developed over the year in a phased manner. Each phase of
developed has made the programming language more user-friendly, easier to use and more
powerful. Each phase of improved made in the development of the programming languages can be
referred to as a generation. The programming language in terms of their performance reliability
and robustness can be grouped into five different generations,
1.
2.
3.
4.
5.
First generation languages (1GL)
Second generation languages (2GL)
Third generation languages (3GL)
Fourth generation languages (4GL)
Fifth generation languages (5GL)
1. First Generation Language (Machine language)
The first generation programming language is also called low-level programming language because
they were used to program the computer system at a very low level of abstraction. i.e. at the
machine level. The machine language also referred to as the native language of the computer
system is the first generation programming language. In the machine language, a programmer only
deals with a binary number.
Advantages of first generation language
 They are translation free and can be directly executed by the computers.
 The programs written in these languages are executed very speedily and efficiently by the
CPU of the computer system.
 The programs written in these languages utilize the memory in an efficient manner
because it is possible to keep track of each bit of data.
2. Second Generation language (Assembly Language)
The second generation programming language also belongs to the category of low-levelprogramming language. The second generation language comprises assembly languages that use
the concept of mnemonics for the writing program. In the assembly language, symbolic names are
used to represent the opcode and the operand part of the instruction. Advantages of second
generation language
 It is easy to develop understand and modify the program developed in these languages
are compared to those developed in the first generation programming language.
 The programs written in these languages are less prone to errors and therefore can be
maintained with a great case.
3. Third Generation languages (High-Level Languages)
The third generation programming languages were designed to overcome the various limitations
of the first and second generation programming languages. The languages of the third and later
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
14
generation are considered as a high-level language because they enable the programmer to
concentrate only on the logic of the programs without considering the internal architecture of the
computer system.
Advantages of third generation programming language
 It is easy to develop, learn and understand the program.
 As the program written in these languages are less prone to errors they are easy to
maintain.
 The program written in these languages can be developed in very less time as
compared to the first and second generation language.
Examples: FORTRAN, ALGOL, COBOL, C++, C
4. Fourth generation language (Very High-level Languages)
The languages of this generation were considered as very high-level programming languages
required a lot of time and effort that affected the productivity of a programmer. The fourth
generation programming languages were designed and developed to reduce the time, cost and
effort needed to develop different types of software applications.
Advantages of fourth generation languages
 These programming languages allow the efficient use of data by implementing the various
database.
 They require less time, cost and effort to develop different types of software
applications.
 The program developed in these languages are highly portable as compared to the
programs developed in the languages of other generation.
Examples: SOL, CSS, coldfusion
5. Fifth generation language (Artificial Intelligence Language)
The programming languages of this generation mainly focus on constraint programming. The major
fields in which the fifth generation programming language are employed are Artificial Intelligence
and Artificial Neural Networks
Advantages of fifth generation languages
 These languages can be used to query the database in a fast and efficient manner.
 In this generation of language, the user can communicate with the computer system in a
simple and an easy manner.
Examples: mercury, prolog, OPS5
Compiler Interpreter, Linker and Loader
Regardless of what language you use, you eventually need to convert your program into a language
that the computer can understand
Two ways for doing that: compile the program or interpret the program
Compiler
A compiler is a computer program that translates a program in a source language into an
equivalent program in a target language.
or
Compilers: Translate a source (human-writable) program to an executable (machine- readable)
program Source code Compiler Executable Input data Executable Output data
Translate the entire program .
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
15
Convert the entire program to machine code, when the syntax errors are removed then converted
into the object code
Requires more main memory
Neither source nor the compiler are required for execution. Slow for debugging and testing.
Execution time is less. Security of source code .
Interpreter
Interpreter is a program that executes instructions written in a high-level language
or
Interpreters: Convert a source program and execute it at the same time. Translate the program line
by line. each time the program is executed ,every line is checked for syntax error & then converted to
equivalent machine code directly.
Requires less main memory
Source program and the interpreter are required for execution. Good
for fast debugging and testing
Execution time is more.
No Security of source code .
Linker
A program that takes as input the object files of one or more separately compiled program modules,
and links them together into a complete executable program, resolving reference from one module
to another.
Loader
A program that takes an input an executable program, loads it into main memory, and causes
execution to being by loading the correct starting address into the computer register. When the
program finished, control must somehow be returned to the operating system.
Object File: A single object file might contain machine code for only one procedure or a set of
procedures.
Executable File: An executable file must contain all the machine code needed for a particular
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
16
program; it must contain the address of the first instruction to be executed. SOFTWARE:
A collection of programs, libraries and collection of data together is referred as software. Software
can be System Software or Application Software
System Software
System Software includes the Operating System and all the utilities that enable the computer
to function. System software is a term referring to any computer software which manages and
controls the hardware so that application software can perform a task.
Examples: Operating System, Linker, Loader etc.,
Application Software
This is a general purpose program or acollection of program written by the user to solve a
particular problem. Application Software includes programs that do real work for user.
Examples: Student Management Software, Payroll System etc.,
WHAT IS AN ALGORITHM?
An algorithm is a part of the plan for the computer program. Infact
,an algorithm is an effective procedure for solving a problem in a finite number of steps.
It is effective,which means that an answer is found and it has a finite number of steps. A
well-designed algorithm will always provide an answer,it may not be the desired anwser but there
will be an answer. A well-designed algorithm is also guaranteed to terimnated.
An Algorithm can also be defined as "finite step by step list of well defined instructions
for solving a particular problem".
We always need to write algorithm for making different data structure operations. So lets
understand what algorithm consist of.
In first part of algorithm we tell the purpose of algorithm. It lists for variables and input data.
The second part is a list of steps.
The steps in algorithm are executed one after the other. Control may be transferred to step
'n' by using statement like 'Go to step n'. The exit and stop statements completes the
algorithm. The data may be assigned to variables by using read statement and it is displayed
by write or print statement.
Before any programmer start making something(own application),he/she should first make the
algorithm as it is related to many factors like process execution time, results, etc. GENERAL
SYNTAX OF ALGORITHM IS GIVEN BELOW:
ALGORITHM 1: Purpose of algorithm and input data and variables used. Start
Step 1: ………………………………………………………
Step 2: ………………………………………………………
:
:
Step n: …………………………………………………………….
Stop or Exit.
DIFFERENT WAYS OF STATING ALGORITHM.
An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which
specify a finite sequence of operations that provides the solution to a problem, or to a specific class
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
17
of problems for any allowable set of input quantities (if there are inputs).
In other word, an algorithm is a step-by-step procedure to solve a given problem
Algorithm may be represented in various ways. There are four ways of stating algorithms. There
steps are as follows: Step-form, Pseudo-code, Flow chart, Nassi–Shneiderman diagram (NSD)
STEP-FORM ALGORITHM:
In the step form representation, the procedure of solving a problem is stated with written
statements. Each statement solves a part of problem and these together completes the solution. The
step-form uses just normal language to define each procedure. Every statement, that defines an
action, is logically related o preceding statement.
PSEUDO-CODE:
The pseudo-code is a written form representation of the algorithm. However, it differs from
the step form as it uses a restricted vocabulary to define its action of solving the problem. One
problem with human language is that it can seem to be imprecise. But the pseudo-code, which is in
human language, tends towards more precision by using a limited vocabulary.
Example:
suppose you are required to design an algorithm for finding the average of six numbers. The
pseudocode will be as follows
Start
Get
the 6
numbers
a,b,c,d,e,f
Calculate
sum=a+b+c+d+e+f Average
= sum / 6
Output
the
average Stop
FLOW CHART AND NASSI-SCHNEIDERMAN:
Flow chart and Nassi-Schneiderman are graphically oriented representation forms. They use
symbols and language to represent sequence,decision and repetition actions.
Flowchart:
Flowcharting is a tool developed in the computer industry, for showing the steps involved in
a process. A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by
arrows - each shape represents a step in the process, and the arrows show the order in which they
occur. Flowcharting combines symbols and flowlines, to show figuratively the operation of an
algorithm.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
18
NASSI-SCHNEIDERMAN DIAGRAM
A Nassi–Shneiderman diagram (NSD) in computer programming is a graphical design
representation for structured programming?
These diagrams are also called structograms, as they show a program's structures. Following a topdown design, the problem at hand is reduced into smaller and smaller subproblems, until only simple
statements and control flow constructs remain. Nassi– Shneiderman diagrams reflect this top-down
decomposition in a straightforward way, using nested boxes to represent subproblems. Consistent with
the philosophy of structured programming, Nassi–Shneiderman diagrams have no representation for
a GOTO statement
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
PROCESS BLOCK
BRANCHING BLOCK
19
LOOPING BLOCK
KEY FEATURES OF AN ALGORITHM AND THE STEP-FORM.
Here is an example of an algorithm,for making a pot of tea.
1.
2.
3.
4.
5.
6.
7.
If the kettle does not contain water,then fill the kettle.
Plug the kettle into power point and switch it on.
If the teapot is not empty,then empty the teapot.
Place tea leaves in teapot.
If the water in the kettle is not boiling,then go to step 2.
Switch off the kettle.
Pour water from the kettle into the teapot.
It can be seen that the algorithm has a number of steps and that some steps(1,3 and 5) involve
decision making and one step(5 in case) involves repetition,in this case the process of waiting for
the kettle to boil.
Developing a program
A programmer has to go through the
following stages to develop a computer
program:
1. Defining and Analyzing The
Problem
2. Designing The Algorithm
3.
4.
5.
6.
Coding or Writing The Program
Test Execution
Debugging
Final Documentation
Step by step details of the program
development process follows:
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
20
Defining and Analyzing the Problem
In this step, a programmer studies the problem. He decides the best way to solve these problems.
Studying a problem is also necessary because it helps a programmer to decide about the following
things:
 The facts and figures which are necessary for developing the program.
 The way in which the program will be designed
 Also, the language in which the program will be most suitable.
 What is the desired output and in which form it is needed, etc
Designing The Algorithm
An algorithm is a sequence of steps that must be carried out before a programmer starts preparing
his program. The programmer designs an algorithm to help visual possible alternatives in a
program also.
Coding or Writing The Program
The next step after designing the algorithm is to write the program in a high-level language. This
process is known as coding.
Test Execution
The process of executing the program to find out errors or bugs is called test execution. It helps a
programmer to check the logic of the program. It also ensures that the program is error-free and
workable.
Debugging
Debugging is a process of detecting, locating and correcting the bugs in a program. It is performed
by running the program again and again.
Final Documentation
When the program is finalized, its documentation is prepared. Final documentation is provided to
the user. It guides the user how to use the program in the most efficient way.
Structured Programming
Structured Programming Approach, as the word suggests, can be defined as a programming
approach in which the program is made as a single structure. It means that the code will execute the
instruction by instruction one after the other. It doesn’t support the possibility of jumping from one
instruction to some other with the help of any statement like GOTO, etc. Therefore, the instructions
in this approach will be executed in a serial and structured manner. The languages that support
Structured programming approach are:
C,C++,Java,C#..etc
The structured program mainly consists of three types of elements:
 Selection Statements
 Sequence Statements
 Iteration Statements
The structured program consists of well structured and separated modules. But the entry and exit
in a Structured program is a single-time event. It means that the program uses single-entry and
single-exit elements. Therefore a structured program is well maintained, neat and clean program.
This is the reason why the Structured Programming Approach is well accepted in the programming
world.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
21
Advantages of Structured Programming Approach:
1.
2.
3.
4.
5.
6.
7.
Easier to read and understand
User Friendly
Easier to Maintain
Mainly problem based instead of being machine based
Development is easier as it requires less effort and time
Easier to Debug
Machine-Independent, mostly.
Disadvantages of Structured Programming Approach:
1. Since it is Machine-Independent, So it takes time to convert into machine code.
2. The converted machine code is not the same as for assembly language.
3. The program depends upon changeable factors like data-types. Therefore it needs to be
updated with the need on the go.
Basics of C
History of C
In 1960 at the age of turns to computer software there was no such language to develop every
type application that time international committee USN created a language called ALGOL-6 but it is
too general. In 1963 to avoid this generally another language called general purpose language GPL
written by Cambridge University. But it is too difficult to learn to avoid it BCPL Entered which is
written by “Martin Richards” at “Cambridge University” at Same time at AT and T bell laboratories.
The powerful language developed called B written by ke Thompson, Denis Ritchie in 1972 developed
a language called “C” by inheriting the features of B and BCPL. To run the C programwe require
Compiler.
What is C?
C is a programming language, it is a structured programming language, it is general purpose
programming language, It is a middle level language.
C was invented to develop an OS called Unix by Dennis M.Ritchie at AT &T Bell laboratories
New Jersy USA.
C is formalized by ANSI in the year 1988
Most of the state-of-art software have been implemented using C,C was been written in
Assembly language.
Advantages (features) of C programming language
C is the most popular programming language, C has many advantages:
1. Procedural Oriented
C Language is procedure oriented language; here user creates procedures or functions to execute their
task. Procedure oriented language is very much easy to learn because it follows algorithm to execute
your statements. To develop program using procedure oriented language, you need to draw/prepare
algorithm and then start converting it into procedure or functions.
2. Lots of Libraries
C Language provides lots of functions which consist of system generated functions and user defined
functions. C Compiler comes with list of header files which consist of many general functions which
can be used to develop program. while programmer can also create function as per their requirements
that is called as user generated/defined function.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
22
3. Modularity
Modularity is one of the important characteristics of C, we can split the program in to number of
modules instead of writing it sequentially. Modularity improves understandability; it allows
reusability of the modules, which reduce the length of the program.
4. Middle level
As a middle level language it combines both the advantages of low level and high level languages. It is
easily understandable.
5. General purpose
C can be used to implement any kind of applications such as math oriented, graphics, and scientific
oriented and business oriented applications.
6. Portability
C program is compatible with majority of operating systems. Hence it is portable to other systems
even if the operating system differs.
7. Powerful
C is very efficient and powerful programming language. It is best used for data structures and
designing system software.
8. Simple
C is a simple language. C is more or less like English. It has only 32 keywords of its own. For a
programmer, it becomes simple to write programs.
9. Case sensitive
C is a case sensitive language i.e. it allows only lower case letters only.
10. Speed Compilation
C compiler produces machine code very fast compared to other language compiler. C compiler can
compile around 1000 lines of code in a second or two. One more benefit of the C Compiler is that it
also optimizes the code for faster execution.
11. Easy to Learn (Syntax is near to English Language)
C Language syntax is very easy to understand. It uses keyword like if, else, goto, switch, goto, main, etc.
This kind of keyword we all are using in our day to day life to convey meaning or to get some
decisions.
C Language Disadvantages
Every coin has two sides, as C Language has also some disadvantages. C Language has not any
major disadvantages but some features is missing in the C Language, obviously that's why C Language
is very much powerful now.
1. Object Oriented Programming Features (OOPS)
Object Oriented Programming Features is missing in C Language, You have to develop your program
using procedure oriented language only.
2. Run Time Type Checking is Not Available
In C Language there is no provision for run time type checking, for example i am passing float value
while receiving parameter is of integer type then value will be changed, it will not give any kind of
error message.
3. Namespace Feature
C does not provide namespace features, so you can't able to use the same variable name again in one
scope. If namespace features is available then you can able to reuse the same variable name
Integrated Development Environment (IDE)
An integrated development environment (IDE) also known as integrated design environment or
integrated debugging environment is a software application that provides facilities to computer
programmers for software development. An IDE normally consists of a:
 Source code editor
 Compiler and/or interpreter
 Build automation tools
 Debugger
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Process of creating, compiling and running a C program
23
The steps involved in building a C program are:
1. First program is created by using any text editor and the file is stored with extension as .c we
call this file as source file.
2. Next the program is compiled. There are many compilers available like Sun compiler, Borland
compiler. In TurboC environment we press Alt+F9 for compilation.
3. At this stage errors like typing mistake, mistake in key words, Syntax usage errors will be
detected and will displayed by the compiler. The programmer should correct the errors. But a
programmer must note that compiler cannot detect logical errors.
4. After this process the compiled code will be stored in an object file.
5. Press Ctrl+F9 to link object code with system library and to execute the program by creating
an executable file.
6. Give the required input on console screen and press Enter key. To view the results of the
program press Alt+F5
All the programming languages can be divided in to two categories.
1. Problem oriented languages (or) high level languages
2. Machine oriented languages (or) low level languages
1. Problem oriented languages: these languages have been designed to give better programming
efficiency i.e. faster program development.
Ex: FORTRAN, BASIC, PASCAL.
2. Machine oriented languages: these languages have been designed to give a better machine
efficiency i.e. faster program execution.
Ex: assembly language and machine language.
‘C’ stands in between these two categories so that it is often called a middle level language.
Since it was designed to have both a relatively good programming efficiency as well as relatively good
machine efficiency.
GETTING STARTED WITH C
Communicating with a computer involves speaking the language the computer can understand,
which immediately rules out the use of English as the language of communication with the computer.
However, there is a close analogy between learning English and C languages. The classical method of
learning English is to first learn the alphabets or characters used in the language, then learn to
combine to these alphabets to form words, which are in turn combined to form paragraphs. Learning
C language is very much similar to this and easier.
So it is always a good idea to first learn about alphabets, numbers and special symbols used in
C. Then how using these, constants, variables and keywords (reserve words) are constructed. Finally
how these are combined to form instructions. A group of instructions when combined forms a
program.
Steps in learning English language
Alphabets
Words
Sentences
Paragraphs
Steps in learning C language
AlphabetsDigits- Special –
Symbols
Constants
Variables
Keywords
Prepared by: MD Waseem Raza(MCA-TSSET)
Instructions
Program
Downloaded from:
https://www.sucomputersforum.com
24
The C character set
Character denotes any alphabet, digit or special symbol used to represent information. The valid
alphabets, digits and special symbols allowed in C are under.
Alphabets
A,B,C,……………Y,Z
a,b,c,……………...y,z
Digits
0,1,2,……………..9
Special symbols ~ ‘ ! @ # % ^ & * ( ) - _ + = | \ { } [ ] ; : " ’ < > ‚ . ? /
C Tokens
The smallest individual unit in the C program is known as token. C tokens include identifiers,
keywords, variables, constants, special chracters and operators.
C Tokens
Identifiers
Keywords
Variables
Constants
Operator
Identifiers:
Each program element in a C programs are given a name called identifier
Names given to identify variables, functions, and arrays are examples of identifiers.
Ex: int x=10; /*here x is an identifier*/
There are certain Rules that should be followed while naming c identifiers:
1. They must begin with alphabet or underscore
2. Variable name is any combination of 1 to 31 alphabets, digits or underscores.
3. It should not contain white spaces
4. It should not contain punctuation marks
5. It should not be a keyword
Variables:
Variable is an entity that may change during the execution of the program.
Variable is the name of a memory location where some value is stored. These locations can contain
integer, float or character constants. In any language the types of variables depend on the types of
constants that it can handle.
Ex: an integer variable can hold only an integer constant.
Rules for constructing variable names:
1. Variable name is any combination of 1 to 31 alphabets, digits or underscores. The maximum
length of a variable is 31 characters. Some compilers allow variable names whose length could
be upto 247 characters.
2. The first character in the variable name must be an alphabet or underscore
3. No commas or blanks are allowed with in a variable name
4. No special symbol other than an underscore can be used in a variable name
Ex: i, da_3m, _pop5, sum, name, J5x7, Max_number_of_Students
Keywords:
Keywords are the words whose meaning has already been explained to the C compiler. The keywords
cannot be used as variable names because if we do so, we are trying to assign a new meaning to the
keyword, which is not allowed by the computer. The keywords also called as “reserved words”. There
are only 32 keywords available in ‘C’ language.
Auto
double
if
static
break
else
int
struct
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Case
Char
const
continue
default
Do
enum
extern
union
float
for
goto
long
register
return
short
signed
sizeof
25
switch
typedef
unsigned
void
volatile
while
Constants:
The constants in c are applicable to the values which do not change during execution of
program. C supports various types of constants including integers, characters, floating and string
constants.
C has two types of constants: literal and symbolic.
Literal constant:
A literal constant is directly assigned to a variable. C has four types of literal constants such as integer
constants, floating constants, character constants and string constants
Consider the following example
int x=5;
where x is a variable of type int and 5 is a literal constant.
Symbolic constant:
The symbolic constant can be created in the following ways
1. #define
2. the const keyword
The #define preprocessor directive can be used for defining constants.
Ex: # define price 152
We can also define a constant using const keyword
Ex: const int price=152;
Operators
Operator is a symbol used to perform a specific operation on operands. C supports wide variety of
operators such as
 Arithmetic operators
 Logical operators
 Relational operators
 Increment decrement operator
 Assignment operator
 Conditional operator
 Bit wise operators
 Special purpose operators
Input output Instructions
These instructions are used to display Values on to the screen and read value as from screen
In C the input/output statements can be divided into two types
 Formatted input/output statements
 Unformatted input/output statements.
Formatted input output functions:
Printf( ) function
printf is a formatted output function located in Stdio.h function which is used to print the value
contained in a variable on the screen, and the sentence which is written in the double codes in
printf statement prints the same on the screen.
Syntax: printf(“<format string >”,list of variables);
Ex: printf(“%d%d”,a,b);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
26
Scanf( ) function
Scanf is a formatted output function, which is used to read one or more values from the key board
which are belongs to the given control format type and stores at the given address.
Address of a location will be calculated by using ‘&”. If a, b, c are the three variables then their
addresses are &a, &b, &c.
NOTE: the & before the variables in the scanf statement is must.’&’ is a pointer operator.
Syntax: scanf(“<format string>”,&var1,&var2,&var3-------);
Ex: scanf(“%d%d”,&a,&b);
fprintf( ) function
This function is same as the printf( ) function but it writes the data into the file, so it has one
more parameter that is the file pointer.
Syntax: fprintf(fptr,”control character”,variablename);
fscanf( ) function
This function is same as the scanf( ) function but this reads the data from the file, so this has
one more parameter that is the file pointer.
Syntax: fscanf(fptr,”control character”,&vaiable-name)
UNFORMATTED INPUT / OUTPUT STATEMENTS:
Function
getchar()
getche()
getch()
gets()
putchar()
puts()
getc()
putc()
Description
Reads a character and the console remains untill
we press return key
Reads a character and shows on screen but it will
not wait for return key
Reads a character and does not show on the screen
and also it will not stop wait for return key
Reads a string it also accepts spaces in name, it
stops reading when return key pressed
Prints a character on the screen
Prints a name on the screen
Reads a character from a stream
Prints a character to file
Example
Ch=getchar()
Ch=getche()
Ch=getch()
gets(name)
Putch(ch)
Puts(name)
Ch=getc(fp)
putc(ch,fp);
OPERATORS
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations, c operators can be classified in to eight categories. They are
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment and decrement operators.
6. Conditional operators.
7. Bitwise operators.
8. Special operators.
Unary Operators: A unary operator is an operator, which operates on one operand.
Binary: A binary operator is an operator, which operates on two operands
Ternary: A ternary operator is an operator, which operates on three operands.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
27
1. ARITHMETIC OPERATORS:
C provides all the basic arithmetic operators. They are +,-,*,/,%.
Operator
Meaning
Syntactical
Example
form
+
Addition
a+b
4+3
Subtraction
a-b
4-3
/
Multiplication
a*b
4*3
*
Division
a/b
4/3
%
Modulo Division
a%b
4%3
Integer division truncates any fractional part. The modulo division operation produces the
remainder of an integer division.
Ex: c=a+b, c=a-b, c=a*b, c=a/b, c=a%b.
Here a and b are the variables and are known as operands. The modulo division operator % cannot be
used on floating point data.
Note: c does not have an operator for exponentiation.
During modulo divison, the sign of the result is always the sign of the first operand.
Ex: -14%3=-2
-14%-3= -2
14%-3=2
Arithmetic expression can be divided in to three categories.
1. Integer arithmetic expression: if an expression contains only integer operands is known as
integer arithmetic expression.
Ex: if a=5, b=3 then a+b=8.
2. Real arithmetic expression: if an expression contains only real operands is known
as real arithmetic expression.
Ex: if a=5.0,b=3.0 then a+b=8.0.
3. Mixed mode arithmetic expression: if an expression contains either integer or real operands is
known as mixed mode arithmetic expression.
Ex: a=2, b=3.0 then a+b=5.0.
2. RELATIONAL OPERATORS:
These operators are used to compare two quantities and depending on their relation. The
relational operators are
Operator
Meaning
Syntactical
Example
form
<
Less than
a<b
4<3
<=
Less than or equals to
a<=b
4<=3
>
Greater than
a>b
4>3
>=
Greater than or equals to
a>=b
4>=3
==
Equals To
a==b
4==3
!=
Not Equals to
a!=b
4!=3
A simple relational expression contains only one relational operator. The general form of relational
expression is
ae-1 relational operator ae-2
Ex: 2.5<=10 true
2.5<-10 false
3. LOGICAL OPERATORS:
An expression contains two or more relational expression is known as logical expression or a
compound relational expression.
Ex: a>b&&x=21.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
28
‘C’ has three logical operators. They are && (logical AND), || (logical OR), ! (Logical NOT). The logical
operators && and || are used when we want to test more than one condition and make decisions.
The truth table of logical AND (&&)
The truth table of
Cond1
T
T
F
F
Cond2
Cond1
T
T
F
F
Cond2
T
F
T
F
Cond1&&Cond2
T
F
F
F
logic OR (||)
Cond1||Cond2
T
F
T
F
T
T
T
F
Not operator: return the reverse of the original result
!(T)=F !(F)=T
4. ASSIGNMENT OPERATOR
Assignment operators are used to assign the result of an expression to a variable.
Ex: x=10
In the above example 10 is assigned to the variable x.
In adition we have another operator i.e. short and assignment operator
The general format is:
v op=Exp;
Where V is a variable, Exp is an expression and op is an operator and it is equivalent to v=v op (exp);
Ex:
x+=y+1; it is equivalent to x=x+(y+1);
Some other examples
Addition assignment
Subtraction Assignment
Multiplication Assignment
Divisional Assignment
Modulo Division Assignment
a=a+1
a=a-1
a=a*(n+1)
a=a/(n+1)
a=a%b
a+=1
a-=1
a*=n+1
a/=n+1
a%=b
5. INCREMENT AND DECREMENT OPEATORS:
The ++ is known as increment operator and -- is known as decrement operator
The ++ operator adds 1 to the operand whereas the – operator subtract 1 from the operand.
The increment and decrement operators can be written before the operand or after the operand, but if
we write the statements independently they behave differently
Ex: k=6 then
m=++k
in the above example m and k value will be 7
Ex: k=6 then
m=k++
in the above example m value 6 and k value 7
Postfix notation for increment and decrement are k++ and k-Prefix notation for increment and decrement are ++k and --k
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
29
6. CONDITIONAL OPERATOR
?: is known as conditional operator or Ternary operator
General format of the conditional operator is
(Cond)? exp2:exp3
Where exp1, exp2 and exp3 are the expressions
The operator?: works as first exp1 is evaluated, if it is true then exp2 is executed, if the exp1 is false
then exp3 is executed.
Ex: a=10;
b=15;
x= (a>b)? a:b;
In the above example x=15 because exp1 is false so that exp3 is executed i.e. 15.
7. BITWISE OPERATORS:
These operators are used to operate on the bits of operand values.
Operator
Meaning
&
Bitwise AND
!
Bitwise OR
^
Bitwise exclusive OR
<<
Shift left
>>
Shift right
Example: 10&7
1010
0111
0010--- 2
8. SPECIAL OPERATORS:
‘C’ supports some special operators like [],*, sizeof ( ), -> and comma operators.
The comma operator: this operator can be used to link the related expressions together, the commalinked list expressions are evaluated left to right and the value of right-most expression is the value of
the combined expression.
Ex: value=(x=10,y=5,x+y);
The sizeof operator: this is a compile time operator; it returns the number of bytes the operand
occupies. The operand may be a variable, a constant or a data type.
Ex: m=sizeof(sum);
n=sizeof(long int);
k=sizeof(a);
Ex: Program for illustration of operators
main( )
{
int a,b,c,d;
a=15;
b=10;
c=++a-b;
printf(“a=%d b=%d c=%d\n”,a,b,c);
d=b++ +a;
printf(“a=%d b=%d d=%d\n”,a,b,d);
printf(“a/b=%d\n”,a/b);
printf(“a%%b=%d\n”,a%b);
printf(“a*=b=%d\n”,a*=b);
printf(“%d\n”,(c>d)?1:0);
printf(“%d\n”,(c<d)?1:0);
getch( );
}
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Precedence and associativity of operators in C
30
Each Operator in C has a precedence associated with it. This precedence is used to determine
how an expression involving more than one operator is evaluated. There are distinct levels of
precedence and an operator may belong to one of the levels. The operators at the higher level of
precedence are evaluated first. The operators of the same precedence are evaluated either from left to
right or from right to left, depending on the level.
The direction in which the operators is evaluated is known as the associativity property of an
operator.
Operator
()
[]
!
~
+
++
-&
*
Sizeof
*
/
%
+
<<
>>
<
<=
>
>=
==
!=
&
^
|
&&
||
?:
=
*=
/=
%=
+=
-=
,
Operation
Function call
Array subscript
Logical negation (NOT)
Bit-wise 1’s complement
Unary plus
Unary minus
Pre increment or post
Increment
Pre decrement or post
decrement
Address
Indirection
Returns size of operand in
Multiply
Divide
Remainder
Binary plus
Binary minus
Shift left
Shift right
Less than
Less than or equal
Greater than
Greater than or equal
Equality
Not equal to
Bit wise AND
Bit wise XOR
Bit wise OR
Logical AND
Logical OR
Work like simple if – else
Simple assignment
Assign product
Assign quotient
Assign modulus
Assign sum
Assign difference
Evaluate
Prepared by: MD Waseem Raza(MCA-TSSET)
ASSOCIATIVITY
Left to right
RANK
1
Right to left
2
Left to right
3
Left to right
4
Left to right
5
Left to right
6
Left to right
7
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
8
9
10
11
12
13
14
Right to left
Left to right
15
Downloaded from:
https://www.sucomputersforum.com
Conversion Characters
31
Conversion characters of format specifiers are the characters used provide the format for the
value to be read or print using scanf and printf functions. The various conversion characters are listed
below
Character
Description
%c
Prints a single character
%d
Prints an integer
%i
Prints signed decimal integer
%e
Prints a number in an exponential notation
%f
Prints a real number
%o
Prints the octal conversion of integer
%s
Prints an item of type name
%u
Prints an unsigned integer
%x
Prints the hexa decimal conversion of integer
%%
Prints a percent sign
%ld
Long integer
%lf
Double Values
%Lf
Long Double Values
Escape Sequences
Character combinations consisting of backslash(\) followed by a letter is called “escape
sequences”. To represent a newline character, singe quote or certain other characters, we must use
escape sequences. An escape sequences is treated as a single character and is valid as a character
constant.
Character
Description
\a
Beep Sound
\b
Back space
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal Tab
\v
Vertical Tab
\’
Single Quotation mark
\”
Double Quotation mark
\\
Back Slash
\?
Question mark symbol
COMMENTS IN C
A comment is a sequence of characters beginning with a forward slash and asterisk
combination ‘/*’ and ends with a sequence of characters asterisk and forward slash ‘*/’.
Ex: /* the comments maintained in the
Program are not displayed in the output screen*/
Type Casting (Type Conversion)
Typecasting refer conversion of type. Typecasting is essential when the values of variables are
to be converted from one type to another type. C allows implicit as well as explicit conversion.
Explicit Type Casting
Sometimes errors may be encountered in the program with implicit typecasting. The desired
type can be achieved by typecasting a value of particular type. The following is the syntax of
typecasting in C.
(data-type name) expression
Ex: x=(float) 5/2;
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
32
Implicit Type Casting
The type conversion is carried out when the expression contains different types of data items.
When the compiler carries such type conversion itself by using in built data types then it is called
implicit type conversion. The variable of lower type (small range) type when converted to higher type
(large range) is known as promotion. When the variable of higher type is converted to lower type, it is
called demotion.
The below table describes various implicit type conversion rules that a compiler follows.
Argument 1 Argument 2 Argument 3
char
int
Int
int
float
Float
int
long
Long
double
float
Double
int
double
Double
long
double
Double
int
unsigned
Unsigned
Structure of C program
Documentation: comments are used for documentation purpose. Comments can be taken between /*
and */ symbols. In ‘C’ language there are two types of comments they are:
Single line comment: it means that the comments are written in single line.
Ex: Program for addition of two numbers
Multiple line comment: It means the comments are written in more than one line.
Documentation section
Definition section
Linking section
Global variables section
main( ) function section
{
declaration part
executable part
}
subprogram section
function1
function2
-----------function n
Ex: Program for addition of two numbers by taking three variables i.e. the two variables are used to
store the two values for addition and the third variable is used to store the result */
These comment lines are enclosed in anywhere of the program, the compiler ignores whatever we
write in these symbols /* */
Linking section: preprocessor directives are executed before the C source code passes through
compiler. Mostly used preprocessor directives are #include and #define. #include is used for
including header files and other files. #define is used to define the macro name and macro expansion.
Global variables section: It may be possible that some variables used in many function in the C
program, so it is necessary to declare them globally. Those variables are called as global variables
main( ) function section: Every C program has one or more functions, if a program has only one
function then it must be main( ). Execution of every C program start with main( ) function. It has two
parts, declaration part declares all the variables used in the executable part. There is at least one
statement in the executable part. The scope of the local variable is local to that function only.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
33
Statements in the main( ) function executed one by one. These two parts must appear between the
opening and the closing braces. The program execution begins at the opening brace and ends at the
closing brace. All statements in the declaration and executable parts end with a semicolon (;).
Subprogram section: This section contains the functions which are called user defined function,
which has also local variables and C statements. User-defined functions are generally placed
immediately after the main( ) function, although they may appear in any order.
Note: all the sections, except the main( ) function section may be absent when they are not required.
The first ‘C’ program
Each instruction in the C program is written as a separate statement. Therefore the C compiler will
comprise of a series of statements. These statements must appear in the same order in which we wish
them to be executed.
The following rules are applicable to all C statements.
1. Blank spaces must be inserted between two words to improve the readability of the
statements, However there are no blank spaces are allowed within a variable constant or
keyword.
2. All the statements are enclosed in small case letters
3. C has no specific rules for the position at which a statement is to be written. That’s why it is
often called a free-form language
4. Every statement must end with a semicolon (;)
Ex: Program to display a sentence on to the screen
#include<stdio.h>
main( )
{
printf(“NSV Degree College”);
}
Executing a C program: The steps for the execution of C program are as:
1. Creating the program
2. Compiling the program and linking the files
3. Executing the program
1. Creating the program: The program must be Entered in to a file with the help of a Turbo C by
selecting a new file (press the keys i.e. alt+f+n). The program must be saved before the compilation,
to save the file press the keys (alt+f+s or F2 button). The file name can consist of letters, digits and
special characters, followed by a dot operator and a letter c. the program that is Entered in to the file
is known as the source program.
Ex: program.c
2. Compiling the program: To compile the program press the keys i.e. alt+c+c. compilation means
finding the errors within the program and converting our source program into machine code which is
understand by the computer. This conversion can be done after examining each instruction for its
correctness. If there are no errors in our program the compilation proceeds and the converted
program will be stored in another file i.e. program.obj.
Linking is the process of putting other program files and functions that are required by the program.
Ex: if the program is using sqrt( ) function, then the object code of this function should be brought
from the math library of the system and linked to the main program.
3.
Executing the program: To execute or run the program we press the keys alt+r+r. executing
the program means getting the output on to the screen. During the execution, the program may
request for some data to be Entered through the keyboard. Sometimes the program does not produce
the correct results. Because some thing is wrong with the program logic or data. Then it would be
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
34
necessary to correct the source program or the data. In case the source program is modified, the
entire process of compiling, linking and executing the program should be repeated.
System ready
Program code
Enter program
Source program
Edit source program
C Compiler
Compile source
program
Yes
Syntax
Errors
No
System library
object code
Link with system
library
Executable object code
Input Data
Data error
Executable object
code
Logic error
Logic and
data
errors
No Errors
Correct output
Stop
Process of compiling and running a C program
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
35
Compiler
The compiler is a program used for converting the code of high level language program into
machine level. The compiler searches all the errors of program and lists them. If the program is error
free then it converts the code of program into machine code and then the program can be executed by
separate commands.
To open C editor
Click on start buttonrunEnter cmd/command ok
C:\documents and settings\nsvdc>cd\ 
C:\>cd turboc2
C:\>tc
It opens c editor
To Compile C program we use Alt+f9
To run C program we use Ctrl+f9
To see the output we use Alt+f5
Program:
Set of instructions grouped together to perform a specific task.
#include<stdio.h> is a standard header file must be added for the c programs which uses its functions,
but not for printf and scanf
1. Write a program to find the sum of two
2. Write a program to find the sum of two
numbers without the scanf function?
numbers using scanf function?
main( )
main( )
{
{
int a=12,b=2,c;
int a,b,c;
c=a+b;
printf(“Enter two values”);
printf(“the sum of two numbers is %d”,c);
scanf(“%d%d”,&a,&b);
}
c=a+b;
printf(“the sum of two numbers is %d”,c);
}
3. Write a program to find the
4. Program to calculate simple interest?
product/multiply two numbers?
main( )
main( )
{
{
float p,t, r,si;
int a=10,b=8,c;
printf(“Enter the values of p,t,r”);
c=a*b;
scanf(“%f%f%f”,&p,&t,&r);
printf(“The product is =%d”,c);
si=p*t*r/100;
}
printf(“the simple interest is =%f”,si);
}
Data types in C
1. Data type determines the type of data a variable will hold, if a variable X is declared as “int”, X
can hold only integer values.
2. Data type also defines operations that can be performed on them.
3. Every variable which is used in the program must be declared as what data type it is.
4. For every data type C compiler defines and allocates required number of bytes.
C Data types can be classified into the following
Basic Data types
Derived Data types
User Defined Data types
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
36
C-Data Types
System Defined data types
User defined
Derived datatype
datatype
Integer type
Integer
Float.double
Char type
Single char
String
Structures
Arrays
Unions
Pointers
Enumeration
Basic Data types: The basic data type include: Integer, Float, Char
Integer type: this data type can hold whole numbers either positive or negative. C has 3 classes of
integer type Short int, int, long int
This data type can occupy 2 bytes of memory.
The type conversion specifier for int is %d.
Ex: +300, 0,-7,1234,8801
The range of the data type shown in the table below
float type: this data type can hold floating point numbers either positive or negative.
This data type can occupy 4 bytes of memory.
The type conversion specifier for float is %f
Ex: 202.50, -385.25, 3.142, 10.78
The range of the data type shown in the table below
Char type: this data type can hold single character.
This data type can occupy 1 bytes of memory.
The type conversion specifier for char is %c
Ex: ‘ A’, ‘I’ ,‘p’, ‘r’, ’4’ , ’7’
The derived Data types:
The derived data type include Array’s, Pointers
The user defined data types:
The user defined data type include Structures, Unions, Enumerations
Data Type
Range
Bytes Format
Signed char
-128 to +127
1
%c
Unsigned char
0 to 255
1
%c
Short signed int
-32768 to +32767
2
%d
Short unsigned int 0 to 65535
2
%u
Signed int
-32768 to +32767
2
%d
Unsigned int
0 to 65535
2
%u
Long signed int
-2147483648 to+2147483647
4
%ld
Long unsigned int 0 to 4294967295
4
%lu
Float
-3.4e38 to +3.4e38
4
%f
Double
-1.7e308 to +1.7e308
8
%lf
Long double
-1.7e4932 to 1.7e4932
10
%Lf
There is one more data type called void which is also known as empty data type.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
CONTROL STRUCTURES
37
These are used to control the flow of execution of program body statements.
These can be divided in to 3 categories.
1.
Conditional Statements
2. Loop Statements
3. Jumping Statements
CONDITIONAL STATEMENTS
Branching means when a program breaks the sequential flow and jumps to another part of the code.
Control statements:
1.
Simple if statement.
2.
If----else statement.
3.
Nested if ----else statement.
4.
Else----if statement.
5.
Switch statement.
1. SIMPLE IF STATEMENT: The general form of simple if statement is
if (test expression)
{
Statement-block;
}
Statement-x;
Flow Chart of Simple If statement
The statement-block may be a single statement or a group of statements. If the test expression
is true, then the statement-block will be executed. If the test expression is false, then the statementblock will be skipped and the execution will jump to the statement-x.
Note: when the condition is true then both the statement-block and the statement-x are executed in
sequence.
Write a program to test whether the given number is less than 10 or not?
main( )
{
int n;
printf (“Enter the number”);
scanf(“%d”,&n);
if (n<10)
{
printf(“the given number is less than 10”);
}}
2. IF----ELSE STATEMENT:
The general form of if----else statement is
if(test expression)
{
True-block statement;
}
else
{
False -block statement;
}
Statement-x;
Flow Chart of If-else statement
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
38
This process is used for only two conditions. The compiler checks the condition first. If the
condition is true then the true-block statement will be executed and control transferred to statementx. If the condition is false, then the false-block statement will be executed and control transferred to
statement-x.
Note: In this statement either true-block statement or false-block statement will be executed, not
both.
1. Write a program to find whether the
given number is even or odd?
#include<stdio.h>
main( )
{
int n;
printf(“\n Enter n value”);
scanf(“%d”,&n);
if(n%2==0)
{
printf(“given number is even”);
}
else
{
printf(“given number is odd”);
}
}
3. NESTED IF----ELSE STATEMENT:
The general form of nested if----else statement is
if(test condition-1)
{
if(test condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
2. Write a program to find whether the
given number is positive or negative?
#include<stdio.h>
main( )
{
int n;
printf(“\n Enter n value”);
scanf(“%d”,&n);
if(n>0)
{
printf(“given number is +VE”);
}
else
{
printf(“given number is -VE”);
}
}
Flow Chart of Nested If-else statement
The logic of execution is first the compiler checks the condition-1, if it is false, then the
statement-3 will be executed. If it is true, then the condition-2 is examined. If it is true then statement1 is executed. If it is false, then the statement-2 is executed. In all cases the statement-x will be
executed.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
39
Write a program to print the largest of three numbers using nested if----else statement?
main( )
{
float a,b,c;
printf("Enter three values");
scanf("%f%f%f",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("the highest value is=%f",a);
}
else
{
printf("the highest value is=%f",c);
}
}
else
{
if(c>b)
printf("%f\n",c);
else
printf("%f\n",b);
}
getch( );
}
4. ELSE----- IF LADDER STATEMENT:
There is another way of putting if’s together when multipath decisions are involved. A
multipath decision is a chain of if’s in which the statement associated with each else is in if.
The general form of nested else-----if statement is
if(condition-1)
statement-1;
else if(condition-2)
statement-2;
else if(condition-3)
statement-3;
----------------------else if(condition-n)
statement-n;
else
default statement;
statement-x;
Flow Chart of Else-if Ladder statement
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
40
This construct is known as else----if ladder. The conditions are evaluated from the top. If the
first condition is true, then the statement associated with it is executed and the control transferred to
the statement-x. If the condition is false, then the control goes to the next condition and repeated the
same process. When all n conditions become false, then the final else containing the default statement
will be executed.
Write a program to print the grade of the student?
main( )
{
int m1,m2,m3,m4,m5,sum;
float avg;
clrscr( );
printf("Enter five subjects marks\n");
scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);
sum=m1+m2+m3+m4+m5;
avg=sum/5;
if(m1<=34||m2<=34||m3<=34||m4<=34||m5<=34)
printf("Fail");
else if(avg>=70)
printf("Distinction");
else if(avg>=60 && avg<70)
printf("First class");
else if(avg>=50 && avg<60)
printf("Second class");
else if(avg>=40 && avg<50)
printf("Third Class");
else
printf("Pass");
getch( );
}
5. SWITCH STATEMENT:
Switch statement is a built-in multi way decision statement. The general form of the switch statement
is
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
.
.
.
.
default:
default-block;
break;
}
statement-x;
Flow chart of Switch statement
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
41
The switch statement tests the value of a given variable (or expression) against a list of case
values and when a match is found, a block of statements associated with that case is executed.
The expression is an integer expression or character. value-1, value-2 …are constants and are
known as case labels. Each of these values should be unique within a switch statement. block-1, block2,…..are statement lists and may contain zero or more statements. Note that case labels end with a
colon.
The break statement can be written at the end of each case so that it immediately exit from the
switch statement and control transfer to the statement-x.
The default is a optional case. If it is written in the switch statement it will be executed if the
value of the expression does not match with any of the case values. If it is not written in the switch
statement, then the control goes to the statement-x.
1. Write a menu driven program?
2. Write a program to print a single digit
#include<stdio.h>
number in words using switch statement.
main( )
#include<stdio.h>
{ int a,b,c;
main( )
char ch;
{
printf("Enter any two numbers\n");
int n;
scanf("%d%d",&a,&b);
printf(“Enter a single digit no.”);
printf("1.Addition \n 2.subtraction \n
scanf(“%d”,&n);
3.Multiplication \n 4.Division \n 5.Modulo
switch(n)
division \n 6.Exit \n”);
{
printf("Enter your choice\n");
case 1: printf(“one”); break;
scanf("%c",&ch);
case 2: printf(“two”); break;
switch(ch)
case 3: printf(“three”); break;
{
case 4: printf(“four”); break;
case '1': c=a+b;
case 5: printf(“five”); break;
printf("Result is:=%d",c); break;
case 6: printf(“six”); break;
case '2': c=a-b;
case 7: printf(“seven”); break;
printf("Result is:=%d",c); break;
case 8: printf(“eight”); break;
case '3': c=a*b;
case 9: printf(“nine”); break;
printf("Result is:=%d",c); break;
default:
printf(“zero”); break;
case '4': c=a/b;
}
printf("Result is:=%d",c); break;
getch( );
case '5': c=a%b;
}
printf("Result is:=%d",c); break;
case '6':
exit( ); break;
default: printf("your choice is wrong \n");
}
getch( ); }
LOOPS
A repetitive process is known as loop.
Loops are used when we want to execute a part of the program or a a block of statements
several times. For example, if we want to print “hello”10 times then we write 10 printf statements,
which is not preferable. Other way of doing this is using loop we can write one loop statement and
only one printf statement.
A looping process would include the following four steps:
1. Setting and initialization of a condition variable.
2. Execution of the statements in the loop.
3. Test for specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
42
The C language provides for three types of loop operations. These are also called as iterative
statements.
1.
The while…..loop
2.
The do…..while loop
3.
The for….loop
1. WHILE……LOOP:The basic format of the while statements is
initialize loop counter;
while(test condition)
{
body of the loop;
increment loop counter;
}
statement-x;
Flow chart of While loop
First the compiler evaluates the condition, if the condition is true then it executes a single or a
block of statements, are executed. This mean that these statements are executed continuously until
the condition is false.
1. Write a program to print hello 10 times?
main( )
{
int i=0;
while(i<=10)
{
printf(“HELLO”);
i=i+1;
}
}
3. Write a program to generate the factors
of a given number?
#include<stdio.h>
main( )
{
int i,n;
printf("Enter n value");
scanf("%d",&n);
i=1;
while(i<=n)
{
if(n%i==0)
{
printf("%d is a facter\n",i);
}
i=i+1;
}
getch();
}
Prepared by: MD Waseem Raza(MCA-TSSET)
2. Write a program to print all even
numbers which are <n.
main( )
{
int i=0,n;
printf(“Enter the value of n“);
scanf(%d”,&n);
while(i<=n)
{
printf(“%d”,i);
i=i+2;
}}
4. Write a program to find whether the
given number is perfect number or not?
main( )
{
int i=1,n,sum=0;
printf("Enter n value");
scanf("%d",&n);
while(i<=n)
{
if(n%i==0)
{
sum=sum+i;
printf("%d is a factor\n",i);
}
i=i+1;
}
printf("sum=%d\n",sum);
if(sum==2*n)
printf("given number is perfect");
else
printf("not perfect");
}
Downloaded from:
https://www.sucomputersforum.com
43
2. DO….WHILE LOOP:The ‘do…while’ statement is also used for looping.
This can be written as
Initialise counter;
do
{
Body of the loop;
Increment loop counter;
}
while(cond);
Statement-x;
Flow chart of Do-While loop:
First the compiler executes a block of statements then evaluates the condition. If the condition
is true it evaluates a block of statements continuously until the condition becomes false.
1. Write a program to print numbers from 2. Write a program to generate the factors
1 to 10?
of a given number?
main( )
#include<stdio.h>
{
main( )
int i=1,n;
{
printf("Enter n value");
int n=1;
scanf("%d",&n);
do
do
{
{
printf(“%d”,n);
if(n%i==0)
n=n+1;
{
}
printf("%d is a facter\n",i);
while(n<11);
}
getch( );
i=i+1;
}
}while (i<=n);
}
3. Write a program to find the factorial of a 4. Write a program to find whether the
given number?
given number is prime or not?
#include<stdio.h>
#include<stdio.h>
main( )
main( )
{
{
int i,n,f;
int i=1,n,count=0;
printf("Enter n value");
printf("Enter n value");
scanf("%d",&n);
scanf("%d",&n);
i=1;f=1;
do
do
{ if(n%i==0)
{ f=f*i;
{ count=count+1;
i=i+1;
printf(“%d is a factor\n”,i); }
}while(i<=n);
i=i+1;
printf("factorial=%d",f);
}while(i<=n);
getch( );
if(count==2)
}
printf("prime no.");
else
printf("not prime no"); }
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
44
3. FOR LOOP:The for statement is very useful
while programming in c. It has
three expressions. Semicolon is
necessary for separating these
expressions.
The first expression is for counter,
second expression is for condition
and third expression is for
modification of counter.
The general form of the for loop is
For (initialization; test-condition; increment)
{
Body of the loop;
}
Flow chart of for loop
The execution of for Loop is as follows:
1. Initialization of the control variable is done first.
2. The value of the control variable is tested using the test-condition.
The test condition is a relational expression, such as i<10. If the condition is true then the body of the
loop is executed, otherwise the loop is terminated out from the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement and the
control variable is incremented. Now the new value of the control variable is again tested whether it
satisfies the loop condition. If the condition is satisfied the body of the loop is again executed. This
process continues until the condition becomes false.
1.Write a program to find whether the
given number is prime or not?
#include<stdio.h>
main( )
{
int i,n,count;
printf("Enter n value");
scanf("%d",&n);
count=0;
for(i=1;i<=n;++i)
{
if(n%i==0)
{
count=count+1;
printf(“%d is a factor\n,i);
}
}
if(count==2)
printf("prime no.");
else
printf("not prime no");
getch( );
}
Prepared by: MD Waseem Raza(MCA-TSSET)
2. Write a program to generate the
fibonacci series for n terms?
#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are
:-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
Downloaded from:
https://www.sucomputersforum.com
Nested Loops
45
Using a loop with in another loop is called
In genereal use nested for loops
Th enested loops are generally used to construct matrix form of data,the outer loop counts no. of rows
and iner loops counts no of columns
Syntax:
Nested do while
Nested while
Nested for
do
while (condition1)
For(intialization;condition
{
{
check;updation)
statement(s);
statement(s);
{
do
while (condition2)
For(intialization;condition
{
{
check;updation)
statement(s);
statement(s);
{
... ... ...
... ... ...
Body of iner loop
}
}while (condition2);
}
Body of outer loop
... ... ...
... ... ...
}
}while (condition1);
}
1. Write a program to print the following
design?
*
* *
* * *
* * * *
#include<stdio.h>
main( )
{
int n,nl,i;
printf("Enter no. of lines");
scanf("%d",&nl);
for(n=1;n<=nl;++n)
{
for(i=1;i<=n;++i)
Prepared by: MD Waseem Raza(MCA-TSSET)
2.Write a program to print the following
design?
1
1 2
1 2 3
1 2 3 4
#include<stdio.h>
main( )
{
int n,nl,i;
printf("Enter no. of lines");
scanf("%d",&nl);
for(n=1;n<=nl;++n)
{
for(i=1;i<=n;++i)
Downloaded from:
https://www.sucomputersforum.com
{
printf("*");
}
printf("\n");
}
}
46
{
printf("%d",i);
}
printf("\n");
}
}
JUMPING STATEMENTS IN C
GOTO STATEMENT:This is an unconditional control statement. When we use this statement the flow of control is
transferred to another part of the program without testing any other condition.
Avoid using ‘goto’ as it is difficult to understand where the flow of control is goes. The goto
statement can be used as
goto label name;
Label name:
statement;
Since label name is the label where the flow of control goes.
1. Write a program to print whether the number is even or odd?
#include<stdio.h>
main( )
{
int n;
printf(“Enter the number”);
scanf(“%d”,&n);
if(n%2= =0)
goto even;
else
goto odd;
even:
printf(“the given number is even”);
goto end;
odd:
printf(“given number is odd”);
goto end;
end:
printf(“end of the program”);
getch( );
}
BREAK STATEMENT:Break statement is used generally with loops and switch statements. It is used to terminate a
loop. This statement causes an immediate exit from that loop in which this statement appears. This
can be written as break;
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Flow chart:-
47
In loop
Yes
Break statement
Skip remaining iterations of loop
No
Next iteration of loop
Write a program to demonstrate break statement?
#include<stdio.h>
main( )
{
int i=1;
while(i<=10)
{
if(i==4)
{
printf("hello");
break;
}
i=i+1;
}
CONTINUE STATEMENT:The continue statement is used for doing next iteration of the loop. The loop does not
terminate when this statement occur. But it skips the statements, which are after this statement in the
block. This can be written as continue;
Flowchart:
in loop
Continue statement
No
yes
Next iteration of loop
Write a program to demonstrate continue statement?
#include<stdio.h>
main( )
{
int i=1;
while(i<=10)
{
if(i==5)
{
printf("hello");
Prepared by: MD Waseem Raza(MCA-TSSET)
Skips current iteration
Downloaded from:
https://www.sucomputersforum.com
48
continue;
}
i=i+1;
}
}
Difference Between While and Do While loop
S.No
1
2
3
4
5
6
7
While Loop
It is known as entry control loop
In this loop the condition is tested at the
top of the loop
In this loop if the condition is true, the
body of the loop will be executed
Here minimum no of executions may be
zero.
In this loop while keyword followed by
test condition is not terminated with
semicolon(;)
Syntax:
Intialization;
While(Condition)
{
Statement Block
Updation;
}
Example:
i=1;
While(i<=10)
{
Printf(“%d\t”,i);
i++;
}
Do While Loop
It is known as exit control loop
In this loop the condition is tested at the
bottom of the loop
In this loop the body of the loop will be
executed, with testing the condition
Here minimumnumber of executions is
one
In this loop while keyword followed by
test condition is terminated with
semicolon(;)
Syntax:
Intialization;
Do
{
Statement Block
Updation;
} While(Condition);
Example:
i=1;
Do
{
Printf(“%d\t”,i);
i++;
} While(i<=10);
ARRAYS
Definition1: Collection of elements of similar type is called as Array, which are stored in Consecutive
memory locations and shared a common name, every element in the collection is identified with its
subscript value.
Definition2: Collection of similar type elements stored in sequential memory locations is known as
array. (or) An array is a collective name that can be given to a group of ‘similar quantities’.
The elements of the array stored in sequential memory location, the similar elements could be
all integers, or all floating values, or all characters, etc. generally the array of characters is called
‘string’.
Ex: m= {45, 25, 35, 20, 40);
m[0]
m[1]
m[2]
m[3]
m[4]
m (name of the array) Index variables Addresses
45
0
&m[0]
25
1
&m[1]
35
2
&m[2]
20
3
&m[3]
40
4
&m[4]
Elements of the array
Subscripts
references
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
49
The elements of array are indicated by specifying the array name followed by subscript in
square brackets.
Ex: m[10];
The elements of this array are
m[0], m[1], m[2], m[3]…………..m[9]
The array elements are counting from “0” hence if the size of array is n. i.e. m[n] then m[0] is the first
element and m[n-1] is the last element of the array.
Syntax for declaration of the array: like the declaration of the variables, we can also declare the
array. The array should be declared with the data type.
The syntax for declaration of array is
Data type array-name[expression];
Ex: int age[10];
float sal[20];
char grade[10];
Here integer array can store integer values and every element of array can hold an integer value.
Similarly float and character array can hold float and character values.
Processing of array:
The elements of the array are stored in contiguous memory locations.
Ex: int m[5];
This is stored in memory as
100 102 104 106 108
m[0] m[1] m[2] m[3] m[4]
We can read and store the values in the array by scanf( ) statement like
scanf(“%d”,&m[1]);
Similarly we can print the value of the array elements by using printf( ) statement
printf(“%d”,m[1]); by this statement we can print the value of 2nd element of the array.
Program to find average marks obtained by a class of 10 students in a test?
main( )
{
int sum=0;
float avg;
int marks[10];
for(i=0;i<=9;i++)
{
printf(“\n Enter marks”);
scanf(“%d”,&marks[i]);
}
for(i=0;i<=9;i++)
sum=sum+marks[i];
avg=sum/10;
printf(“\n average marks=%f”,avg);
}
getch( );
}
Output: displays average marks of 10 students
Advantages of arrays:
Array is capable of storing many elements at atiem with a common name
We can assign the element of an array to any ordinary variable or another array element of same data
type
Any element of array can be accessed randomly
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
50
Disadvantages of arrays:
Predetermination of array size is must
There is a chance of memory wastage
Deleting or inserting elements needs shifting of elements
Program to print the sum of 10 numbers
main( )
{
int m[10],i,sum=0;
for(i=0;i<10;i++)
{
printf(“Enter %d value:\n”,i+1);
scanf(“%d”,&m[i]);
}
for(i=0;i<10;i++)
sum=sum+m[i];
printf(“sum=%d”,sum);
getch( );
}
Output: displays sum of Entered 10 numbers.
Accessing elements of an array: the individual elements in the array can be referred with subscript,
the number in the brackets following the array name. This number specifies the elements position in
the array. All the array elements are numbered, starting with 0.
Ex: marks[] is not the second element this is the third element, because array elements can be started
with 0.
Entering data into an array: the code places data into an array
for(i=0;i<=9;i++)
{
printf(“\n Enter marks”);
scanf(“%d”,&marks[i]);
}
for loop causes the process of asking for and receiving a student’s marks from the user to be repeated
10 times. The first value can be stored in the array element stored in marks[0], second array element
stored in marks[1]. This process will be repeated until i becomes 9.
Reading data from an array: the balance of the program reads the data back out of the array and
uses it to calculate the average. The for loop is much the same but now the body of the loop causes
each students marks to be added and stored in a variable called sum. The result of sum is divided by
10 to get the average.
for(i=0;i<=10;i++)
sum=sum+marks[i];
Array initialization: like the normal variable we can also initialize the arrays as
Ex: int sum[6]={2,5,6,8,9,4};
int n[]=(5,6,9,3,4,2};
float avg={12.3,25.3,42.6,22.11};
Note:
1. Till the array elements are not given any specific values, they are supposed to contain garbage
values.
2. If the array is initialized where it is declared, mentioning the dimension of the array is optional.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
51
Array elements in memory: consider the following array declaration
int m[8];
When we make this declaration 16 bytes get immediately reserved in memory, two bytes each
for the 8 integers, here we not mention any storage class before the declaration. So the compiler
assumes it as automatic storage class. Now all the elements of an array would have garbage values. If
the storage class is declared to be static then all the array elements would have a default initial value
as zero.
2
4
6
8
10
12
14
16
m[0] m[1] m[2]……………………………….....m[7]
Arrays as function arguments: array elements can be passed to a function by calling the function by
value or by reference.
In the call by value we pass values of array elements to the function, where as in the call by reference
we pass addresses of array elements to the function.
Program for demonstration of call by value
main( )
{
int i;
int marks[]=(55,65,75,85,95,35,66};
for(i=0;i<=6;i++)
display(marks[i];
getch( );
}
display( int m)
{
printf(“%d”,m);
}
Output: 55 65 75 85 95 35 66
Here, we are passing an individual array element at a time to the function display( ) and getting
it printed in the function display( ). Note that since at a time only one element is being passed. This
element is collected in an ordinary integer variable m in the function display( ).
Two-dimensional and multi dimensional arrays
It is possible for arrays will have two or more dimensions.The two dimensional arrays consists
rows and columns. But two dimensional char array works like an array of string.
Example for two dimensional array is a matrix of 2x2 or 3x3.
Program to demonstrate two dimensional arrays.
main( )
{
int a[5][5], i,j;
clrscr( );
printf(“Enter 4 elements into 2x2 matrix:”);
for(i=0;i<=2;i++)
{
for(j=0;j<=2;i++)
{
scanf(“%d”,&a[i][j]); }
}
printf(“Entered 2x2 matrix is:\n”);
for(i=0;i<=2;i++)
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
{
for(j=0;j<=2;i++)
{
printf(“%d\t”,a[i][j]);
printf(“\n”);
}
getch( );
52
}
}
Simple program that stores roll number and marks obtained by a student side by side in a
matrix.
main( )
{
int stud[4][2];
int i;
clrscr( );
for(i=0;i<=3;i++)
{
printf(“Enter roll number and marks\n”);
scanf(“%d%d”,&stud[i][0],&stud[i][1]);
}
for(i=0;i<=3;i++)
printf(“\n%d\t%d\n”,stud[i][0],stud[i][1]);
getch( );
}
Output: displays roll number and marks that are being Entered.
There are two parts to the program in the first part through a for loop we read the values of
roll numbers and marks. Where as in the second part through another for loop we print out these
values.
scanf(“%d%d”,&stud[i][0],&stud[i][1]);
in stud[i][0] and stud[i][1] the subscript of the variable stud is row number which changes for every
student the second subscript tells which of the two columns are the 0 th column which contains the
roll number or the first column which contains the marks in every array the counting of rows and
columns begins with zero.
col no.0
col no.1
row no. 0
11
56
row no. 1
12
33
row no. 2
13
80
row no. 3
14
70
Thus, ii is stored in stud [0][0], 56 is stored in stud[0][1] and so on. By the above program we
can say the two dimensional array is nothing but a collection of a number of one dimensional arrays
placed one below the other.
Initializing a two dimensional array:
int stud[4][2]={
{11, 56},{12, 33},
{13, 80),{14, 70)
};
(or)
int stud[4][2]={11,56,12,33,13,80,14,70};
Note: while initializing a two dimensional array it is necessary to mention the second (column)
dimension, where as the first dimension (row) is optional.
Thus the declarations
int arr[2][3]={12,34,23,55,42,12};
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
53
int arr[][3]= {12,34,23,55,42,12};
are perfectly acceptable
where as int arr[2][]={12,34,23,55,42,12};
int arr[][]={12,34,23,55,42,12}; would never work.
Memory map of a two dimensional array: the arrangement of array elements in a in a two
dimensional array of students, which contains roll numbers in one column and the marks in the order.
The memory doesn’t contain rows and columns. In memory whether it is a one-dimensional or two
dimensional array the array elements are stored in one continuous chain.
s[0][0] s[0][1] s1][0]
s[1][1] s[2][0] s[2][1] s[3][0] s[3][1]
08
11
56
12
33
13
80
14
78
10
12
14
16
18
20
22
The marks obtained by the third student using the subscript notation is
Ex: printf(“marks of third student=%d”,stud[2][1]);
Multidimensional array: in one dimensional array we use one bracket where as in two dimensional
arrays we use two brackets and in three dimensional arrays we use three brackets. Similarly in ndimensional array we use n brackets.
In arr[i][j] the starting element of array is arr[0][0] and the last element of array is arr[i-1] arr[j-1],
here i denotes the row in the array and j denotes the column in array.
Searching
Searching is a process of finding the specified element in the group of element. The searching
techniques are divided in to two categories i.e.
1. Linear Search
2. Binary Search
Linear Search: It is a sequential search. In this case we can search the required element one by one
sequentially. It is the lengthy process, so that we may not use this method for more number of
elements.
Program to find an element in an array by using Linear Search
main( )
{
in a[20],I,n,ele,found=0;
clrscr( ):
printf(“how many numbers do you want\n”);
scanf(“%d”,&n);
printf(“Enter %d numbers\n”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the searching element\n”);
scanf(“%d”,&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
found=1;
break;
}
}
if(found==1)
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
54
printf(“%d element is found”,ele);
else
printf(“%d”,element is not found”,ele);
getch( );
}
2. Binary Search: In binary search the elements can be given in the ascending or descending
order.Inthis process Entire List is divided into two parts For each repetation the list will be half.
Program to locate an element in an array, using Binary Search
main( )
{
int a[20],i,n,ele,low,high,mid,found=0;
clrscr( ):
printf(“how many numbers do you want\n”);
scanf(“%d”,&n);
printf(“Enter %d numbers\n”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the searching element\n”);
scanf(“%d”,&ele);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(ele<a[mid])
high=mid-1;
else if(ele>a[mid])
low=mid+1;
else if(ele=a[mid])
{
found=1;
break;
}
}
if(found==1)
printf(“%d element is found”,ele);
else
printf(“%d”,element is not found”,ele);
getch( );
}
Sorting
Sorting is process of arranging the elements in the list according to their values in ascending or
descending order. The three simple and most important sorting techniques are
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
1. Bubble Sort: in the bubble sort technique the elements are sorted in ascending order. This involves
the following steps.
Ex: if we have given five elements then
Process 1:
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
55
Step 1: the first element is compared with the second element then if the second element is lower than
the first element they are interchanged, if the second element greater than the first then they
unchanged.
Step 2: now the second element is compared with the third element, if the third element is lower than
the second then they are interchanged, if not they are unchanged.
Step 3: the third element is compared with the fourth element. If the fourth element is lower than the
third then they are interchanged, if not they are unchanged.
Step 4: the fourth element is compared with the fifth element, if the fifth element is lower than the
fourth then they are interchanged, if not they are unchanged.
Process 2:
Step 1: the same steps will be continued in the second process until the list was sorted in ascending
order.
Ex: 44, 33,55,22,11
Process 1:
Process 2:
44
33
33
33
33
33
33
33
44
44
44
44
44
22
55
55
55
22
22
22
44
22
22
22
55
11
11
11
11
11
11
11
55
55
55
Process 3:
Process 4:
33
22
22
22
33
11
11
11
33
44
44
44
55
55
55
Program for Demonstation of bubble sort
main( )
{
int x[30],j,t,n;
clrscr( );
printf(“Enter the numbers\n”);
scanf(“%d”,&n);
printf(“Enter %d element\n”,n);
for(i=0;i<n;i++)
scanf(“%d”,&x[i]);
for(i=1;i<n;i++)
for(j=0;j<n-i;j++)
if(x[j]>x[j+1])
{
t=x[j];
x[j]=x[j+1]; x[j+1]=t;
printf(“elements aftersorting:\n”);
for(i=0;i<n;i++)
printf(“%d\n”,x[i]);
getch( );
}
Result:
11
22
33
44
55
}
2. Selection sort: In selection sort the given elements are sorted in ascending order it involves the
following steps
Ex: if 5 elements are Entered then in selection sort the elements are sorted as under:
Process 1:
Step 1: the first element is compared with the second element if the second element is lower than the
first element then they are interchanged. If not they are unchanged.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
56
Step 2: the first element is compared with the third element if the third element is lower than the first
element then they are interchanged. If not they are unchanged.
Step 3: the first element is compared with the fourth element if the fourth element is lower than the
first element then they are interchanged. If not they are unchanged.
Step 4: the first element is compared with the fifth element if the fifth element is lower than the first
element then they are interchanged. If not they are unchanged.
Process 2: the same steps are involved in process 2 until the elements are sorted in ascending order.
Process 1:
Process 2:
44
33
33
22
11
11
11
11
11
33
44
44
44
44
44
44
33
22
55
55
55
55
55
55
55
55
55
22
22
22
33
33
33
33
44
44
11
11
11
11
22
22
22
22
33
Process 3:
11
11
22
22
55
44
44
55
33
33
11
22
33
55
44
Process 4:
11
11
22
22
33
33
55
44
44
55
Result:
11
22
33
44
55
Program for demonstration of selection sort
main( )
{
int x[30],i,j,t,n;
printf(“Enter the elements\n”);
scanf(“%d”,&n);
printf(“Enter %d elements\n”,n);
for(i=0;i<n;i++)
scanf(“%d”,&x[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(x[i]>x[j])
{
t=x[i];
x[i]=x[j];
x[j]=t;
}
printf(“elements after sorting are:\n”);
for(i=0;i<n;i++)
printf(“%d”,x[i]);
getch( );
}
3. Insertion Sort: The Insertion Sort insert each element in proper place this is same as playing cards
in which we place the card in proper order there are n elements in the array and we place each
element of array at proper place in the previously sorted elements.
Let us take there are n elements in the array arr. Then process of inserting each element in proper
place is as follows:
Step 1:
arr[1] is already sorted because of only one element
Step 2:
arr[2] is inserted before or after arr[1] so, arr[1]and arr[2] are sorted
step 3:
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
57
arr[3] is inserted before arr[1],in between arr[1] and arr[2] or after arr[2] so, arr[1], arr[2], arr[3] is
sorted.
.
.
.
.
.
.
.
.
Step n:
arr[n] is inserted into its proper place in array arr[1],arr[2]…………………arr[n-1]
so arr[1], arr[2],…………………arr[n] are sorted.
Ex: 82, 42, 49, 8, 92,25,59,52
82
42
49
8
92
25
59
52
82
42
49
8
92
25
59
52
42
82
49
8
92
25
59
52
42
49
82
8
92
25
59
52
8
42
49
82
92
25
59
52
8
42
49
82
92
25
59
52
8
25
42
49
82
92
59
52
8
25
42
49
59
82
92
52
8
25
42
49
52
59
82
92
Result
Program for sorting the elements of array with insertion sort
main( )
{
int arr[10],n,i,j,k;
printf(“Enter the number elements\n”);
Scanf(“%d”,&n)
printf(“Enter %d elements”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]); }
for(j=1;j<n;j++)
{
k=arr[j];
for(i=j-1;i>=0&&k<arr[i];i--)
arr[i+1]=arr[i];
arr[i+1]=k;
}
printf(“elements aftersorting:\n”);
for(i=0;i<n;i++)
printf(“%d”,arr[i]);
getch( );
}
Merging
It means combining or joining two numbers or items
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Program to demonstration of merging matrices
#include<stdio.h>
main( )
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;
clrscr( );
printf("Enter the order of the two matrices:\n");
scanf("%d%d",&m,&n);
printf("Enter %d X %d first matrix:\n",m,n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("Enter %d X %d second matrix:\n",m,n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i][j+n]=b[i][j];
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<2*n;j++)
printf("\t%d",a[i][j]);
}
getch( );
}
58
Character Array’s or Strings
String is defined as collection of characters defined between double quotes.
Or
String is an array of characters terminated by null character’\0’
“String”
“I believe in war not in morality”
Declaring and initializing string variables
A sting variable is a valid c variable name and is always declaredasan array. The general form of
declaration is
Char string-name[size];
Ex:
char str[10];
char sname[20];
char designation[30];
String library functions:
Strlen,strrev,strcpy,strcmp,strcat,strlwrand strupr
1. strlen( ): This function returns the length of the string that is the number of characters in the
string. strlen(“sai”) returns the value i.e. 3.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
59
Program to find the length of the string
#include<string.h>
main( )
{
char str[20];
int length;
printf(“Enter the string\n”);
scanf(“%s”,&str);
length=strlen(str);
printf(“the length of the string is %d”,length);
getch( );
}
2. strcmp( ): This function is used for comparison of two strings. If the two strings match, strcmp( )
would return a value 0,otherwise it would return a non-zeo value. This function compares the string
character by character.
strcmp(s1,s2) return a value
<0 when s1<=s2
=0 when s1==s2
>0 when s1>s2
Program to find understanding the work of strcmp( ) function
#include<string.h>
main( )
{
char str1[10],str2[10];
printf(“Enter the first string and second string\n”);
scanf(“%s%s”,str1,str2);
if((strcmp(str1,str2))==0)
printf(“strings are same\n”);
else
printf(“strings are not same”);
getch( )
}
3. strcpy( ): This function is used for copying of one string to another string.
strcpy(str1,str2) copy str2 to str1. Here str2 is the source string and str1 is destination string. if
str2=”sai” then this function copy “sai” into str1.
Program to illustrate the function strcpy( )
#include<string.h>
main( )
{
char str1[10],str2[10];
printf(“Enter first and second string\n”):
scanf(“%s%s”,str1,str2);
strcpy(str1,str2);
printf(“now the first string is :%s”,str1);
getch( );
}
4. strcat( ): This function is used for concatenation of two strings. If the first string is “sachin” and
second string is ”tendulkar” then after using this function the resultant string is “sachintendulkar” is
copied into first string.
strcat(str1,str2) concatenates str2 at the end of str1.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
60
Program to illustrate the function strcat( )
#include<string.h>
main( )
{
char str1[10],str2[10];
printf(“Enter first and second string\n”):
scanf(“%s%s”,str1,str2);
strcat(str1,str2);
printf(“the resultant string is :%s”,str1);
getch( );
}
5. strrev( ): This function is used for reverse the given strings. If the first string is “telangana” then
result string will be “anagnalet”
Program to illustrate the function strrev( )
#include<string.h>
main( )
{
char str1[10],str2[10];
printf(“Enter your name:\n”):
scanf(“%s”,str1);
str2=strrev(str1);
printf(“the reverse string is :%s”,str2);
getch( );
}
6. strlwr( ): This function is used for convert the given string to lower case. If the given string is
“TELANGANA” then result string will be “telangana”
7. strupr( ):This function is used for convert the given string to upper case. If the given string is
“telangana” then result string will be “TELANGANA”
Write a program to accept your name and then
a) Display it in upper case
b) Display its length in characters
c) Display its reverse
#include<string.h>
main( )
{
char x[10];
clrscr( );
printf("enetr any string\n");
scanf("%s",x);
printf("\n Upper case of the string:%s\n",strupr(x));
printf("\n Length of the string:%d\n",strlen(x));
printf("\n Reverse of the string:%s",strrev(x));
getch( );
}
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
61
Functions from ctype.h
toupper() Converts a character into uppercase
tolower() Converts a character into lowercase
isdigit()
ctype.h isalpha()
Determines whether the char is digit or not
Determines weather given character is alphabet?
ispunct()
Determines weather given character is punctuation?
isupper()
Determines whether the char is in uppercase
islower()
Determines whether the char is in lowercase
Functions from string.h
String.h
strcat ( )
Concatenates str2 at the end of str1
strcpy ( )
Copies str2 into str1
strlen ( )
Gives the length of str1
strcmp ( )
Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if
str1 > str2
strdup ( )
Duplicates the string
strlwr ( )
Converts string to lowercase
strupr ( )
Converts string to uppercase
strrev ( )
Reverses the given string
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
FUNCTIONS IN C
62
Unit-III
Function definition 1: A function is a self-contained subprogram that it can perform some specific
task.
Function definition 1: A function is a set of statements to perform a specific task.
A C program consists of one or more functions. If a program has only one function then it must be
the main( ) function.
Each funtion defines a specific task of the program. These are used to Simplify the program. By this we
can say functions divide the work of a program,performs logically.
DEFINATION OF FUNCTION OR FUNCTION IMPLEMENTATION:
A function defination will include the following elements.
1. function type.
2. function name.
3. list of parameters.
4. local variable declaration.
5. function statements.
6. return statement.
All these six elements can be grouped in to two parts,namely
1. function header (function type,function name,list of parameters)
2. function body (local variable decleration,function statements,return statements)
The general format of a function definition is:
function_ type function_name (parameter list)
{
local variable declaration;
Executable statement 1;
Executable statement 2;
Executable statement 3;
Return statement;
}
Function _type function_name(perameter list) is known as the function header.
Function header: it consists three parts function type,function name and the formal parameter list
note that: a semicolon is not used at the end of the function header.
Name and type: the function type specifies the type of value (like float or double) that the function is
expected to return the program.
The function name is any valid C identifier (variables,functions arrays) and it must follow the same
rules of variable names in C.
Formal parameter list: the parameter list declares the variables that will receive the data sent by the
calling program the parameters are also known as arguments.
The parameter list contains declaration of variables seperated by commas and surrounded by
paranthesis.
Ex: int sum(int a, int b)
Note: there is no semicolon after closing the paranthesis and the declaration of parameter variables
cannot be combined.
If there is no parameters to indicate that the the parameter list is empty we use the key word void in
between the paranthesis.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
63
void printline (void)
{
--------------------------------------------}
Function body: the function body contains the declarations and statements necessary for performing
the required task. The body enclosed in braces, contains three parts.
1. local variable declaration
2. function statements
3. return statement
Note: 1. when a function reaches its return statement the control is transferred back to the calling
program in the absence of a eturn statement the closing brace acts as a void return.
2. a local variable is a variable that is defined inside the function
Return statement: the return statement is used in function to return a value to the calling function. It
may also be used to an immediate exit from the function to the calling function without returning a
value in which it appear.
Syntax: return(expression)
Here return is the keyword. This statement can appear any where in the body of the function.
Advantages of Functions:
 Functions support modular programming
 Functions reduce programsize
 Use of functions avoid cod eduplication
 Functions provide code reuseability
 Functions can be caled repetatively as per requirement
 A set of functions can be used to form libraries
Types of Functions
C program has two types of functions
1. System defined functions (Library functions)
2. User defined function
1. System defined functions (Library function): these functions are predefined functions that are
available in C. They are already defined and declared in their respective header files. They are the
readily available functions which can be used directly.
The Library functions can be used in any program by includeing respective heder files. The header
files must be included using # include Preprocessor directive. These functions are not required to be
written by the user.
Ex: printf( ), scanf( ),strcmp( ),strlen( ) etc..
2. User defined function: these functions defined by the user that means that user can create the
functions for doing any specific tasks of the program are called as User defined function.
main( ) is the example of user defined function. Every program must have a main function to indicate
where the program has to begin its execution.
Execution of every c program always begins with main( ) function. Each function must be called in the
main( ). After each function has done its operation controlmreturns bacj to the main( ). Then the
remaining statements of main( ) are executed.
The user defined fiunction can be devided into four categories.
1. function with no arguments and no return value
2. function with arguments but no return value
3. function with no arguments but return value
4. function with arguments and return value
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
1. function with no arguments and no return value
fucntion which have function with no arguments and no return value this can be return as
64
main( )
calling function
{
----------------------func( );
function call (function declaration)
----------------------}
func( )
called function (function body)
{
----------------------statements
----------------------}
Here function func( ) is called by the main( ) and the code of the function (body of the function) is
written after main( ) function. As the function func( ) has no arguments main( ) cannot send any data
to func( ) and it has no return statement, hence function cannot return any value to the main( )
Demonstrate a function with no arguments and no return values
#include<stdio.h>
main( )
{
void add( );
clrscr( );
add( );
getch( );
}
void add( )
{
int a,b,c;
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
c=a+b;
printf("Addition of two numbers=%d",c);
}
2. Function with arguments but no return value
These funcions have arguments, hence the calling function can send data to the called function but
it cannot return any value to the calling function as it has no return ststement. This function can be
written as
main( )
{
----------------------int a,b;
func(a,b);
----------------------}
calling function
actual arguments
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
65
func(c,d)
formal arguments
{
----------------------statements
----------------------}
Here a and b are the actual arguments which are used for sending the value. c and d are the
formal arguments which are used to take the values from the actual arguments. It is necessary to
declare the datatype of the formal arguments before the defining the function
Demonstrate a function with arguments but does not return any value
#include<stdio.h>
main( )
{
int a,b;
void add(int,int);
clrscr( );
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
add(a,b);
getch( );
}
void add(int a,int b)
{
int c;
c=a+b;
printf("Addition of two numbers=%d",c);
}
A function may may not send back any value to the calling function, if it does, it is done through the
return ststement.
The return ststement can take the following form
return or return (expression)
3. function with no arguments but return value
This can be written as
main( )
calling function
{
----------------------func( );
----------------------}
func( )
{
----------------------statements
----------------------return (expression)
}
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Demonstrate a function no arguments but return value*
#include<stdio.h>
main( )
{
int c;
clrscr( );
c=add( );
printf("Addition of two numbers =%d",c);
}
add( )
{
int a,b,c;
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
c=a+b;
return(c);
}
4. function with arguments and return value
this can be written as
main( )
calling function
{
----------------------int a,b;
func(a,b);
actual arguments
----------------------}
func(c,d)
formal arguments
int c,d;
{
----------------------statements
----------------------return (expression)
}
Demonstrate a function no arguments but return value
#include<stdio.h>
main( )
{
int a,b,c;
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("Addition of two numbers =%d",c);
}
int add(int a,int b)
{
int c;
c=a+b;
return(c);
}
Prepared by: MD Waseem Raza(MCA-TSSET)
66
https://www.sucomputersforum.com
The different Parameter Passing Techniques
Call by value and call by reference or message passing techniques
Downloaded from:
67
The main objective of passing argument to a function is message passing. The message
passing is also known as communication between two functions i.e, between caller and callee
functions.
There are two methods by which we can pass values to the functions.
I. Call by value or pass by value
II.
Call by reference or pass by reference
(i)
Call by value
In this method actual argument(value) is passed to the formal argument and operation is done
on the formal arguments. If any changes made in the formal arguments then there is no
effect in the actual arguments.
Program to explain call by value
#include<stdio.h>
Void change(int x, int y)
main( )
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
printf(“Before calling the function a and b are %d,\t %d\n”,a,b);
change(a,b);
printf(“After calling the function a and b are %d,\t %d\n”,a,b);
}
void change(int p,int q)
{
p=p+100;
q=q+100;
printf(“In function changes are %d,\t %d\n”,p,q);
}
Out put:Enter a,b values:5 8
before calling the function a and b are 5, 8
in function changes are 105,108
after calling the function a and b are 5,8
(Before calling the function value ( ) the values of a and b are 5 and 8. The variables a and b are passed
as parameters in the function value( ).
The values of a and b are passed to p and q. but the memory locations of p and q are different from the
memory locations of a and b.
So that when the values of p and q are incremented then there is no effect on the values of a and b. so
after calling the function the values of a and b are same as before calling the function i.e. a=5 and b=8.
(ii)
Call by reference
In call by reference method, instead of the values, addresses of the variable are passed. In
this value of variables are effected by changing the value of the formal parameter.
Program to explain call by reference
#include<stdio.h>
void change(int *p,*q);
void main( )
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
68
printf(“before calling the function a and b are %d,\t %d\n”,a,b);
change(&a,&b);
printf(“after calling the function a and b are%d,\t %d\n”,a,b);
getch( );
}
void change(int *p,int *q)
{
*p=*p+100; *q=*q+100;
printf(“in function changes are %d,%d\n”,*p,*q);
}
Out put:Enter a,b values5 10
before calling the function a and b are 5,10
In function changes are 15, 20
After calling the function a and b are 15, 20
(Before calling the function ref( ) the values of a and b are 5 and 10. The address of the variables a and
b are passed as parameters in the function ref( ).
The address of a & b are passed to p & q, which is a pointer variable.*p=*p+10 means value at address
is incremented. So the value at address 1000 which is 5 incremented. Similarly *q=*q+10 means 10 is
incremented. Now the value of *p=15 and *q=20.
Here the address is not changed but the value at this address is changed. Hence after calling the
function the value of the variable a and b are changed.
Note: in call by reference that we can interchange the variable in function. Now the value of variables
will also be interchanged after calling the function.
Types of variables
C supports two types of variables
A. Local variables
B. Global variables
Local variables
The variables which are defined within a body of the function or block is called as local
variables. These variables belongs to that particular function or block.
Program for illustration of local variables
void func1( );
void func2( );
main( )
{
int t=1000;
/* local to main( ) function block only*/
clrscr( );
func2( );
printf(“\n%d”,t);
}
void func1( )
{
int t=10;
/*local to func1( ) only*/
printf(“%d”,t);
}
void func2( )
{
int t=100;
/*local to func2( ) only*/
func1( );
printf(“\n %d”,t);
}
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
69
In the above program the same variable ‘t’ used in main ( ) block, func1 ( ) and func2 ( ) i.e. in
the main ( ) block the value of t=1000 is available to main ( ) function block only. In the func1 ( ) the
value of t=10 is available to func1 ( ) block only and in the func2 ( ) the value of t=100 is available to
func2 ( ) block only.
Global variables
The variables which are defined outside the main() function is called as global variables. The
global variables have the same data type and same name throughout the program.
Program for illustration of global variables
int a=8,b=6;
main( )
{
int c=a+b;
printf(“the sum of the two numbers=%d\n”,c);
func( );
}
func( )
int c=a*b;
printf(the multiplication of two numbers=%d”,c);
}
In the above program the global variables are a and b and these variables are available to main
( ) function block and also func ( ) block i.e. the global variables are available to all the functions and
blocks which are declared with in the program.
In the above program the variable c is called local variable.
INLINE FUNCTIONS or THE C PREPROCESSORS
Preprocessor is a program that processes our source program before it is passed to the
compiler.
The preprocessor offers several features called preprocessor directives. These directives begin
with # symbol. These directives can be placed any where in the program. But they are generally
written at the beginning of a program, before the first function definition.
The preprocessor directives are
1. Macro expansion
2. File inclusion
3. Conditional compilation
4. Miscellaneous directives.
1. Macro expansion:
Ex:
#define UP 25
main( )
{
int I;
for(i=1;i<=UP;i++)
printf(“\n%d”,i);
getch( );
}
In the above program instead of writing 25 in the for loop we are writing UP. Because it is
already defined before the main through the statement i.e #define UP 25. This statement is called as
macro definition or macro. During preprocessing the preprocessor replaces every occurance of UP in
the program with 25.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
70
Ex:
#define PI 3.1415
main( )
{
float r=6.25;
float area;f
area=PI*r*r;
printf(“\n area of circle=%f”,area);
getch( );
}
In the above programs PI and UP are called macro templates where as 25 and 3.1415 are called macro
expansions.
When we compile a program before the source code causes to the compiler it is examined by the c
preprocessor for any macro defination. When the #define directive found then the compiler goes
through the entire program for macro templates. If they found it replaces the macro template with
macro expansion. Then the program goes to compiler.
Macro template and macro expansion are separated by blank space. The macro definition never ends
with a semicolon.
By using #define can produce more efficient and more easily understandable programs.
A #define directive could be used even to replace anoperator, condition and even an entire c
statement.
#define AND &&
#define RANGE(a>25 AND a<=50)
#define FOUND printf(“with in range”);
main( )
{
int a=30;
if(RANGE)
FOUND
else
printf(“out of range”);
}
Macros with arguments:
Functions can have arguments. In the similar way macros also can have arguments.
Ex:#define AREA(x) (3.14*x*x)
main( )
{
foat r1=6.25,r2=2.5,a;
a=AREA(r1);
printf(“\n area of the circle=%f”,a);
a=AREA(r2);
printf(“\n area of the circle=%f”,a);
getch( );
}
In the above program the statement AREA (r1) causes the variable r1 to be substituted for x. So that
AREA (r1) is equalent to 3.14*r1*r1.
 No blank spaces are inserted between macro template and its argument while defining a
macro.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
71
Ex: in the above program there is no blank space between AREA and (x) in the definition. If we
insert a blank space inbetween these two then the (x) is one of he part of macro expansion should
be enclosed with in the parantheses
Ex:
#define SQUARE(n) n*n
main( )
{
int j;
j=64/SQUARE(4);
printf(“j=%d”,j);
}
Output: j=64. Because the macro expansion not written in the parantheses. So that in the above
program macro template not replaced with macro expansion.
If the macro expansion in the above program written with in the parantheses then the output will
be j=4.
File inclusion/#include directive:
The second preprocessor directive i.e file inclusion causes one file to be included in another
file. To include a file in another file i.e the preprocessor command for file inclusion can be written
like
#include”file name”
Whenever we write like this then the entire contents of file name to be inserted into the source
code at that point in the program.
The file inclusion is used whenever if we have a large program, then it is better to devide in to
several different files. Each file must contain a set of related functions. And these files are included
at the beginning of the main program file.
The file name isshould be enclosed with in the double quotation marks.So that the compiler
search that file in the current directory and as well as a specified list of directories.
first.c
msg1( )
{
printf(“good morning\n”);
}
msg2( )
{
printf(“good afternoon\n”);
}
msg3( )
second.c
#include “first.c”
main( )
{
clrscr( );
msg1( );
msg2( );
msg3( );
}
printf(“good evening\n”);
}
Prepared by: MD Waseem Raza(MCA-TSSET)
https://www.sucomputersforum.com
Recursion, Recursive function
Downloaded from:
72
A function is called ‘recursive’ if a statement within the body of a function calls the same
function i.e. a function calls itself.
Ex: factorial of a value means the product of all the integers between 1 and that number for example 4
factorial is 4*3*2*1 it can be written as 4!where stands for factorial.
Syntax:
main ( )
{
---------------------func( );
---------------------}
func( )
--------------------func( );
--------------------}
Program for printing the factorial value of a given number using recursion
main( )
{
int n,fact;
printf(“Enter any number\n”);
scanf(“%d”,&n);
fact=rec(n);
printf(“factorial valueof %d is %d”,n,fact);
}
rec(int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}
Limitations of Recursion
1. Recusrsive solutions may involve extensive overhead because they use function calls. Each
function call requies push of return memory address, parameters returned result, etc. and
every function return requires that many pops.
2. Each time you call a function you use up some of your memory allocation may be in stack heap.
If theer are large number of recursive calls then you may run out of memory.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
DIFFERENCE BETWEEN RECURSION AND ITERATION
73
The difference between recursion and iteration are explained below:
Iteration
Recursion
1. Iteration uses repetition control structure 1. Recursion uses selection control structure
2. Recursion achieves repetition through
called loops
repeated function calls
2. Iteration explicitly uses a repetition control
3. Recursion terminates when a base case is
structure
recognized.
3. Iteration terminates when loop continuation 4. Recursion produce simpler versions of the
condition fails
original problem until the base condition is
4. Iteration modifies the counter until the
reached
counter value reaches to fail the loop 5. Infinite recursion occurs if the recursion step
does not reduce the problem during each
repetition condition
recursive call to reach the base condition
5. An infinite loop occurs with iteration when
6. Due to the repeated function calls in
the loop continuation test never becomes
recursion, it may take more processing time
false.
and memory space.
6. As iteration normally occurs within a
Example :
function so it may not take more processing
long factorial(long n)
{
time and memory space.
if(n < 2)
Example :
return
n;
long factorial(long n)
else
{ long f=1,i;
return
n*factorial(n - 1);
for(i=1;i<=n;i++)
}
f=f*i;
return f;
}
Arrays as function argument
Array elements can be passed to a function by calling the function by value or by reference.
In the call by value we pass values of array elements to the function, where as in the call by reference
we pass addresses of array elements to the function.
Program for demonstration of call by value
main( )
{
int i;
int marks[]=(55,65,75,85,95,35,66};
for(i=0;i<=6;i++)
display(marks[i];
getch( );
}
display( int m)
{
printf(“%d”,m);
}
Output: 55 65 75 85 95 35 66
Here, we are passing an individual array element at a time to the function display( ) and getting it
printed in the function display( ). Note that since at a time only one element is being passed. This
element is collected in an ordinary integer variable m in the function display( ).
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
74
Sending a function as argument to another function
It is also possible to send a function as argument to another function in C. The below program
demonstrates the concept of sending a function as argument to another.
#include<stdio.h>
int double1(int d);
int square(int k);
void main()
{
int a=5,b;
b=double1(square(a));
printf(“b=%d”,b);
}
Int double1(int p)
{
return(p*2);
}
int square(int q)
{
return(q*q);
}
Output: 50
Standard functions in header files
Each ‘C’ program must contain the standard header file i.e. #include<stdio.h> at the beginning
of the program. But it is not necessary for the functions printf ( ) and scanf ( ) because these are
defined as a part of the C language.
The file name stdio.h means standard input output header file. This file tells the compiler to
search for a file i.e. stdio.h and place its contents in the program. So the contents of the header file
become the part of the source code when it is compiled.
Reading a character: to read a single character from the keyboard we can use the function getchar (
); (this can also be done with the help of the scanf ( ) function)
The general form of the getchar ( ) function
Variable-name=getchar ( );
where variable-name is a valid C name that has been declared as char type, when this
statement is executed the computer waits until a key is pressed and then assigns this character as a
value to getchar ( ) function, because getchar ( ) function written at the right hand side of the =, the
character value of getchar ( ) assigned to the variable name on the left hand side of =.
Ex: char a;
a=getchar ( );
If we press the key ‘m’ then it assigns to the variable name i.e. ‘a’
Program for getchar ( ) function*/
#include<stdio.h>
main( )
{
char answer;
printf(“would you like to know my name\n”);
printf(“type Y for yes and N for no\n”);
answer=getchar( );
if(answer==’Y’|| answer==’y’)
{
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
75
printf(“my name is C language”);
}
else
{
printf(“your are good for nothing”);
}
getch( );
}
Program to requests the user to Enter a character and display a message on the screen telling
the user whether the character is an alphabet or digit or any other special character.
To test whether the Entered character is an alphabet or digit, we can use the following functions
isalpha(character);
isdigit(character);
These character functions are contained in the file <ctype.h> so that, the statements
#include<ctype.h> must be included in this program.
#include<ctype.h>
#include<stdio.h>
main( )
{
char ch;
printf(“press any key\n”);
ch=getchar( );
if(isalpha(ch)>0)
printf(“the character is an alphabet”);
else if(isdigit(ch)>0)
printf(“the character is digit”);
else
printf(“the character is a special symbol”);
getch( );
}
The isalpha( ) function assumes a non-zero value (true) if the Entered character is alphabet.
Otherwise it assumes zero value (false) similarly isdigit( ) function.
Writing a character: like getchar( ) there is another similar function putchar( ) for writing a
character one at a time to the screen.
The general form of the putchar( ) function
putchar(variable name);
Where variable name is character type variable.
This statement displays the character contained in the variable name.
Ex: answer=’y’;
putchar(answer); It will display the character ‘y’ on to the screen.
Program to read a character from the keyboard and then print it reverse case.
In the program we use three functions islower( ), to upper( ) and tolower( ).
Here islower( ) is a conditional function and takes the value true if the argument is a lowercase
alphabet otherwise takes the value false. The function toupper( ) converts the lowercase argument
into uppercase. The function tolower converts uppercase into lowercase.
#include<ctype.h>
#include<stdio.h>
main( )
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
{
https://www.sucomputersforum.com
76
char alphabet;
printf(“Enter an alphabet”);
putchar(“\n”);
alphabet=getchar( );
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
getch( );
}
Functions from math.h
Header file function
Sqrt
Pow
Sin
Cos
Abs
math.h
Ceil
Floor
Exp
Log
Log 10
strlen
strcpy
strrev
string.h
strcmp
strupr
strlwr
printf
stdio.h
Scanf
toupper
tolower
isdigit
ctype.h
Isalpha
Ispunct
isupper
islower
Meaning
Finds square root of a number
Finds power i.e. X to the power of Y
Computes sin value of given radians
Computes cos value of given radians
Returns the absolute value of x
Returns smallest integer value greater than or equal to x
Returns largest integer value greater than or equal to x
Returns the value of e raised to x
Returns the natural logarithm (base e)
Returns the common logarithm (base 10)
Finds the length of a string
Copies one string to another string
Reverses a string
Compares two strings
Converts a string into uppercase
Converts a string into lowercase
To print the formatted text on the screen
To read the formatted text from the keyboard
Converts a character into uppercase
Converts a character into lowercase
Determines whether the char is digit or not
Determines weather given character is alphabet?
Determines weather given character is punctuation?
Determines whether the char is in uppercase
Determines whether the char is in lowercase
Other functions of Stdio.h
1. getchar( ): This function read character type data from standard input. This function read one
character at a time.
Syntax: variable-name=getchar( );
2. putchar( ): This function print one character at a time which is taken by the standard input.
Syntax: putchar(variablename);
Program to understand the use of getchar( ) and putchar( ) functions
#include<stdio.h>
main( )
{
char ch;
printf(“Enter any character\n”):
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
ch=getchar( );
printf(“the character is:”);
putchar(ch);
getch( );
77
}
Output: Enter any character M (press the Enter key)
The character is: M
3. getch( ): This function read any alphanumeric character from the standard input.
The difference between getchar( ) and getch ( ) is that getchar( ) continue access the keyboard until
the carriage return key (Enter key) is pressed. It stops the accessing the keyboard as soon as the key is
pressed. getch( ) works as, if any key pressed in the keyboard the accessing will be stopped. i.e. the
Entered character will not be displayed.
Syntax: variable-name=getch( );
4. putch( ): This function print any alphanumeric character which is Entered from the standard input.
Syntax: putch(variable name);
Program to understand the use of getch( ) and putch( ) functions
#include<stdio.h>
main( )
{
char ch;
printf(“Enter any character\n”):
ch=getch( );
printf(“the character is:”);
putch(ch);
getch( );
}
Output: Enter any character (we need not press the Enter key)
The character is: M
5. getche( ): This function reads a character from the keyboard and we need not press the Enter key.
It displays the Entered character that we are typed.
Program to understand the use of getche( ) functions
#include<stdio.h>
main( )
{
char ch;
printf(“Enter any character :\n”):
ch=getche( );
printf(“the character is:”);
putch(ch);
getch( );
}
Output: Enter any character M (we need not press the Enter key)
The character is: M
2. String input/output functions:
1. sscanf( ): This function is same as the scanf function except that data is read from the memory
pointed by array rather than the standard input
Syntax: sscanf(array name,”control character”,variable name);
Program to understand the use of sscanf function
#include<stdio.h>
main( )
{
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
78
char arr[20];
static int i;
static char x;
printf(“Enter i and x values\n”);
gets(arr);
sscanf(arr,"%d\t%c\n",i,x);
printf("%s\n",arr);
}
Output: Enter i and x values
6C
6C
2. sprintf( ): This function is same as printf function except that instead of sending output on the
screen. This will writes the output to an array.
Syntax: sprintf(array name,”control character”,variable name);
Program to understand the use of sprintf function
main( )
{
char arr[20];
int i=6;
float x=3.5;
clrscr( );
sprintf(arr,"%d %f",i,x);
printf("%s\n",arr);
getch( );
}
Output: 6 3.500000
3. gets( ): This function reads the character from standard input and store them in a character type
array.
Syntax: gets(array-name);
4. puts: This function prints the string which is already accepted in the character array.
Syntax: puts(array-name);
Program to understand the use of gets( ) and puts( ) functions
main( )
{
char arr[25];
clrscr( );
printf("Enter the string\n");
gets(arr);
printf("the accepted string is:");
puts(arr);
getch( );
}
Output: Enter the string sri vidyajyothi degree college
the accepted string is sri vidyajyothi degree college
3. file input output functions:
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
79
1. fprintf( ): This function is same as the printf( ) function but it writes the data into the file, so it has
one more parameter that is the file pointer.
Syntax: fprintf(fptr,”control character”,variablename);
Program to understand fprintf( ) function
#include<stdio.h>
main( )
{
FILE *fopen( ),*p;
char name[10];
float sal;
p=fopen("rec.txt","w");
printf("Enter your name:\n");
scanf("%s",name);
printf("Enter your salary:\n");
scanf("%f",&sal);
fprintf(p,"%s %f",name,sal);
fclose(p);
}
Output: Enter your name
Sindhu
Enter your salary
5000
2. fscanf( ): This function is same as the scanf( ) function but this reads the data from the file, so this
has one more parameter that is the file pointer.
Syntax: fscanf(fptr,”control character”,&vaiable-name)
Program to understand the use of fscanf( ) function/
#include<stdio.h>
main( )
{
FILE *p,*fopen( );
char name[20];
float sal;
clrscr( );
p=fopen("rec.txt","r");
fscanf(p,"%s %f", name,&sal);
printf("name\tsal\n");
while(!feof(p))
{
printf("%s\t %f",name,sal);
fscanf(p,"%s %f",name,&sal);
}
fclose(p);
}
Output:
name
sal
Sindhu
5000.000000
3. getc( ): The getc( )is a macro which is used to read a single character from a given file and
inclement the filepointer. It returns EOF, if the end of file is reached or it encounters an error.
Syntax: getc(fptr);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
80
ch=getc(fptr);
Where fptr is a file pointer
Programto understand the use of getc( ) function
#include<stdio.h>
main( )
{
FILE *p,*fopen( );
char name[20];
char ch;
clrscr( );
printf("Enter the file name \n");
scanf("%s",name);
if((p=fopen(name,"r"))==NULL)
{
printf("file does not exist");
exit( );
}
else
{
while((ch=getc(p))!=EOF)
printf("%c",ch);
}
fclose(p);
}
Output: Enter the file name
rec.txt
(Then it displays the contents exist in the filename rec.txt)
4. putc( ): The putc( ) macro is used to write a single character into a file. It returns the value of EOF if
an error occurs.
Syntax: putc(ch,ptr);
Where ptr is a file pointer and ch is a variable written to the file which is pointed by file pointer.
Program to understand the use of putc( ) function
#include<stdio.h>
main( )
{
FILE *p;
char name[20];
char ch;
printf("Enter the file name \n");
scanf("%s",name);
if((p=fopen(name,"w"))==NULL)
{
printf("file cannot be open");
exit( );
}
else
{
while((ch=getchar( ))!=EOF)
putc(ch,p);
}
fclose(p);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
81
}
Output: Enter the file name
rec.txt and then type the text (data) that you want and press ctrl+z
5. fgetc( ): This function is same as the getc( ) function. It is also read a single character from a given
file and increments the file pointer position. It returns EOF if end of file is reached or it encounters an
error.
Syntax: fgetc(fptr);
Ch=fgetc(fptr);
Where fptr is a file pointer and ch is a variable which receive the character returned by the function.
Program to understand the use of fgetc( ) function
#include<stdio.h>
main( )
{
FILE *fopen( ),*p;
char ch;
clrscr( );
if((p=fopen("k2.c","r"))==NULL)
printf("this file does't exist");
else
{
while((ch=fgetc(p))!=EOF)
printf("%c",ch);
}
fclose(p);
}
Output: the contents of the file k2.c will be displayed on to the screen.
6. fputc( ): This function writes the character to the specified stream at the current file position and
then increments the file position indicator.
Syntax: fputc(ch,fptr);
Where fptr is a file pointer and ch is a variable written to the file which is pointed by file pointer.
Program to understand the use of fputc( ) function
#include<stdio.h>
main( )
{
FILE *p,*p1;
char name[20];
char ch;
clrscr( );
printf("Enter the file name \n;
scanf("%s",name);
if((p=fopen(name,"r"))==NULL)
{
printf("file does not exist");
exit( );
}
else
{
p1=fopen("NSVDC.txt","w");
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
82
while((ch=fgetc(p))!=EOF)
fputc(ch,p1);
}
fclose(p);
fclose(p1);
getch( );
}
Output: Enter the file name
nsv.txt
It is useful to store the block of data into the file rather than individual elements. Each block
has some fixed size; it may be of structure or of an array. It is possible that a data file has one or more
structures or arrays. So it is easy to read the entire block from file or write the entire block to the file.
There are two functions fread( ) and fwrite( ) to do this
1. fread( ): This function is used to read an entire block from a given file.
Syntax: fread(ptr,size,nst,fptr);
Where ptr is a pointer which points to the array and receives the structure, size is the size of the
structure, nst is the number of structures and fptr is a file pointer.
Program to understand the use of fread( ) function
#include<stdio.h>
main( )
{
struct rec
{
int code;
char name[20];
}person[10];
FILE *fptr;
int i=0;
int j;
char str[15];
printf("Enter the file name\n");
scanf("%s",str);
if((fptr=fopen(str,"r"))==NULL)
{
printf("file does't exist\n");
exit( );
}
else
while(!feof(fptr))
{
fread(&person,sizeof(person),1,fptr);
i++;
}
for(j=0;j<=i;j++)
{
printf("code:%d\t",person[j].code);
printf("name:%s\n",person[j].name);
}
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
83
fclose(fptr);
getch( );
}
Output: Enter the file name
NSVDC.txt
code: 2201 name:Sidra
code:2202 name:Raza
2. fwrite( ): This function is used for writing an entire block to a given file.
Syntax: fwrite(ptr,size,nst,fptr);
Where ptris a pointer which pointsto the array of structure in which data is written, size is the size of
the structure, nst is the number of structures and fptr is the file pointer.
Program to understand the use of fwrite ( ) function
#include<stdio.h>
main( )
{
struct rec
{
int code;
char name[20];
}person[10];
FILE *p;
int i,j=0,n;
char str[15];
clrscr( );
printf("Enter the file name\n");
scanf("%s",str);
if((p=fopen(str,"w"))==NULL)
{
printf("file does't exist\n");
exit( );
}
else
{
printf("how many records:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("code:");
scanf("%d",&person[i].code);
printf("name:");
scanf("%s",&person[j].name);
}
while(j<n)
{
fwrite(&person,sizeof(person),1,p);
j++;
}
}
fclose(p);
}
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
Output: Enterthe file name
nsv.txt
how many records:2
code:2201
name:Sidra
code:2202
name:Raza
84
Storage classes in C
To define a variable fully needs to mention not only it’s type but also it’s storage class.
A variable storage class tells us
1. Where the variable would be stored
2. What will be the initial value of the variable?
3. What is the scope of the variable, i.e. in which function the value of the variable would be available
4. What is life of the variable, i.e how long the variable exists?
There are four types of storage classes in C
1. Automatic Storage Class
2. Register Storage Class
3. Static Storage Class
4. External Storage Class
1. Automatic Storage Class: The features of a variable whenever it is declared as automatic storage
class are
Storage
:
Memory
Default initial value
:
Garbage Value (unknown value)
Scope
:
local to the block in which the variable is defined
Life
:
Till the control remains within the block in
which the variable is defend
Note: the keyword “auto” can be used to declare the automatic storage class
main( )
{
auto int i,j;
printf(\n%d%d”,i,j);
getch( );
}
Output: i and j values are garbage values, i and j are stored in memory
1. Write a program to demonstrate the scope
2. Write a program to demonstrate the scope
and life of an automatic variable
and life of an automatic variable
main( )
main( )
{
{
auto int i=1;
auto int i=1;
{{ {
{
auto int i=2;
printf(“\n i=%d”,i);
{
auto int i=3;
}
printf(“\n i=%d”,i);
printf(\n i=%d”,i);
}
}
printf(\n i=%d”,i);
printf(\n i=%d”,i);
}
}
printf(\n i=%d”,i);
}
}
Output:
i=1
Output:
i=3
i=1
i=2
i=1
i=1
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
85
2. Register Storage Class: The features of a variable whenever it is declared as register storage class
are
Storage
: CPU registers
Default initial value : Garbage Value (unknown value)
Scope
: local to the block in which the variable is defined
Life
: Till the control remains within the block in which the variable is defend
Note: the keyword “register” can be used to declare the register stooge class
The values can be accessed very fast which are stored in the CPU registers compared with the values
stored in the memory. Generally the register storage class can be used in loops.
Ex: write a program to print 1 to 10 numbers
main( )
{
register int I;
for(i=1;i<=10;i++)
printf(“\n%d”,i);
}
Output: the program displays 1to 10 numbers
Here, even though we have declared the storage class of I as register, we cannot say for sure that the
value of i would be stored in the CPU registers, why because the number of CPU registers are limited
and they may be busy doing some other work.
We cannot use the register storage class for all the data types
for example the following declaration is wrong.
register float;
register double;
register long double;
3. Static Storage Class: The features of a variable whenever it is declared as Static storage class are
Storage
:
Memory
Default initial value
:
Zero
Scope
:
local to the block in which the variable is defined
Life
:
value of the variable exist between different function Calls
Note: /*the keyword “static” can be used to declare the static storage class */
Program to demonstrate scope and life of static storage class and automatic storage class.
main( )
{
increment( );
increment( );
increment( );
}
increment( );
{
auto int i=1;
printf(“i=%d\n”,i);
i=i+1;
}
Prepared by: MD Waseem Raza(MCA-TSSET)
main( )
{
increment( );
increment( );
increment( );
}
increment( );
{
static int i=1;
printf(“i=%d\n”,i);
i=i+1;
}
Downloaded from:
Ouput:
https://www.sucomputersforum.com
i=1
i=1
i=1
Ouput:
86
i=1
i=2
i=3
Note: In the above example, when variable i is auto, each time increment( ) is called it is reinitialized to one. When the function terminates, I value i.e. 2 will be lost as the result how many times
we call increment( ), i is initialized to 1 every time. Where as if i is static, it is initialized to 1 only
once. It is never initialized again. Because i is static the changed value exist between different function
calls.
4. External storage class: - The features of a variable whenever it is declared as Static storage class
are
Storage
:
Memory
Default initial value
:
Zero
Scope
:
Global
Life
:
As long as the program execution does not come to an end.
The variables are declared before the main( ) function are by default external variables. Then it is not
necessary to declare the external keyword.
Program for illustration of external storage class
int i;
main( )
{
printf(“\ni=%d”,i);
increment( );
increment( );
decrement( );
decrement( );
}
increment( )
{
i=i+1;
printf(“\n on incrementing i=%d”,i);
}
decrement( )
{
i=i+1;
printf(“\n on incrementing i=%d”,i);
}
Out put:
i=0
on incrementing i=1
on incrementing i=2
on decrementing i=1
on decrementing i=0
Situations of using Storage Classes
Use static storage class only if you want the value of a variable to persist between different
functions calls. Generally static variables are used in recursive functions
Use register storage class for the variables which are being used very often in the program
Use extern storage class for the variables which are being used by almost all functions in the
program. If you do not have express needs mentioned above use automatic storage class
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
POINTERS
87
The computer’s memory is a sequential collection of storage cells, each cell is known as byte. It has
a number called address associated 0with it.
Sum Variable
50
value
3000
address
These addresses are numbered consecutively, starting from ‘0’. The last address depends up on the
memory size.
Ex: a computer system having 64 k memory will have its last address as 65535.
Memory cell
address
0
1
2
3
65535
Whenever we declare a variable, the system allocates somewhere in the memory in an
appropriate location to hold the value of the variable. Since every byte has a unique address number,
this location will have its unique number.
Ex: int sum =50 . This statement instructs the system to find a location for the integer variable sum
and put the value 50 in that location. If the system allocated the address location 3000 for sum.
So that we can represent this in figure like
Variable
Sum |
X
|
value
50
|
3000 |
address
3000
5000
We can access the value 50 by using either the name sum or the address 3000. Because
memory addresses are numbers. So that they can be assigned to some other variables, that can be
stored in memory like any other variable. Such variable that hold memory addresses are called
pointer variables.
Def: - A pointer is nothing but it is a variable that contains an address, which is a location of another
variable in memory.
If we assign the address of variable sum to variable x. The link between the variable x and sum can be
like x=&sum=50
Since the value of the variable x is the address of the variable sum. We can access the value of
sum by using the value of x and therefore we can say that the variable x points to the variable sum. So
that x gets the name pointer.
Advantages by using pointers
1. Pointer is used for saving memory space.
2. By using pointers, assigns the memory space and also releases it. This concept helps in making the
best use of the available memory. (Dynamic memory allocation means the memory allocated at
run time).
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
3.
4.
5.
6.
7.
https://www.sucomputersforum.com
88
With pointer data manipulation is done with address, so the execution time is faster.
The two dimensional and multi dimensional array representation is easy with pointers.
Pointers reduce the length and complexity of the programs.
By using pointers increases the execution speed so that it will reduce the program execution time.
Pointer concept is used with data structures such as linked list, stacks, queues and trees.
Address of operator(&): Accessing the address of a variable
The address of a variable is not known to us immediately. Because actual location of the variable in
the memory is system dependent. To know the address of a variable we can use the operator “&” . This
operator we have already used in scanf statement. Whenever we use this operator before a variable
then it returns the address of the variable.
Ex: m=&sum.
This will assigns the address 3000(the location of sum) to the variable m. This operator & is known as
“address of operator”.
Declaration of pointer
The pointer variable must be declared before we use them. The general form is
data _type *pt_name;
This declaration tells three things about the variable pt_name.
1.
the asterisk(*) tells that the variable pt_name is a pointer variable.
2.
pt_name needs a memory location.
3.
pt_name points to a variable of type data type.
Ex: int *p;
This declares the variable as a pointer variable. That points to an integer datatype.
Initialization of a pointer variable
The process of assigning the address of a variable to a pointer variable is must be initialized
before they are used in the program. The un initialized pointer will produce unknown result.
Once a pointer variable has been declared we can use the assignment operator to initializing the
variable.
Ex: int sum;
int *p;
declaration
p=∑
initialization
The variable must be declared before the initialization.
Write a program to print the address of a variable along with its value
#include<stdio.h>
main( )
{
char a= ‘A’;
int x=125;
float p=10.25,q=3.14;
printf(“%c is stored at address %u\n %d is stored at address %u\n”,a,&a,x,&x);
printf(“%f is stored at address %u\n %f is stored at address %u\n”,p,&p,q,&q);
}
Output: A is stored at address 4436
125 is stored at address 4435
10.25 is stored at address 2341
3.14 is stored at address 5423
The ‘*’ operator is the value at address operator. It represents the value at the specified address.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
89
Ex:
#include <stdio.h>
main( )
{
int a=5;
printf(“value of a=%d\n”,a);
printf(“address of a=%u\n”,&a);
printf(“value at address %u=%d”,&a,*(&a));
}
Output: value of a=5
address of a=2000
value at address 2000=5
Write a program for initialization and declaration of a pointer
#include<stdio.h>
main( )
{
int a=5;
int *b;
b=&a;
printf(“value of a=%d\n”,a);
printf(“value of a=%d\n”,*(&a));
printf(“value of a=%d\n”,*b);
printf(“address of a=%u\n”,&a);
printf(“address of a=%u\n”,b);
printf(“address of b=%u\n”,&b);
}
Output:
value of a=5
value of a=5
value of a=5
address of a=2000
address of a=2000
address of b=3000
Pointer to pointer
Pointer is a variable that contains the address of the another variable. Similarly another
pointer variable can store the address of this pointer variable. So that we can say this is a pointer to
pointer variable.
Ex:
main( )
{
int a=5 ,*b, **c;
b=&a;
c=&b;
printf(“value of a=%d\n”,a);
printf(“value at address of a is=%d\n”,*(&a));
printf(“value of a=%d\n value of a=%d\n”,*b,**c);
printf(“value of b= address of a=%u%d\n”,b);
printf(“value of c= address of b=%u\n”,c);
printf(“address of a= %u\n address of a= %u\n”,&a,b);
printf(“address of a= %u\n address of b= %u\n”,*c,&b);
printf(“address of b= %u\n”,c);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
90
printf(“address of c= %u\n”,&c);
getch( );
}
Output:
value of a=5
value of a=5
value of a=5
value of a=5
value of b=2000 address of a= 2000
value of c=3000 address of b= 3000
address of a=2000
address of a=2000
address of a=2000
address of b=3000
address of b=3000
address of c=4000
Explanation:
a
b
c
5
2000
3000
2000
3000
4000
Here ‘b’ is a pointer variable which contains the address of the variable ‘a’. ‘c’ is a pointer to pointer
variable, which contains the address of the pointer variable ‘b’.
Pointers to functions
Similar to a variable, a function also holds an address in the memory. So we can declare a
pointer to a function, which can then be used as an argument in another function. A pointer to
function is declared as follows:
type(*fptr)( )
This tells the compiler that *fptr is a pointer to a function which returns type value. The parenthesis
around *fptr are necessary.
The below program demonstrates pointer to function concept:
#include<stdio.h>
void my_int_func(int x)
{
printf(“%d\n”,x);
}
main()
{
void (*foo)(int);
foo=&my_int_func;
/*call my_int_func(note that you do not need to write (*foo)(2);*/
/* but if you want */
(*foo)(2);
}
Pointers and array
Array is a collection of similar data type elements. When we declare an array then consecutive
memory locations are allocated to the array elements. The base address of array is the address of the
0th element of the array. The name of array also gives the base address of the array.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
91
Ex: int arr[4]={5,10,15,20}
Here arr[4] means that array ‘arr’ has 4 elements and is of int data type.
arr[0]
arr[1]
arr[2]
arr[3]
1000
1002
1004
1006
Here the base address of the array is the address of the 0 th element of the array. Since the array
is of type int, hence the address of the next element of the array is incremented by 2.
Following are two main points to understand the concept of pointer with array.
1. Elements of array are stored in the consecutive memory location.
2. When an array pointer is incremented it refers to the next location of its data type.
Ex: int arr[4]={5,10,15,20};
Int *a;
a=arr;
This shows ‘a’ is a pointer variable which holds the base address of the array arr or a=&arr[0];
When pointer variable is incremented by 1 then it contains the base address +2 because the pointer is
of type int. the address of the next element will be also base address +2, because elements of array are
stored in consecutive memory locations.
Program to print the value and address of the element*/
main( )
{
int arr[4]={5,10,15,20};
int i;
for(i=0;i<4;i++)
{
printf(“value of arr[ %d]=%d\n”,i,arr[i]);
printf(“value of arr[ %d]=%u\n”,i,&arr[i]);
}
}
Using pointer to print the value and address of array elements?
main( )
{
int arr[4]={5,10,15,20};
int *b,i;
b=arr; (or) b=&arr[0];
for(i=0;i<4;i++)
{
printf(“value of arr[ %d]=%d\n”,i,*b);
printf(“value of arr[ %d]=%u\n”,i,b]);
}
}
Here b is a pointer variable. b= arr means the base address are given to the pointer variable ‘b’.
*b gives the value at address. ‘b’ gives the address of the array element. When ‘b’ is incremented then
it holds the address of the next element of array and *b gives the value at this address.
Array of pointer
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
92
We can also declare an array as a pointer. Every element of this array can hold address of any
variable. so we can say every element of this array is a pointer variable. it is same as array but it
contains the collection of addresses.
Program for understanding the concept of array of pointers*/
main( )
{
int *arr[3];
int a=5,b=10,c=15,i;
arr[0]=&a;
arr[1]=&b;
arr[2]=&c;
for(i=0;i<3;i++)
{
printf(“address =%u\t”,arr[i]);
printf(“value =%d\n”,*arr[i]);
}
getch( );
}
Output: address=1000
address=2000
address=3000
a
b
c
5
1000
10
2000
value=5
value=10
value=15
15
3000
arr[0] arr[1] arr[2]
1000
2000
3000
5000 6000 7000
Note: the array of pointer can also contains the address of another array
Program to understand this concept.
main( )
{
static int arr[4]={5,10,15,20};
static int a[4]={arr,arr+1,arr+2,arr+3};
int j,**b;
b=a;
for(j=0;j<4;j++)
{
printf(“address =%u\t”,*b);
printf(“value =%d\n”,**b]);
}
}
Here ‘a’ is declared as array of pointer. Each element of this array pointer contains the address
of the each element of array ‘arr’.
‘b’ is declared as pointer to pointer variable, which contains the address of the pointer array ‘a’.
arr[0]
arr[1]
arr[2]
arr[3]
5
10
15
20
1000
1002
1004
1006
Prepared by: MD Waseem Raza(MCA-TSSET)
https://www.sucomputersforum.com
Downloaded from:
a[0]
1000
a[1]
1002
a[2]
1004
93
a[3]
1006
b
1000
2000
Pointer and strings: a string is a collection of characters that are stored in the character array. Every
string is terminated (end) with the ‘\0’ (null character). It is automatically inserted at the end of every
string.
Ex: char arr[10]={‘a’,’n’,’u’,’\0’};
A
1000
n
1001
u
\0
1002
1003
Program to print the character of any string and also address of each character.
main( )
{
char arr[]=”anas”;
int j;
for(j=0;arr[j]!=’\0’;j++)
{
printf(“address =%u\t”,&arr[j]);
printf(“character =%c\n”,arr[j]);
}
getch( );
}
Output: address=1000
character=a
address=1001
character=n
address=1002
character=a
address=1003
character=s
Program to print the address and character of the string by using the pointers
main( )
{
char arr[]=”anas”;
char *a;
a=arr;
while(*a!=’\0’)
{
printf(“address =%u\t”,a);
printf(“character =%c\n”,*a);
a=a+1;
}
}
Output: address=1000
character=a
address=1001
character=n
address=1002
character=a
address=1003
character=s
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
94
Program to print the address and character of the string by using the pointer
main( )
{
char arr[]=”vidya”;
char *a;
a=arr;
while(*a!=’\0’)
{
printf(“address =%u\t”,a);
printf(“character =%c\n”,*a);
a=a+1;
}
getch( );
}
Output: address=1000
character=v
address=1001
character=i
address=1002
character=d
address=1003
character=y
address=1004
character=a
Command line arguments
The arguments that we pass on to main( ) at the command prompt are called command line
arguments.
The function main( ) can have two arguments traditionally named as argc and argv.
Argc: it represents number of arguments(tells how many strings are on command line)
Argv: it represents list of arguments in the form of strings. Or it is an array of pointer which pints to
every string i.e. on command line.
Every C program contains at least one function i.e. main( ). The main( ) function can contain two
parameters. These parameters are called command line arguments.
This can be written as
main(argc,argv)
int argc;
char *argv[];
{
-----------------------------}
This can also be written as
main(int argc, char *argv[])
{
-----------------------------}
Program to understand command line arguments
#include<stdio.h>
main(int argc,char *argv[])
{
int i;
clrscr( );
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
95
printf("argc=%d\n",argc);
for(i=0;i<argc;i++)
printf("argv[%d]=%s\n",i,argv[i]);
getch( );
}
On the command prompt we have to type program name and then text
Ex: if the program name is NSVWDC.c then type
c:\turboc\NSVWDC.exe. C is powerful language
Output: argc=5
argv[0]= c:\turboc\NSVWDC.exe
argv[1]=C
argv[2]=is
argv[3]=powerful
argv[4]=language
Dynamic Memory Allocation
Since C is a structured language, it has some fixed rules for programming. One of it includes changing
the size of an array. An array is collection of items stored at continuous memory locations.
As it can be seen that the length (size) of the array above made is 9. But what if there is a requirement
to change this length (size). For Example, if there is situation where only 5 elements are needed to be
entered in this array. In this case the remaining 4 indices are just wasting memory in this array. So
there is a requirement to lessen the length (size) of the array from 9 to 5.
Take another situation. In this there is an array of 9 elements with all 9 indices filled. But there is a
need to enter 3 more elements in this array. In this case 3 indices more are required. So the length
(size) of the array needs to be changed from 9 to 12.
This procedure is referred as Dynamic Memory Allocation.
Therefore, Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
Lets see each of them in detail.
malloc()
“malloc” or “memory allocation” method is used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of type void which can be cast into a pointer of
any form.
Syntax:
ptr = (cast-type*) malloc(byte-size)
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes,
this statement will allocate 400 bytes of memory.
And, the pointer ptr holds the address
of the first byte in the allocated memory.
If the space is insufficient, allocation fails and returns a NULL pointer.
Example:
filter_none
edit
play_arrow
brightness_4
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i, sum = 0;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
Prepared by: MD Waseem Raza(MCA-TSSET)
96
Downloaded from:
https://www.sucomputersforum.com
97
}
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
calloc()
“calloc” or “contiguous allocation” method is used to dynamically allocate the specified
number of blocks of memory of the specified type. It initializes each block with a default value ‘0’.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory
for 25 elements each with the size of float.
If the space is insufficient, allocation fails and returns a NULL pointer.
Example:
filter_none
edit
play_arrow
brightness_4
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i, sum = 0;
// Get the number of elements for the array
n = 5;
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
98
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
free()
“free” method is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() are not de-allocated on their own. Hence the free() method is
used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of
memory by freeing it.
Syntax:
free(ptr);
Example:
filter_none
edit
play_arrow
brightness_4
#include <stdio.h>
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
99
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i, sum = 0;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.\n");
// Memory has been successfully allocated
printf("\nMemory successfully allocated using calloc.\n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc Memory successfully freed.
realloc()
“realloc” or “re-allocation” method is used to dynamically change the memory allocation of a
previously allocated memory. In other words, if the memory previously allocated with the help
of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.
Syntax:
ptr = realloc(ptr, newSize);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
where ptr is reallocated with new size 'newSize'.
If the space is insufficient, allocation fails and returns a NULL pointer.
Example:
filter_none
edit
play_arrow
brightness_4
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i, sum = 0;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
Prepared by: MD Waseem Raza(MCA-TSSET)
100
Downloaded from:
https://www.sucomputersforum.com
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.\n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Prepared by: MD Waseem Raza(MCA-TSSET)
101
Downloaded from:
https://www.sucomputersforum.com
102
UNIT-IV
STRUCTURES AND UNIONS
Arrays are used to store large set of data and manipulate them but the disadvantage is that all
the elements stored in an array are to be of the same data type.
If we need to use a collection of different data type items it is not possible using an array. When
we require using a collection of different data items of different data types we can use a structure.
Def: structure is a method of packing data of different types. A structure is a convenient method of
handling a group of related data items of different data types.
Defining a structure:We can define the structure as
struct tag{
member 1;
member 2;
member 3;
member n;
};
In this declaration struct is a keyword, tag is a name that identifies structures of this type and member
1, member 2,….. member n are individual member declarations.
This can also be defined as
struct tag{
member 1;
member 2;
member 3;
member n;
}var; /*Here var is the structure variable.*/
Declaring structure variables
A structure variable declaration is similar to the declaration of variables of any other data types. It
includes the following elements.
1. the keyword struct.
2. the structure tag name.
3. list of variable names separated by commas.
4. a terminating semicolon.
Ex1: struct book-bank, book1, book2, book3;
Declares book1, book2, book3 as variables of type struct book-bank.
Each one of these variables has four members. The complete declaration is like this
struct book-bank
{
char title[20];
char author[15];
int page;
float price;
};
struct book-bank,book1,book2,book3;
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
103
The members of a structure themselves are not variables. They do not occupy any memory until they
are associated with the structure variables such as book1. When the compiler comes across a
declaration statement, it reserves memory space for the structure variables. It is also allowed to
combine both the structure definition and variables declaration in one statement.
We can also declare as
struct book-bank{
char title[20];
char author[15];
int page;
float price;
}book1,book2,book3;
*use of tag name is optional.
struct {
char title[20];
char author[15];
int page;
float price;
}book1,book2,book3;
Ex2: if we want to find the person details record, this can be defined as
struct
{
char name[20];
int age;
char add[20];
}rec;
Here name, age and add are the members of this structure. rec is the structure variable.
for accessing any member of the structure, we use dot(.) operator. As example rec.name points to the
member name of this structure.
Program to accept name, age and address of any person and display it.
main( )
{
struct
{
char name[20];
int age;
char add[20];
}rec;
printf(“Enter the name”);
scanf(“%s”,rec.name);
printf(“Enter the age”);
scanf(“%d”,&rec.age);
printf(“Enter the address”);
scanf(“%s”,rec.add);
printf(“Name: %s\n”,rec.name);
printf(“Age: %s\n”,rec.age);
printf(“Address: %s\n”,rec.add);
getch( );
}
Output: Enter the name raiyaan
Enter the age 21
Enter the address jagtial
Name: raiyaan
Age: 21
Address: jagtial
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
104
Initialize value to the structure
We can also initialize the value to the members of structure as
struct{
char name[20];
int age;
char add[20];
}rec={“raiyaan”,21,”jagtial”};
Here rec.name, rec.age, rec.address have values raiyaan,21 and jagtial.
#include<stdio.h>
main( )
{
struct{
char name[20];
int age;
char add[20];
}rec={“anas”,21,”jagtial”};
printf(“Name: %s\n”,rec.name);
printf(“Age: %s\n”,rec.age);
printf(“Address: %s\n”,rec.add);
getch( );
}
Output:Name: anas
Age: 21
Address: jagtial
Array of structures
As we know array is collection of same datatype of elements. For example we can take 10
integer values in the integer array. Similarly we can declare the array of structure where every
element of array is of structure type. Array of structure can be declared as
struct rec
{
char name[20];
int age;
char address[20];
}person[10];
Here person is an array of 10 elements and each element of person has structure of rec, means
each element of person has 3 member elements which are name, age and address.
Program to accept record of 10 person which has name ,age and address and also display them.
#include<stdio.h>
main( )
{
struct rec{
char name[20];
int age;
char address[20];
}person[10];
int i ;
for(i=0;i<10;i++)
{
printf(“Enter the record %d\n”,i+1);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
}
https://www.sucomputersforum.com
105
printf (“name:”);
scanf(“%s”,person[i].name);
printf (“age:”);
scanf(“%d”,person[i].age);
printf (“address:”);
scanf(“%s”,person[i].address);
printf(“name\t \t age\t address”);
for(i=0;i<10;i++)
{
printf(“%s\t\t”,person[i].name);
printf(“%d\t”,person[i].age);
printf(“%s\n”,person[i].address);
}
getch( );
}
Passing structure to function
In function we take the variables as actual parameter and pass them in same data type in
formal parameter. Similarly we can pass the structure variable. The general form is
struct rec{
char name[20];
int age;
char address[20];
}var1;
main( )
{
-------------fun(var1);
-------------}
fun(var2)
struct rec var2;
{
----------------------------------}
It is necessary to declare the structure globally.
Program to accept student name and then calculate the total marks of c, fit, bom. Write this
program passing structure to functions.
#include<stdio.h>
struct student{
char name[20];
int c, fit, bom;
}var;
main( )
{
fun(var);
}
fun(struct student sum)
{
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
106
int total=0;
printf(“Enter the name”);
scanf(“%s”,sum.name);
printf(“\n Enter marks in c”);
scanf(“%d”,&sum.c);
printf(“\n Enter marks in fit”);
scanf(“%d”,&sum.fit);
printf(“\n Enter marks in bom”);
scanf(“%d”,&sum.bom);
total=sum.c +sum.fit+sum.bom;
printf(“name\t\t c\t fit\t bom\t total\n”);
printf(“%s\t\t%d\t%d\t%d\t%d\n”,sum.name,sum.c,sum.fit,sum.bom,total);
getch( );
}
Structure within structure(Nested Structures)
We can take the member element of structure of any data type, such as int, float, char etc.
Similarly we can take the member of structure as structure type. We can take any structure i.e. called
structure within structure.
Syntax: struct tag1{
member 1;
member 2;
---------struct tag2{
member 1;
member 2;
----------member m;
}var1;
---------member m;
}var2;
For accessing the member1 of inner structure we write as var2.var1.member 1;
Ex: struct rec{
char name[15];
int age;
struct dob{
int day;
int month;
int year;
}birthday;
char address[15];
}emp;
Here struct rec is the structure for the employee record and struct dob represent the birth date of that
employee.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
107
Program to accept the employee name and basic salary and also accept the employee address,
city and pin code and print employee name, basic sal, da, hra, pf, netsal, add, city, pin code.
#include<stdio.h>
main( )
{
struct employee{
char name[20];
int age;
struct sal{
float bsal, da, hra, pf, ns;
}a;
char add[20];
long pin;
}rec;
printf(“Enter the employee name and age\n”);
scanf(“%s%d”, rec.name, &rec.age);
printf(“Enter the address and pin code\n”);
scanf(“%s%ld”,rec.add, &rec.pin);
printf(“Enter the bsal”);
scanf(“%f”,&rec.a.bsal);
rec.a.da=rec.a.bsal*0.20;
rec.a.hra=rec.a.bsal*0.10;
rec.a.pf=rec.a.bsal*0.12;
rec.a.ns=rec.a.bsal+rec.a.da+rec.a.hra-rec.a.pf;
printf(“employee information:”);
printf(“name=%s”,rec.name\n);
printf(“age=%d”,rec.age\n);
printf(“bsal=%f”,rec.a.bsal\n);
printf(“da=%f”,rec.a.da\n);
printf(“hra=%f”,rec.a.hra\n);
printf(“pf=%f”,rec.a.pf\n);
printf(“ns=%f”,rec.a.ns\n);
printf(“add=%s”,rec.add\n);
printf(“pin=%ld”,rec.pin\n);
getch( );
}
Program to demonstrate structure within structure.
main( )
{
struct person{
char name[20];
int age;
struct address{
char street[20];
int hno;
char city[20];
}add;
long phno;
}rec;
clrscr( );
printf(“Enter the name and age\n”);
scanf(“%s%d”,rec.name, &rec.age);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
108
printf(“Enter the street and city\n”);
scanf(“%s%s”, rec.add.street, rec.add.city);
printf(“Enter the hno and phno\n”);
scanf(%d%ld”, &rec.add.hno, &rec.phno);
printf(“name\t\t age\t street\t\t hno\t city\t\t phno”);
printf(“\n%s\t\t%d”,rec.name,rec.age);
printf(“\t%s\t\t%d”,rec.add.street,rec.add.hno);
printf(“\t%s\t\t%ld”,rec.add.city,rec.phno);
getch( );
}
Pointer to structure
Pointer is a variable which hold the starting address of another variable, it may be of int, float,
char. Similarly if the variable is of structure type then for accessing the starting address of the
structure, we must declare pointer for a structure variable. These pointers are called structure
pointers and can be declared as
struct rec
{
char name[20];
int age;
int sal;
}data;
struct rec *ptr;
Here ptr is a pointer variable which points to the structure rec. ptr can hold the starting address of the
structure by writing
ptr=&data;
Because data is a structure variable this can be also be written as
struct rec
{
char name[20];
int age;
int sal;
}data,*ptr;
ptr=&data;
data is a structure variable and ptr is a structure pointer that points to the starting address of
structure variable data.
There are two ways for accessing the member of structure through the structure pointer. First is to
use the arrow operator (->) formed by hyphen and greater than symbol.
Ex: for accessing the member element age of the structure we can write as
ptr->age;
The other way for accessing the member element as
(*ptr).age;
Here parenthesis is necessary because the dot operator as higher precedence than the *operator.
Program to understand pointer to structure
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
main( )
{
struct rec
{
char name[20];
int age;
int sal;
}data,*ptr;
ptr=&data;
printf(“Enter the name\n”);
scanf(“%s”,ptr->name);
printf(“Enter the age\n”);
scanf(“%d”,&ptr->age);
printf(“Enter the salary\n”);
scanf(“%d”,&ptr->salary);
printf(“name=%s”,ptr->name);
printf(“age=%d”,ptr->age);
printf(“salary=%d”,ptr->salary);
getch( );
}
Program to accept name, class and marks of five students
with the use of structure with array of pointer and also print them
void main()
{
struct
{
char name[20];
int clas;
int marks;
}data, *rec[5];
int i;
*rec=&data;
for(i=0;i<5;i++)
{
printf("Enter the name\n");
scanf("%s",rec[i]->name);
printf("Enter the class\n");
scanf("%d",&rec[i]->clas);
printf("Enter the marks\n");
scanf("%d",&rec[i]->marks);
}
printf("Given Student details are: \n");
printf("========================================");
printf("\nname \t class\tmarks\n");
printf("========================================\n");
for(i=0;i<5;i++)
{
printf("%s\t",rec[i]->name);
printf("%d\t",rec[i]->clas);
printf("%d\n",rec[i]->marks);
}
getch( );
Prepared by: MD Waseem Raza(MCA-TSSET)
109
Downloaded from:
https://www.sucomputersforum.com
110
}
We can also use pointer as a member of structure
Program to use a pointer as a member of structure and print the value of members
main( )
{
struct rec
{
char *name;
int *age;
int *sal;
}data*ptr;
char name1[10]=”Awdc”;
int age1=23;
int sal=17000;
ptr=&data;
clrscr( );
ptr->name=name1;
ptr->age=&age1;
ptr->sal=&sal1;
printf(“name=%s\n”,ptr->name);
printf(“age=%d\n”,*ptr->age);
printf(“sal=%d\n”,*ptr->sal);
getch( );
}
UNIONS
Union is same as the structure as the structure contains members of different data types. In the
structure each member has its own memory location. Where as members of unions has same memory
location. We can assign values to only one member at a time, so assigning value to another member
that time has no meaning.
When a union is declared, compiler automatically allocates a memory location to hold the
largest data type of member in the union. Thus the union is used for saving memory. The concept of
union is useful when it is not necessary to assign the values to all the members of the union at a time.
Union can be declared as
union unionname
{
member1;
memebr2;
---------------------};
The declaration of union variable is same as the structure.
union unionname
{
member1;
memebr2;
---------------------}variable name;
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
111
This can also be declared as
union unionname variable name;
Ex:
union emp
{
int age;
char code[4];
};
code
Byte 0 Byte 1 Byte 2 Byte 3
age
We can access the union member same as structure if we can access directly then we use the
dot (.) operator. If we access through pointer then we use arrow (->) operator.
Program for accessing the union member
main( )
{
union result
{
int marks;
char grade;
}rec;
printf(“size of union:%d\n”,sizeof(rec));
rec.marks=90;
printf(“marks:%d”,rec.marks);
rec.grade=’A’;
printf(“grade:%c\n”,rec.grade);
getch( );
}
Program to access the union member through pointer
main( )
{
union result
{
int marks;
char grade;
}data;
union result*res;
res=&data;
res->marks=75;
res->grade=’A’;
printf(“marks=%d grade=%c”,,res->marks,res->grade);
getch( );
}
Output: marks=66 grade=A
Program to access the union member through pointer
main( )
{
union result
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
112
{
int marks;
char grade;
}data;
union result*res;
res=&data;
res->marks=75;
printf(“marks=%d”,res->marks);
res->grade=’A’;
printf(“grade=%c”,,res->grade);
getch( );
}
Output: marks=75 grade=A
A structure may be a member of union or a union may be a member of structure
Ex:
union result
{
int marks;
char grade;
};
struct res
{
char name[15];
int age;
union result performance;
}data;
Here data is the structure variable of type res. It has three members an array of character name, an
integer age and an union member performance. Union member will take only one value at a time an
integer value marks or a character value grade.
This can also be written as
struct res
{
char name[15];
int age;
union result
{
int marks;
char grade;
}performance;
}data;
Program for union as a member of structure
main( )
{
union result
{
int marks;
char grade;
};
struct res
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
{
char name[15];
int age;
union result per;
}data;
printf(“size of union:%d\n”,sizeof(data.per));
printf(“size of structure:%d\n”,sizeof(data));
data.per.marks=90;
printf(“%d\t%c\n”,data.per.marks,data.per.grade);
data.per.grade=’A’;
printf(“%d\t%c\n”,data.per.marks,data.per.grade);
getch( );
}
Output: sizeof union:2
sizeof structure:19
90
A
Differences between structure and unions
S.No.
Structure
It is a user defined data type that
1
encapsulates different data types
It can hold set of different values
2
grouped together in structure
variables
All the members of The structure are
3
Accessed with dot(.) Operator
Each individual member can hold
4
different members location
5
6
We can initialize Or access all the
members at a time
Structure declaration
struct student
{
char name[10];
int rno;
int fees;
}rec={“Awdc”,30,2006};
113
union
It is a user defined data type that
encapsulates different data types
It can hold a single Value at a time, which
can be the value of Anyone of the
members.
All the members of the union are
accessed with dot(.) operator
Members of the union Share common
memory location, whose size is largest of
memory required by individual member.
We cannot initialize or access all the
members at a time
union declaration
union student
{
int age;
char grade;
}rec;
rec.age=20;
User defined type declaration
Typedef: typedef is used for defining new data type i.e. it is used for giving aliases for data type.
Sothat we can give another name for the data types to be used in the program.
The general syntax is
typedef type dataname;
here type is the data type and dataname is the user defined name for that type.
Ex:typedef int marks
In the above example marks is name for integer data type. Now we can use marks as data type
instead of integer data type i.e. marks, age, class;
Program for understand typedef
main( )
{
typedef int rama;
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
114
typedef rama sita;
rama x=30;
sita y=40;
printf(“%d”,x+y);
}
In the above example writing “rama” is as good as writing “int” and writing “sita” is a good as
writing “rama” which in turns is “int” hence x and y are treated as of type “int”.
Similarly we can also use typedef for defining structure.
typedef struct
{
member1;
memebr2;
----------------------}dataname;
Here dataname is the another user definedname for defining this structure
typedef struct
{
char name[15];
int class;
int marks;
}rec;
rec person[10];
here rec is used for defining the structure and person has the same structure as the rec.
Program to accept name, age and address of 10 persons with the use of typedef and also pint
them
main( )
{
typedef struct
{
char name[15];
int age;
char address[20];
}rec;
rec person[10];
Int I;
for(i=0;i<10;i++)
{
printf(“Enter the name , age and address\n”);
scanf(“%s%d%s”,person[i].name.&person[i].age,person[i].address);
}
printf(“name\tage\taddress\n”);
for(i=0;i<10;i++)
{
printf(“%s\t”,person[i].name);
printf(“%d\t”,person[i].age);
printf(“%s\t”,person[i].address);
}
getch( );
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
115
}
Enumeration
Enumeration is a way of defining user defined data type. It allows declaring string constants
with integer equivalent values. That is enumeration data type is a set of integer constants, which has
some value these are called as enumeration constants. This can be defined same as structure or union
The general form is
enum enum-tag
{
member1;
member2;
----------------------};
Where enum is a keyword and member1, member2 is integer identifiers.
This can also be defined as
enum enum-tag
{
member1;
member2;
-----------}var;
Here var is an enumeration variable, these variables can also be defined as
enum enum-tag var;
here var is the enumeration variable of type enum-tag
Ex: enum month{jan,feb,mar,apr,may,june);
here month is the enum-tag and numeration contains six integer constants.
Enumeration constants are automatically assigned an integer value beginning from 0,1,2,….etc to the
lat member of the enumeration. So in the above example these integer constant will take following
values.
jan=0,feb=1,mar=2,apr=3,may=4,june=5
These are the default values assigned to the enumeration constants. It is also possible to assign
any value to the integer constant but the successive integer constant will take value increasing by 1.
Ex: enum month{jan,feb=4,mar=5,apr=6,may=11,june=12);
Now the values are jan=0, feb=4, mar=5, apr=6, may=11, june=12
These enumeration variables can be processed as the integer variable; we can also give the value to
the enumeration variable.
Ex: enum month{jan,feb,mar,apr,may,june);data1,data2
data1=mar;
data2=may;
Now data1 has the integer value 2 and data2 will take the value 4
Program to print the default values, assigned to the integer constant*/
main( )
{
enum month{jan,feb,mar,apr,may,june }data1,data2,data3,data4,data5,data6;
data1=jan;
data2=feb;
data3=mar;
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
116
data4=apr;
data5=may;
data6=june;
printf(“January=%d\n February=%d\n”,data1,data2);
printf(“march=%d\n april=%d\n”,data3,data4);
printf(“may=%d\n June=%d\n”,data5,data6);
getch( );
}
Output: January=0 …………….june=5
Program to give the value to the enumeration variable and print them*/
main( )
{
enum month{jan,feb,mar,apr,may,june}data1,data2;
data1=mar;
data2=june;
printf(”march=%d\n”,data1);
printf(“june=%d\n”,data2);
getch( );
}
Output: march=2
June=5
Program to assign any value to the definition of the enum and print them*/
main( )
{
enum month{ jan,feb=-1,mar,apr,may=8,june }data1,data2,data3,data4,data5,data6;
data1=jan;
data2=feb;
data3=mar;
data4=apr;
data5=may;
data6=june;
printf(“\tJanuary=%d\t February=%d\t March=%d\n”,data1,data2,data3);
printf(“\tApril=%d\t May=%d\t June=%d\n”,data4,data5,data6);
getch( );
}
Output:
January=0
February=-1 March=0
April=1May=8
June=9
FILES
Definition: a file is a collection of data or text placed on the disk. By using the file the data can be
stored in the disk or secondary storage device. So the data can be read when we required. There are
two types of files.
1. Sequential File
2. Random Access Files or Direct Access Files
1. Sequential File: In sequential file data are kept sequential. As example if we want to access the 44 th
record then first 43 records should be read sequentially to reach the 44 th record.
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
117
2. Random Access Files: In the random access file the data can be accessed and processed randomly.
As an example if we want to access the 44th record then this record can be accessed directly. It takes
less time than the sequential file.
The steps for file operation in C programming are as follows
1. open a file
2. read the file or write the data in the file
3. close the file
1. Opening of a file: when we store a record in the file then at first we need a temporary area in
memory where we store the data/records then we transfer it to the file. To store these records in the
memory we use pointer which points to the starting address where this data/records is stored. We
write this as
FILE *p
Here p is a pointer of file type. For declaring any variable to file type pointer, it necessary to write FILE
in capital and then pointer variable name.
For opening a file we use the library function fopen( ). First we declare pointer variable fopen( ) as file
type pointer. We write this as
FILE *p, *fopen( );
Then p=fopen(“file name”,”mode”);
Where file name is the name of data file where data/record is stored. Modedesides which operation
(read, write and append) is to be performed with data file.
Modes for opening file
1. w (write): This mode open a new file for writing a record, if the file name already exists then using
this mode the previous data/records are erased and the new data/record Entered is written to the
file.
Ex: p=fopen(“sai.txt”,”w”);
here sai.txt is the filename and w is the mode.
Operations possible-writing to the file.
2. r (read): This mode is used for opening a file for reading purpose only.
Ex: p=fopen(“sai.txt”,”r”);
3. a(append): This mode open a file for appending a data/record. If the file does not exists the work
of this mode is same as w mode.
Ex: p=fopen(“sai.txt”,”a”);
Here sai.txt file can be already exists or new file
Operations possible-adding new contents at the end of a file .
If the file sai.txt does not exists then compiler return NULL to the file pointer. This can be written as
p=fopen(“sai.txt”,”r”);
if(p==NULL)
printf(“file does not exist”);
we can also write this as
if ((p=fopen(“sai.txt”,”r”))==NULL);
printf(“file does not exist”);
Operations possible-reading from the file.
4. w+ (write+read): This mode is used for both reading and writing purpose. This is same as the “w”
mode but we can also read the record which is stored in the file
Ex: p=fopen(“sai.txt”,”w+”);
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
118
Operations possible- writing new contents, reading them back and modifying existing contents of the
file.
5. a+ (append+read): This mode is used for both reading and appending purpose. This is same as the
“a” mode but we can also read the record which is stored in the file
Ex: p=fopen(“sai.txt”,”a+”);
Operations possible- reading existing contents, appending new contents to the end file, cannot modify
existing contents.
6. r+(read+write): This mode is used for both reading and writing purpose. We canread the record
and also write the record in the file. From this mode previous record of file is not deleted
Ex: p=fopen(“sai.txt”,”r+”);
If the file sai.txt does not exists then compiler return NULL to the file pointer.
This can be written as
p=fopen(“sai.txt”,”r+”);
if(p==NULL)
printf(“file does not exist”);
we can also write this as
if ((p=fopen(“sai.txt”,”r+”))==NULL);
printf(“file does not exist”);
operations possible- reading existing contents, writing new contents and modifying existing contents
of the file.
Closing file: The files which are opened from the fopen( ) function must be closed at the end of the
program.
This is written as
fclose(p)
if the opening file is more than one then we close all the files.
fclose(p1)
fclose(p2)………
Structure of the file program
main( )
{
FILE *p, *fopen( ):
P=fopen(“file name”,”mode”);
------------------fclose(p);
}
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
PRACTICAL PROGRAMS
1. Write a program to Find the largest two (three) numbers using if and conditional operator
# include <stdio.h>
# include <stdio.h>
# include <conio.h>
# include <conio.h>
void main()
void main()
{
{
int a, b, c, big ;
int a, b, big ;
clrscr();
clrscr();
printf("Enter three numbers : ") ;
printf("Enter two numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
scanf("%d %d ", &a, &b ) ;
big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
big = a > b ? a : b ;
printf("\nThe biggest number is:%d", big) ; printf("\nThe biggest number is:%d", big) ;
}
}
Output:
Output:
Enter three numbers: 33 66 22
Enter two numbers: 33 66
The biggest number is:66
The biggest number is:66
2. Write a program to print the reverse of a given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r;
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
while(n!=0)
{
r=n%10;
printf("%d",r);
n=n/10;
}
}
Output:
Enter a number 4567
7654
3. Write a program to Print the prime number from 2 to n where n is given by user.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,c=0,i,j;
clrscr();
printf("\n Enter n value:");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
c=0;
for(j=1;j<=i;j++)
Prepared by: MD Waseem Raza(MCA-TSSET)
119
Downloaded from:
https://www.sucomputersforum.com
if(i%j==0)
c++;
if(c==2)
printf("\t %d ",i);
}
}
Output:
Enter n value:20
2
3
5
7
11
13
17
19
4. Write a program to find the roots of a quadratic equation using switch statement.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,d,r1,r2,real,img;
int op;
clrscr();
printf("\n Enter a,b,c values:");
scanf("%f%f%f", &a,&b,&c);
d=(b*b)-4*a*c;
if(d>0)
op=1;
if(d==0)
op=2;
if(d>0)
op=3;
Switch op
{
Case 1:
{
printf("\n Roots are Real and Unequal");
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf("\n root1= %f, \t root2= %f",r1,r2);
}
break;
case 2:
{
printf("\n Roots are Real and Equal");
r1=-b/(2*a);
printf("\n root1= root2= %f",r1);
}
break;
case 3:
{
d=abs(d);
printf("\n Roots are Imaginary");
real=-b/(2*a);
img=sqrt(d)/(2*a);
printf("\n root1= %f+i%f",real,img);
Prepared by: MD Waseem Raza(MCA-TSSET)
120
Downloaded from:
https://www.sucomputersforum.com
printf("\n root2= %f-i%f",real,img);
}}}
Output:
5. Write a program to print a triangle stars as follows (take number of lines from user):
*
***
*****
*******
*********
#include<stdio.h>
void main()
{
int i,j,k,n;
printf("Enter number of rows of the triangle: \n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(k=1;k<=(2*i)-1;k++)
{
printf("*");
}
printf("\n");
}
Output:
}
getch();
6. Write a program to find largest and smallest elements in a given list of numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
Prepared by: MD Waseem Raza(MCA-TSSET)
121
Downloaded from:
https://www.sucomputersforum.com
int a[10],n,min,max,i;
clrscr();
printf("Enter the no. of elements you want in list:");
scanf("%d",&n);
printf("\n Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
/* finding min. element of an array */
min=a[0];
for(i=1;i<n;i++)
if(a[i]<min)
min=a[i];
/* finding max. element of an array */
max=a[0];
for(i=1;i<n;i++)
if(a[i]>min)
max=a[i];
printf("\n Min. element Is= %d",min);
printf("\n Max. element Is= %d", max);
}
Output:
Enter the no. of elements you want in list: 8
Enter 8 elements: 101
13
84
56
90
Min. element Is=13
Max. element Is=101
7. Write a program to find the product of two matrices
#include<stdio.h>
#include<conio.h>
void read_mat(int a[][5],int m, int n);
void disp_mat(int a[][5],int m, int n);
void find_mul(int a[][5],int b[][5],int c[][5],int m, int n,int q);
void main()
{
int a[5][5],b[5][5],c[5][5];
int m,n,p,q;
clrscr();
printf("enter the dimensions of first matrix");
scanf("%d%d",&m,&n);
printf("\nenter the dimensions of second matrix");
scanf("%d%d",&p,&q);
if(n==p)
{
printf("\nenter matrix A of dimensions %d X %d",m,n);
read_mat(a,m,n);
printf("\nenter matrix B of dimensions %d X %d",p,q);
read_mat(b,p,q);
find_mul(a,b,c,m,n,q);
printf("\n the matrix A is : \n");
disp_mat(a,m,n);
printf("\n the matrix B is : \n");
Prepared by: MD Waseem Raza(MCA-TSSET)
122
47
33
Downloaded from:
https://www.sucomputersforum.com
disp_mat(b,p,q);
printf("\n the result of A*B (matrix C) is : \n");
disp_mat(c,m,q);
}
else
printf("multiplication is not possible");
}
void read_mat(int a[][5], int m, int n)
{
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
void disp_mat(int a[][5], int m, int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("\t%d",a[i][j]);
printf("\n");
}
}
void find_mul(int a[][5], int b[][5],int c[][5],int m, int n,int q)
{
int i,j,k;
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
Output:
Prepared by: MD Waseem Raza(MCA-TSSET)
123
Downloaded from:
https://www.sucomputersforum.com
8. Write a program to find the GCD of two numbers using iteration and recursion
(Recursive Version)
(iterative version)
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
#include<conio.h>
void main()
{
void main()
int n1,n2,gcd;
{
printf("\nEnter two numbers: ");
int x,y,m,i;
scanf("%d %d",&n1,&n2);
clrscr();
gcd=findgcd(n1,n2);
printf("Insert any two numbers: ");
printf("\nGCD of %d and %d is:
scanf("%d%d",&x,&y);
%d",n1,n2,gcd);
if(x>y)
}
m=y;
int findgcd(int x,int y)
else
{
m=x;
while(x!=y)
for(i=m;i>=1;i--)
{
{
if(x>y)
if(x%i==0&&y%i==0)
return findgcd(x-y,y);
{
else
printf("\nGCD of two number is :
return findgcd(x,y-x);
%d",i) ;
}
break;
return x;
}
}
}
}
9. Write a program to illustrate use of storage classes.
Auto variable
#include <stdio.h>
void call1( );
void call2( );
void main( )
{ int v = 10;
call2( );
printf(“\n V=%d”,v);
}
void call1( )
{ int v = 20;
printf(“\t V=%d”,v);
}
void call2( )
{ int v = 30;
call1( );
printf(“\t V=%d”,v);
}
output:
V=20
Prepared by: MD Waseem Raza(MCA-TSSET)
Register Varaible
#include<stdio.h>
void main( )
{
register int m=1;
for( ; m<=5;m++)
printf(“\t %d”, m);
}
output:
1 2 3 4 5
124
Downloaded from:
https://www.sucomputersforum.com
V=30
V=10
Static Variable
#include <stdio.h>
void increment( );
void main( )
{
increment( );
increment( );
increment( );
}
void increment( )
{
int static m;
m++;
printf(“\n m=%d”,m);
}
Output:
m=1
m=2
m=3
10.
Extern Variable
#include <stdio.h>
int v=10;
void call1( );
void call2( );
void main( )
{
call1( );
call2( );
printf(“\n In main( ) v = %d”,v);
}
void call1( )
{ printf(“\n In call1( ) v = %d”,v); }
void call2( )
{ printf(“\n In call2( ) v = %d”,v); }
output:
In call1( ) v = 10
In call2( ) v = 10
In main( ) v = 10
Write a program to demonstrate the call by value and the call by reference concepts
/* call by value*/
#include<stdio.h>
#include<conio.h>
void change(int x,int y);
void main( )
{
int x,y;
clrscr();
printf("Enter x,y,values:");
scanf(“%d%d”, &x,&y)
printf("\n\nThe values of x,y before
function call:");
printf("\nx=%d,\ty=%d”,x,y);
change(x,y);
printf("\n\nThe values of x,y after
function call:");
printf("\nx=%d,\ty=%d”,x,y);
}
void change(int x,int y)
{
printf("\n\nThe values of x,y in function
before changing:");
printf("\nx=%d,\ty=%d”,x,y);
x=x+10;
y=y+10;
printf("\n\nThe values of x,y in function
after changing:");
Prepared by: MD Waseem Raza(MCA-TSSET)
/*call by reference*/
#include<iostream.h>
#include<conio.h>
void change(int *p,int *q);
main( )
{
int x,y;
clrscr();
printf(“Enter x,y,values:");
scanf(“%d%d”,&x,&y);
printf("\n\nThe values of x,y before
function call:");
printf("\nx=%d,\ty=%d”,x,y);
change(&x,&y);
printf("\n\nThe values of x,y after
function call:");
printf("\nx=%d,\ty=%d”,x,y);
}
void change(int *p,int *q)
{
printf("\n\nThe values of *p, *q in
function before changing:");
printf("\n*p=%d,\t*q=%d”,*p,*q);
*p=*p+10;
*q=*q+10;
printf("\n\nThe values of *p, *q in
function after changing:");
125
Downloaded from:
https://www.sucomputersforum.com
printf("\nx=%d,\ty=%d”,x,y);
}
printf("\n*p=%d,\t*q=%d”,*p,*q);
}
output:
Enter x,y values 12 10
The values of x,y before function call
x=12 y=10
The values of x,y in function before
changing
x=12 y=10
The values of x,y in function after changing
x=22 y=20
The values of x,y after function call
x=12 y=10
output:
Enter x,y values 12 10
The values of x,y before function call
x=12 y=10
The values of *p ,*q in function before
change
x=12 y=10
The values of *p ,*q in function after
change
x=22 y=20
The values of x,y after function call
x=22 y=20
11. Write a program that prints a table indicating the number of occurrences of each alphabet in the
text entered as command line arguments.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char ch;
do{
char a[20],f=0;
int i,n,ascii;
clrscr();
printf("enter a string:");
gets(a);
strlwr(a); /* Sting convert in small letter*/
for(ascii=97;ascii<=122;ascii++)
{
n=0;
f=0;
for(i=0;a[i]!=NULL;i++)
{
if(ascii==a[i])
{
n++; /* If Checking sucessfull ..increment +1*/
f=1;
}
}
if(f==1) /* Checking f value is similar or not */
printf("\n\t%c value found %d times ",ascii,n);
}
printf("\n\t continue (y/n):");
ch=getch();
}while(ch=='y'||ch=='Y');
}
Prepared by: MD Waseem Raza(MCA-TSSET)
126
Downloaded from:
https://www.sucomputersforum.com
Output:
12. Write a program to illustrate use of data type enum.
#include<stdio.h>
#include<conio.h>
enum month {jan=1, feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
void main()
{
clrscr();
printf("\n jan = %d",jan);
printf("\n mar = %d",mar);
printf("\n oct = %d",oct);
printf("\n dec = %d",dec);
}
Output:
13. Write a program to demonstrate use of string functions string.h header file.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20],str2[20],str3[40];
int n,p;
clrscr();
puts("enter a string");
gets(str1);
n=strlen(str1);
printf("\n the length of string %s is %d:",str1,n);
puts("\n enter str2");
gets(str2);
p=strcmp(str1,str2);
if(p)
printf("\n str1 and str2 are not equal");
else
printf("\n str1 and str2 are equal");
Prepared by: MD Waseem Raza(MCA-TSSET)
127
Downloaded from:
}
https://www.sucomputersforum.com
strcat(str1,str2);
printf("\n after concatenation str1 = %s",str1);
strcpy(str3,str1);
printf("\n after copy str3 = %s",str3);
Output:
14. Write a program that opens a file and counts the number of characters in a file.
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
void main()
{
char ch;
int i=0;
FILE *fp;
clrscr();
fp=fopen("x.dat","r");
while((ch=getc(fp))!=EOF)
{
i++;
}
printf("\n No. of characters in the given file is : %d",i);
}
Output:
No. of characters in the given file is :58
15. Write a program to create a structure Student containing fields for Roll No., Name, Class, Year
and Total Marks. Create 10 students and store them in a file.
#include<conio.h>
#include<stdio.h>
#include<ctype.h>
void main()
{
FILE *fp;
Prepared by: MD Waseem Raza(MCA-TSSET)
128
Downloaded from:
https://www.sucomputersforum.com
129
char *fname,ch='y';
int n=0,total=0;
struct stud
{
int roll_no;
char stud_name[20];
int sub1, sub2, sub3, total;
char group[20];
int year;
}s;
clrscr();
printf("\n enter source file name:\t");
gets(fname);
fp=fopen(fname,"w");
if(fp==NULL)
{
printf("\n unable to open");
exit(0);
}
while(ch=='Y'||ch=='y')
{
printf("\n enter Roll number");
scanf("%d",&s.roll_no);
printf("\n enter student name:\t");
scanf("%s",s.stud_name);
printf("\n enter Group\n");
scanf("%s",s.group);
printf("\n enter year");
scanf("%d",&s.year);
printf("\n Enter 3 subject marks");
scanf("%d%d%d",&s.sub1,&s.sub2,&s.sub3);
s.total=s.sub1+s.sub2+s.sub3;
fprintf(fp,"%d%s%s%d%d%d%d%d",s.roll_no,s.stud_name,s.group,s.year,s.sub1,s.sub2,s.sub3,s.total)
;
n++;
printf("\n do you want to add another record (Y/N)?");
fflush(stdin);
scanf("%c",&ch);
}
printf("\n%d record are store in %s file",n,fname);
fclose(fp);
getch();
}
Output:
16. Write a program that opens an existing text file and copies it to a new text file with all lowercase
letters changed to capital letters and all other characters unchanged.
#include<stdio.h>
#include<process.h>
#include<ctype.h>
Prepared by: MD Waseem Raza(MCA-TSSET)
Downloaded from:
https://www.sucomputersforum.com
130
void main() {
FILE *fp1, *fp2;
char a;
clrscr();
fp1 = fopen("test.txt", "r");
if (fp1 == NULL) {
puts("cannot open this file");
exit(1);
}
fp2 = fopen("test1.txt", "w");
if (fp2 == NULL) {
puts("Not able to open this file");
fclose(fp1);
exit(1);
}
do {
a = fgetc(fp1);
}
if(islower(a));
a=toupper(a);
fputc(a, fp2);
} while (a != EOF);
fcloseall();
getch();
Note:
1. Write the Pseudo Code and draw Flow Chart for the above programs.
2. Recommended to use Open Source Software: GCC on Linux; DevC4-1- (or) Code Blocks on Windows 10.
Prepared by: MD Waseem Raza(MCA-TSSET)
Download