Principles of Programming Using C BPOPS103-203
Principles of Programming Using C BPOPS103-203
Accredited with “A” Grade by NAAC | NBA Accredited for CSE, ECE & Mining Engg Programs
Oorgaum, Kolar Gold Fields - 563 120, Karnataka | Web : www.drttit.edu.in
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
Dr. T. Thimmaiah Institute of Technology
VISION
To produce technically competent engineers having innovative skills positive
attitude, leadership and professional ethics, with a focus on developing
sustainable and new technology.
MISSION
Create a conducive environment for teaching, learning and innovation by
providing state of the art infrastructure.
Learn sustainable and new technologies through industry institute collaborations.
Produce technically competent engineers with ethics, discipline and social
consciousness through holistic education.
FOREWORD
This guidebook is tailored for the students, who are in rst or second semester. This
book aims to provide a clear understanding of essential computer topics in the
course Principles of Programming using C which is crucial for academic success.
We extend our sincere thanks to Dr. T. Venkat Vardhan, President, Golden Valley
Educational Trust for his continuous support and encouragement.
We also thank our Principal, Dr. Syed Ariff; Vice-Principal, Dr. H. G. Shenoy;
Dean Academics, Prof. Ruckmani Divakaran ; IQAC Head, Dr. Jenitha A;
HOD, Computer Science Engineering Dr. Geetha C. Megharaj; and all members
of our department for their encouragement and motivation.
Course Instructors
Prof. Parvathi TR, Assistant Professor
Prof. Sudha S, Assistant Professor
Prof. Jerusha Madhurya P, Assistant Professor
EDITORIAL NOTE
We congratulate and appreciate the authors for their effort towards making this
course simple and student friendly. This will denitely help the students to face the
exam with condence and score better.
We wish the students will positively and effectively make use of this guide.
This is the rst edition of the guide; we welcome the feedback and suggestions from
students and faculty members to improve further for the benet of the students.
MODULE: 1
INTRODUCTION TO C
➢ Computer is an electronic device, which takes input from the user in the form
of data and instructions.
➢ Once the computer receives the data, it waits for the user’s instructions
to process the data.
➢ On receiving the instructions from the user, the computer processes the data
and generates the output and displays it to the user.
➢ The data that is given as an input to the computer can be text, numerals,
audio, video and image etc.
“An electronic device which accepts the data, performs the required mathematical and
logical operations at the high speed and outputs the result”.
➢ Input: Sending the data and command to the computer is known as input.
➢ Processing: Work done by the computer with the help of processing hardware and
software to produce results is known as processing.
➢ Storage: A place to save results inside or outside the computer is known as storage.
1.1.1 CHARACTERISTICS OF COMPUTER
➢ Speed: Computers can perform millions of operations per second. The speed of
computers is usually given in nanoseconds/picoseconds where 1ns=1 x 10-9 seconds
and 1ps = 1 x 10-12 seconds.
➢ Accuracy: A computer is a very fast, reliable, and robust electronic device. It always
gives accurate results, provided we give correct input and instructions as input. The
output generated by the computer always depends on the given instructions and input data. If
the input is wrong the output will be erroneous. This is called, “garbage-in, garbage-out”.
➢ Automation: Computers performs the task without any human intervention. The user
just needs to assign the task to the computer, after which it automatically controls
different devices attached to it and executes the program instructions.
➢ Versatile: Computers are versatile devices as they can perform multiple tasks of
different nature at the same time
➢ No IQ: Computers do not have any decision making abilities of their own. They need
guidance to perform various tasks.
➢ A computer with Von Neumann Architecture as shown in Figure: 1 stores data and
instructions in the same memory.
➢ There is a serial machine in which data and instructions are selected one at a time.
➢ Data and instructions are transferred to and from memory through shared data bus.
➢ Since there is a single bus to carry data and instructions, process of execution becomes slower.
Von Neumann Architecture with shared memory for instructions and data
Figure1.2 Von Neumann Architecture with separate memory for instructions and data
Disadvantage:
Advantage:
➢ Consumed less electricity, Generated less heat, Faster cheaper and more reliable, could
be programmed using high and assembly level language, had faster primary memory
and larger secondary memory.
Disadvan tage:
➢ Large Magnetic core memory was used as primary memory and magnetic
tapes and disks were used to store data and instructions.
Advantage:
➢ Faster and could perform one million transactions per second, Smaller,
cheaper and more reliable, Faster and larger primary and secondary memory,
widely used for scientific and business applications.
Disadvantage:
➢ Difficult to maintain and got heated very quickly.
Advantage:
➢ Smaller, cheaper, faster and more reliable, Consumer less electricity,
generated less heat, Used as General purpose computers, GUI’s made work
with computer easier, Widespread of computers to office and homes
Disadvantage:
➢ Not intelligent systems.
2) Mainframe Computers:
➢ These are very expensive and need a very large clean room with air
conditioning, making them very costly to deploy.
Dumb terminals:
Intelligent terminals:
➢ It have their own processor and perform processing operations but do not
have their own storage space.
➢ Mainframe computers are typically used as servers on WWW.
3) Minicomputers:
4) Microcomputers:
➢ They are commonly known as PC’s.
➢ The first microcomputer was designed by IBM in 1981 and was named as
IBM-PC.
5) Desktop PCs:
➢ It is the most popular model of PC’s.
Laptops:
Workstations:
➢ A workstation is nothing but a computer like a personal computer, but
with more powerful microprocessor and large, high resolution monitor for
better quality of pictures along with large amount of memory.
Advantages:
Disadvantages:
➢ Workstations are costly, Not Portable.
Network computers:
➢ Network computers have less processing power, memory, and storage
than a desktop computer.
➢ Some network computers do not have any storage space and merely rely on the
network's server for data storage and processing tasks. The concept of network
computers had become popular in the mid-1990s.
➢ Network computers that are specifically designed to access only the Internet
or intranet are often known as Internet PCs or Internet boxes.
➢ Some network computers used in homes do not even have a monitor. Such
computers may be connected to a television, which serves as the output
device.
➢ The most common example of a home-based network computer is Web TV,
which enables the user to connect a television to the Internet.
➢ The Web TV is equipped with a special set-top box that is used to connect
to the Internet.
➢ The set-top box also provides controls to enable the user to navigate the
Internet, send and receive e-mails, and to perform other tasks on the network
while watching television.
➢ The other reason for the popularity of network computers is that they are cheaper
to purchase and maintain than PCs.
Smart phones:
Disadvantages:
Tablet Computers:
➢ It has all the features of a laptop and allows the user to write on the screen
using digital pen. This pen is called stylus. This pen is also used to tap on
the icon so as to select an item.
Advantages:
➢ They are very slim and light weight compared to laptops and hence they are portable.
Disadvantages:
2. Internet: The internet is a network that connects the computers all over the
world.
4. Desktop publishing: This software enables to create page layouts for entire
books.
10) Multimedia and Animation: which combines still images, moving images,
text, sound.
11) Legal System: Computers are used by lawyers to shorten the time
required to conduct legal precedent and case research.
12) Retail Business: Computers are used here to enter orders, calculate costs,
and print receipts.
13) Sports: Computers are used here to compile statistics, identify weak and
strong players, sell tickets etc.
14) Travel and Tourism: Computer are used to prepare tickets, monitor the
train or airplane route, and guide the plane to a safe landing.
16) Astronomy: Spacecrafts are usually monitored using computers that not
only keep a continuous record of the voyage and of the speed, directions, fuel
and temperature, but also suggest corrective actions when vehicle make a
mistake.
18) Industry and Engineering: Computers are found in all kind of industry like
thermal power plants, oil refineries, chemical industry, Computer-aided
designing, Computer aided manufacturing.
19) Expert Systems: Expert systems are used to automate the decision-making
process in a specific area, such as analyzing the credit histories for loan
approval, diagnosing patients’ condition for prescribing an appropriate
treatment.
➢ Storing data
➢ Processing data
➢ Displaying results
Input
➢ The process of entering the data and instructions into the computer system
is called Input.
➢ The data and instructions can be entered by using different input
devices such as keyboard, mouse, scanner, and trackball.
Storage:
1) Primary storage
2) Secondary storage
1. Primary storage:
➢ Primary storage, also known as the main memory, is the storage area that is
directly accessible by the CPU at very high speeds.
➢ It is used to store the data and parts of programs, the intermediate results of
processing, and the recently generated results of jobs that are currently being worked
on by the computer.
2)Secondary storage
Output:
➢ Output is the process of giving the result of data processing to the outside world
(external to the computer system).
➢ The results are given through output devices such as monitor, and printer.
➢ Since the computer accepts data only in binary form and the result of processing
is also in binary form, the result cannot be directly given to the user.
➢ The output devices, therefore, convert the results available in binary codes into a
human-readable language before displaying it to the user.
Control :
➢ The control unit (CU) is the central nervous system of the entire computer system.
It manages and controls all the components of the computer system.
➢ It is the CU that decides the manner in which instructions will be executed and
operations performed. It takes care of the step-by-step processing of all
operations that are performed in the computer.
➢ Note that the CPU is a combination of the arithmetic logic unit (ALU) and the
CU. The CPU is better known as the brain of the computer system because the
entire processing of data is done in the ALU, and the CU activates and monitors
the operations of other units.
Processing:
➢ The process of performing operations on the data as per the instructions specified
by the user (program) is called processing.
➢ Data and instructions are taken from the primary memory and transferred to
the ALU, which performs all sorts of calculations.
➢ When the processing completes, the final result is then transferred to the
main memory.
➢ Hence, the data may move from main memory to the ALU multiple times before
the processing is over.
CPU:
➢ The CPU is the brain of the computer. It performs all calculations and
controls the devices connected to the computer system.
➢ The faster the CPU, the quicker programs can process the instructions.
RAM:
➢ A fast CPU is of no use if the computer does not have sufficient RAM.
➢ RAM is the computer's memory which stores information used by
applications that are currently being executed by the CPU.
➢ The HDD of the computer is the secondary memory of the computer system
where information is stored permanently.
➢ All types of data, documents, and programs are stored on the hard disk.
➢ The larger the hard disk, the more the amount of data that can be stored on
the drive.
➢ Though the size of the HDD does not affect the speed of execution of the
program, it does affect the speed at which the user can access his/ her files.
Video card:
➢ The video card is a board that plugs into the motherboard of the computer
and generates images for display.
➢ Many video cards these days have their own RAM and processor to enhance
the speed of the graphics display.
➢ In such a computer, a separate video card is used only if the computer has
to be used for high-end multimedia work or to play video games.
Sound card:
➢ As with video cards, sound cards are expansion boards that are used to enable a
computer to manipulate sound.
➢ For example, sound cards allow the users to plug in speakers and a microphone.
Some sound cards also provide the jacks for hooking your computer up to a
common stereo.
➢ These days, many computers come with a built-in sound chip, which makes it
unnecessary to buy a separate card unless a higher quality of sound is needed.
Modem:
Network card:
Fans:
➢ There are one or more fans inside the computer to keep the air moving
and the computer cool.
Cables:
➢ There are multiple wires inside the computer that are flat, ribbon-like cables.
➢ They are used to provide power and communication to the various parts
inside the computer.
Keyboard:
Disadvantages:
➢ The process of moving the cursor to another position is very slow. Mouse and
other pointing devices are more apt for this purpose.
Pointing Devices:
➢ A pointing input device enables the users to easily control the movement
of the pointer to select items on a display screen, to select commands from
commands menu, to draw graphics, etc.
➢ Some examples of pointing devices include mouse, trackball, light pen,
joystick, and touchpad.
Mouse:
➢ The mouse is an input device that was invented by Douglas Engelbart in 1963.
• Point: Placing the pointer over the word or the object on the
screen by moving the mouse on the desk is termed as pointing.
• Click: Pressing either the left or the right button of the mouse is known
as clicking. Clicking a mouse button initiates some action; for example,
when you click the right button by pointing the mouse on a word, a
menu pops up on the screen. When you move the pointer over the icon
of an application, say Internet Explorer, and double-click on it, then it
opens that application for you.
• Scroll: The scroll wheel, which is placed in between the left and
right buttons of the mouse, is used to vertically scroll through
long documents.
The mouse is specially used to create graphics such as lines, curves, and
freehand shapes on the screen. It is connected to a serial or a universal serial bus
(USB) port on the system unit. Some of the popular mouse types are as follows:
1. Mechanical mouse
2. Optical mouse
3. Cordless mouse
1. Mechanical Mouse
➢ This type of mouse has a rubber or metal ball at its bottom and an electronic circuit
containing sensors.
➢ When the mouse is moved over a flat surface, the sensors detect the direction of
movement of the ball.
➢ The electronic circuit translates the movement into signals and feeds it as input to
the computer.
2. Optical mouse:
➢ The optical mouse is more advanced than the mechanical mouse. It contains a ball
inside. The movement of the mouse is detected using laser technology, by using
optical sensors.
3. Cordless mouse:
TouchPad
Advantages:
➢ Occupies less space.
➢ Easy to use.
➢ Built in keyboard so need to carry an extra device.
Handheld devices:
➢ A handheld devices is a pocket-sized computing device with a display
screen and touch input and/or a miniature keyboard.
➢ Some examples are:
1. Smartphone's
2. PDA’s
Joystick:
➢ Joystick is a cursor control device widely used in computer games and
CAD/CAM applications.
➢ It consists of a hand-held lever that pivots on one end and transmits its
coordinates to a computer.
➢ It has one or more push-buttons, called switches, whose position can also
be read by the computer.
Stylus:
➢ A stylus is a pen-shaped input device used to enter information or write
on the touch screen of a phone.
➢ Stylus is a small stick that can also be used to draw lines on a surface as input
to a computer, choose an option from a menu, move the cursor to another
location on the screen, take notes and create short messages.
➢ The stylus usually slides into a slot built into the smart phone for that purpose.
Touch Screen
➢ A touch screen is a display screen which can identify the occurrence and
position of a touch inside the display region.
➢ The user can touch the screen either by his finger or by using a stylus.
Optical devices:
➢ Optical devices, also known as data-scanning devices, use light as a source
of input for detecting or recognizing different objects such as characters,
marks, codes, and images.
➢ These devices convert these objects into digital data and send it to the
computer for further processing.
➢ Some optical devices that are discussed include barcode readers, image
scanners, optical character recognition (OCR) devices, optical mark
readers (OMR), and magnetic ink character recognition (MICR) devices.
Barcode readers:
➢ A barcode reader (or price scanner or point-of-sale scanner) is a hand-held input
device which is used to capture and read information stored in a barcode.
➢ A barcode reader consists of a scanner, a decoder, and a cable used to connect the
reader with a computer.
➢ The barcode reader merely captures and translates the barcode into numbers
and/or letters.
➢ To make use of the information captured it must be connected to a computer for
further processing.
➢ For this purpose, the barcode reader is connected to a computer through a serial
port, keyboard port, or an interface device called a wedge.
Advantages: Cheap, Portable, Used to read data stored in bar codes, Handy
and easy to use.
Image scanner:
➢ It is a device that captures images, printed text, handwriting from
different sources and converts it into a digital image for computer
editing and display.
Advantages:
➢ Any printed or handwritten document can be scanned and stored in a
computer for further processing.
➢ The scanned and stored document will never deteriorate in quality with
time.
➢ The document can be displayed and printed whenever required. There is
no fear of loss of documents.
➢ The user can scan important documents and store them permanently in
the computer.
Disadvantages
➢ Scanners are usually costlier than other input devices.
➢ The documents that are scanned and stored as images have a higher size as
compared to other equivalent text files.
➢ Text documents are scanned and stored as images. Therefore, they occupy
more space and are also not editable because computers cannot interpret
individual characters and numbers in the image.
Optical Character Recognition (OCR):
Advantages:
➢ Printed documents can be converted into text files
➢ Advanced OCR can recognize handwritten text and convert them
into computer readable text files.
Disadvantages:
➢ OCR cannot recognize all types of fonts
➢ Documents that are poorly types or have strikeover cannot be recognized
➢ Very old documents when passed through OCR may not have an
exact copy of the text file.
Advantages:
➢ Optical mark readers works with a very fast speed. They can read up to 9,000
forms per hour
Disadvantages:
Audio devices
➢ Audio devices are used to either capture or create sound. They enable computers
to accept music, speech or sound affects for recording and/or editing.
➢ Microphone and CD player are examples of two widely used audio input devices.
➢ Microphone feeds audio input to the computer. The computer must have a sound
card to convert analog signals generated through microphone into digital data so
that it can be stored in the computer.
➢ When the user wants to hear the pre-recorded audio input, the sound card converts
the digital data into analog signals and sends it to the speakers.
Advantages: Audio devices can be used by people who have visual problems; It is
best used in situations where users want to avoid i/p through keyboard or mouse.
Disadvantages: Audio input devices are not suitable in noisy places; With
audio input devices it is difficult to clearly distinguish between two similar
sounding words like “sea” and “see”
Advantages:
➢ Video input devices are very useful for applications like video conferencing
➢ Video input devices can be used to record memorable moments in one’s life
Disadvantages:
➢ Videos and images captured using video input devices have a very
big file size and there must be compressed before being stored on
the computer.
➢ The focusing anode focuses the stream of electrons to form a tight beam
which is then accelerated by an accelerating anode.
➢ This tight, high-speed beam of electrons flies through the vacuum in the tube
and hits the flat screen at the other end of the tube.
➢ This screen is coated with phosphor, which glows when struck by the beam,
thereby displaying the picture which the user sees on the monitor.
Advantages:
➢ The images are clear even when we try to view in different angle.
Disadvantages:
➢ They are bigger in size and weight and therefore difficult to move from
one place to another when compared with other types of monitor.
➢ LCD monitor is a thin, flat electronic visual display that uses the
light modulating properties of liquid crystals which do not emit light
directly.
➢ LCD screens are used in a wide range of applications ranging from computer
monitors, television, instrument panels, aircraft cockpit displays, signage, to
consumer devices like such as video players, gaming devices, clocks, watches,
calculators, and telephones.
➢ The LCD consists of two pieces of polarizing filters (or substrates) that
contain a liquid crystal material between them.
➢ A backlight creates light which is made to pass through the first substrate.
➢ Most LCD displays use active matrix technology in which a thin film
transistor(TFT) arranges tiny transistors and capacitors in a matrix of the
display.
➢ Passive matrix technology is the other type of LCD, which uses a grid of
conductive metal to charge each pixel.
Advantages:
➢ They are very compact and light weight, consume less power.
➢ They are more reliable than CRTs and can be made in almost any size
or shape.
Disadvantages:
➢ Images are not very clear when tried to view from an angle.
Plasma Monitors
➢ Plasma monitors are thin and flat monitors widely used in TVs and
computers. The plasma display contains two glass plates that have tiny cells
filled with xenon and neon gas.
➢ To ionize the gas in a particular cell, the electrodes that intersect at that cell
are charged at least thousands of times in a small fraction of a second
➢ When these UV photons hit a phosphor atom in the cell, one of the
phosphor's electrons jumps to a higher energy level and the atom heats up.
When the electron falls back to its normal level, it releases energy in the
form of a visible light photon.
Advantages: The technology allows producing a very wide screen using extremely
thin materials, very bright images are formed which look good from every single
and are not heavy and hence portable.
Projector
➢ A projector is a device which takes an image from a video source and projects
it onto a screen or other surface.
➢ These days, projectors are used for a wide range of applications varying from home
theater systems to organizations for projecting information and presentations
onto screens large enough for rooms filled with people to see.
➢ LCD Projector make use of their own light to display the image on the wall and
are based on LCD technology. Requires darkened room as image may be
blurred.
➢ Digital light processing (DLP) projector use number of mirrors to reflect the light.
The room may be darkened or not as it displays clear image in both the
situations.
Speakers
➢ Today all business and home users demand sound capabilities and thus
different types of speakers to enable users to enjoy music, movie, or a
game and the voice will be spread through the entire room.
➢ With good quality speakers, the voice will also be audible even to people
sitting in another or room or even to neighbors.
➢ However, in case the user wants to enjoy loud music without disturbing
the people around him, he can use a headphone.
➢ Another device called headset was developed to allow the users to talk
and listen at the same time, using the same device.
Printers:
• Color: Colored printouts are needed for presentations or maps and other pages
where color is part of the information. They are more expensive.
• Speed: Speed means number of pages that are printed in one minute. While
high speed printers are a little expensive, the inexpensive printers on the
other hand can print only about 3 to 6 sheets per minute. Color printing
is even slower.
Impact Printer:
➢ Ex., dot-matrix printers, daisywheel printers, and most types of line printer.
Advantages:
➢ These allow the user to produce carbon copies and are cheap.
Disadvantages:
➢ A dot matrix printer prints characters and images of all types as a pattern of
dots.
➢ It has a print head (or hammer) that consists of pins representing the character
or image.
Advantages:
➢ It can produce carbon copies; offers lowest printing cost per page;
➢ Widely used for bulk printing where quality of the print is not of much
importance; is cheap;
➢ When the ink is about to finish, the printout gradually fades rather than
suddenly stopping partway through a job
➢ It can use continuous paper rather than individual sheets, making them
useful for data logging.
Disadvantages:
➢ It creates a lot of noise when the pins strike the ribbon to the paper.
➢ The print head runs back and forth, or in an up and down motion, on the page
and prints by striking an ink-soaked cloth ribbon against the paper, much like
the print mechanism on a typewriter.
➢ The print head of a daisy wheel printer is a circular wheel, about 3 inches
in diameter with arms or spokes. The characters are embossed at the outer
end of the arms.
➢ To print a character, the wheel is rotated in such a way that the character
to be printed is positioned just in front of the printer ribbon.
➢ The key benefit of using a daisy wheel printer is that the print quality is high as
the exact shape of the character hits the ribbon to leave and impression on
paper.
Line Printer
➢ Line printer is a high speed impact printer in which one typed line is printed
at a time. The speed of a line printer usually varies from 600 to 1200 lines-
per-minute or approximately 10 to 20 pages per minute.
Band Printer:
➢ A band printer (loop printer) is an impact printer . The set of characters are
permanently embossed on the band and this set cannot be changed unless
the band is replaced.
➢ The band itself revolves around hammers that push the paper against the
ribbon, allowing the desired character to be produced on the paper.
➢ However, band printers cannot be used for any graphics printing as the
characters are predetermined and cannot be changed unless the band is
changed.
➢ They offer better print quality, faster printing and the ability to create
prints that contain sophisticated graphics.
Advantages:
➢ They are noiseless, fast and can print text in different fonts.
Inkjet Printers
➢ In inkjet printers , the print head has several tiny nozzles, also called jets.
➢ As the paper moves past the print head, the nozzles spray ink onto it,
forming the characters and images.
➢ There is usually one black ink cartridge and one so-called color cartridge
containing ink in primary pigments (cyan, magenta, and yellow.
➢ While inkjet printers are cheaper than laser printers, they are more expensive
to maintain.
➢ The cartridges of inkjet printers have to be changed more frequently and the
special coated paper required to produce high-quality output is very
expensive.
➢ So the cost per page of inkjet printers becomes ten times more expensive
than laser printers.
➢ Therefore, inkjet printers are not well-suited for high-volume print jobs.
Laser Printer
➢ When a document is sent to the printer, the following steps takes place:
2. After the drum is charged, it is rolled in toner (a dry powder type of ink).
3. The toner sticks to the charged image on the drum. The toner is transferred
onto a piece of paper and fused to the paper with heat and pressure.
Plotters
➢ A plotter is used to print vector graphics with a high print quality. They
are widely used to draw maps, in scientific applications and in
applications like CAD, CAM and CAE
➢ A drum plotter is used to draw graphics on a paper that is wrapped
around a drum. It works by rotating the drum back and forth to produce
vertical motion. The pen which is mounted on a carriage is moved across
the width of the paper. Hence, the vertical movement of the paper and the
horizontal movement of the pen create the required design under the control of
the computer.
➢ In a flatbed plotter, the paper is spread on the flat rectangular surface of the plotter
and the pen is moved over it. Flatbed plotters are less expensive and used in many
smaller computing systems. In this type of plotter, the paper is not moved rather
plotting is done by moving an arm that moves a pen over paper.
PROGRAMMING PARADIGMS
➢ The style of writing programs and the set of capabilities and limitations that a
particular programming language has depends on the programming paradigm
it supports.
Monolithic programming:
➢ Therefore, all the actions required to complete a particular task are embedded
within the same application itself.
➢ This not only makes the size of the program large but also makes it difficult to
debug and maintain.
Procedural programming:
➢ A subroutine that needs the service provided by another subroutine can call that
subroutine.
Advantages
➢ The only goal is to write correct programs
Disadvantages
➢ No concept of reusability
➢ Requires more time and effort to write programs
➢ Modules are coded separately and once a module is written and tested
individually, it is then integrated with other modules to form the overall
program.
➢ With modules, many programmers can work on a single, large program, with each
working on a different module.
Disadvantages:
➢ Not data-centered, Global data is shared and therefore may get inadvertently
modified, Main focus is on functions
Object-oriented programming (OOP)
3. Functions that operate on data are tied together with the data.
4. Data is hidden and not accessible by external functions.
5. New data and functions can be easily added as and when required.
Q7) Explain the SDLC life cycle for the efficient design of a program with a neat diagram.
Model QP-3, Marks 8
2. Design:
3.Implementation:
➢ Designed algorithms are converted into program code using any of the high
level languages.
➢ The choice of language depends on the type of program like whether it is a
system or an application program.
➢ Program codes are tested by the programmer to ensure their correctness.
➢ While constructing the code, the development team checks whether the software is
compatible with the available hardware and other software components that were
mentioned in the Requirements Specification Document created in the first phase.
4.Testing:
➢ All the modules are tested together to ensure that the overall system works well
as a whole product.
➢ Although individual pieces of codes are already tested by the programmers in the
implementation phase, there is always a chance for bugs to creep in the program
when the individual modules are integrated to form the overall program structure.
➢ Software is tested using a large number of varied inputs also known as test
data to ensure that the software is working as expected by the users’ requirements
that were identified in the requirements analysis phase.
➢ Software Training and Support is a crucial phase which makes the end users
familiar with how to use the software.
➢ Moreover, people are often resistant to change and avoid venturing into an
unfamiliar area, so as a part of the deployment phase, it has become very crucial to
have training classes for the users of the software
6. Maintenance:
➢ Maintenance and enhancements are ongoing activities which are done to cope
with newly discovered problems or new requirements.
➢ Such activities may take a long time to complete as the requirement may call for
addition of new code that does not fit the original design or an extra piece of code
required to fix an unforeseen problem.
➢ As a general rule, if the cost of the maintenance phase exceeds 25% of the prior-
phases cost then it clearly indicates that the overall quality of at least one prior
phase is poor.
➢ In such cases, it is better to re-build the software (or some modules) before
maintenance cost is out of control.
ALGORITHMS
Decision: Decision statements are used when the outcome of the process depends on
some condition. For example, if x=y, then print “EQUAL”. Hence, the general form of
the if construct can be given as if condition then process.
Step 1: Input the first number as A
Step 2: Input the Second number as B
Step 3: IF A = B
Then PRINT “EQUAL”
ELSE
PRINT “ NOT EQUAL”
Step 4: END
Repetition: Repetition, which involves executing one or more steps for a number of
times, can be implemented using constructs such as while, do-while, and for loops.
These loops execute one or more steps until some condition is true.
FLOWCHART
Pseudocode:
➢ It is basically meant for human reading rather than machine reading, so it omits
the details that are not essential for humans. Such details include variable
declarations, system-specific code, and sub-routines.
➢ They consist of short English phrases that explain specific tasks within a program’s
algorithm. They should not include keywords in any specific computer language. The
sole purpose of pseudocodes is to enhance human understandability of the solution.
TYPES OF ERRORS
Q8) Discuss different types of error occur in program. Model QP-2, Marks 6
1. Run-time errors:
➢ Such errors occur when the program performs some illegal operation like
➢ Run-time errors may terminate program execution, so the code must be written
in such a way that it handles all sorts of unexpected errors rather terminating it
unexpectedly.
Syntax Errors: Syntax error is generated when rules of C programming language are
violated. For example, if we write int a: then a syntax error will occur since the correct
statement should be int a;
Semantic Errors: Semantic errors are those errors which may comply with rules of
the programming language but are not meaningful to the compiler. For example, if
we write, a * b = c; it does not seem correct. Rather, if written like c=a*b would
have been more meaningful.
3. Logical errors:
➢ Logical Errors are errors in the program code that result in unexpected and
undesirable output which is obviously not correct.
➢ Such errors are not detected by the compiler, and programmers must check
their code line by line or use a debugger to locate and rectify the errors.
➢ Logical errors occur due to incorrect statements. For example, if you meant
to perform c= a + b; and by mistake you typed c = a * b; then though this
statement is syntactically correct it is logically wrong.
4. Linker errors:
➢ Linker Errors occur when the linker is not able to find the function definition
for a given prototype.
➢ For example, if you write clrscr(); but do not include conio.h then a linker error
will be shown.
TESTING APPROACHES
➢ System testing checks the entire system. For example, if our program code
consists of three modules then each of the module is tested individually using
unit tests and then system test is applied to test this entire system as one
system.
Debugging Approaches
➢ Once located, errors are then isolated and fixed to produce an error-free
code.
Brute-Force Method:
Backtracking Method:
➢ This method works by locating the first symptom of error and then trace
backward across the entire source code until the real cause of error is
detected.
1.4 INTRODUCTION TO C
Characteristics of C
➢ Small size: C has only 32 keywords. This makes it relatively easy to learn
➢ Stable Language
➢ Quick Language : Since C Programs make use of operators and data types, they are
fast and efficient.
Q9) With Suitable Example- Explain the basic structure of C Program. Jan/Feb
2023, Marks 8
➢ Every program must contain one function that has its name as main().
➢ The source code file contains the source code of the program. The file extension of
any C source code file is “.c”.
➢ This file contains C source code that defines the main function and
maybe other functions.
➢ The main() is the starting point of execution when you successfully compile and
run the program.
➢ A C program in general may include even other source code files (with the file
extension .c).
Header file
➢ Conventionally, header files names ends with a “.h” extension and its name can
use only letters, digits, dashes, and underscores.
➢ While some standard header files are available in C, but the programmer may
also create his own user defined header files.
Object Files:
➢ Object files are generated by the compiler as a result of processing the source code
file.
➢ Linker uses this object file to produce an executable file (.exe file) by combining the of
object files together.
➢ Object files have a “.o” extension, although some operating systems including
Windows and MS-DOS have a “.obj” extension for the object file.
➢ The linker links the various object files to produce a binary file that can be
directly executed.
➢ The compiler translates the source code into an object code as shown in Fig 10.
➢ The object code contains the machine instructions for the CPU, and calls to the
operating system API(Application Programming Interface).
➢ Therefore, in next step, the object file is processed with another special program
called a linker.
➢ While there is a different compiler for every individual language, the same
linker is used for object files regardless of the original language in which the new
program was written.
USING COMMENTS
➢ The compiler ignores the comments when forming the object file. This means
that the comments are non-executable statements.
C TOKENS
CHARACTER SET IN C
KEYWORDS
Table 1.4: Keywords in C Language
➢ All keywords are basically a sequence of characters that have a fixed meaning.
➢ The keywords are for, while, do-while, auto break, case, char, continue, do,
double, else, enum, extern, float, goto, if, int, long, register, return, short,
signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile.
IDENTIFIERS
➢ Identifiers are names given to program elements such as variables, arrays and
functions.
Q10) What are the basic data types available in C? Jan/Feb 2023, Marks 6
1.4.3 VARIABLES
Q11) Explain the rules for forming identifiers names. Give examples for valid and invalid
identifiers for the same. Model QP-2, Marks 8
➢ When using a variable, we actually refer to address of the memory where the
data is stored. C language supports two basic kinds of variables.
➢ Numeric variables can be used to store either integer values or floating point
values.
• Numeric values may also be associated with modifiers like short, long,
signed and unsigned.
➢ Character variables can include any letter from the alphabet or from the
ASCII chart and numbers 0 – 9 that are put between single quotes.
Declaring Variables
➢ To declare a variable specify data type of the variable followed by its name.
float salary,
double balance_amoutn,
Initializing Variables
1.4.4 CONSTANTS
1.Integer constants
2.Floating-point constants
3.Character constants
4.String constants
• #define PI 3.14159
Declaring Constants
Rule 1: Constant names are usually written in capital letters to visually distinguish
them from other variable names which are normally written in lower case characters.
Note that this is just a convention and not a rule.
Rule 2: No blank spaces are permitted in between the # symbol and define keyword
Rule 3: Blank space must be used between #define and constant name and between
constant name and constant value
Rule 4: #define is a pre-processor compiler directive and not a statement.
Therefore, it does not end with a semi-colon.
➢ A stream acts in two ways. It is the source of data as well as the destination
of data.
➢ Streams are associated with a physical device such as the monitor or with
a file stored on the secondary memory. We have Text Stream and Binary Stream
as shown in Figure 1.4.5.
➢ In a text stream, sequence of characters is divided into lines with each line being
terminated with a new-line character (\n). On the other hand, a binary stream
contains data values using their memory representation.
Formatting Input/output:
Q12) Summarize the formatted input and output statements with suitable examples. Model
QP-3, Marks 6
Flag Description
- Left Justify within the data given field width
+ Displays the data with its numeric sign( either + or -)
# Used to provide additional specifiers like o,x, X,o,ox, oX for octal and hexa
decimal values respectively for values different than zero.
O The number is left padded with zeros
Example:
%6.3f means print floating point value of max 6 digits where 3 digits are
allotted for the digits after the decimal point.
printf(“\n Result: %6.3f”,
123.53435); output: Result:
123.534
Some examples of printf:
• printf(“\n Result: %d%c%f”,12,'a',2.3);
Output: Result: 12a2.300000
Output:
The number is
1
scanf():
➢ The scanf() function is used to read formatted data from the keyboard.
%[*][width][modifier]type
Rules to use scanf():
Rule 1: The scan function works until:
(a) the maximum number of characters has been processed
(b) a white space character is encountered, or
(c) an error is detected.
Rule 2: Every variable that has to be processed must have a conversion specification
associated with it. Therefore, the following scan statement will generate an error as
num3 has no conversion specification associated with it.
scanf("%d %d", &num1, &num2, &num3) ;
Rule 3: There must be a variable address for each conversion specification.
Therefore, the following scanf statement will generate an error as no variable address
is given for the third conversion specification.
scanf(*'%d %d %d", &numa, &num2) ;
The ampersand operator (&) before each variable name specifies the
address of that variable name.
Rule 4: An error will be generated if the format string is ended with a white space
character.
Rule 5: The data entered by the user must match the character specified in the control
string (except white space or a conversion specification), otherwise an error will be
generated and scan will stop its processing.
For example, consider the following scan statement.
scanf(*%d / %d", &num1, &num2) ; Here, the slash in the control string is
neither a white space character nor a part of conversion specification, so the
users must enter data of the form 21/46.
Rule 6: Input data values must be separated by spaces.
Rule 7: Any unread data value will be considered as a part of the data input in the
next call to scanf.
1. Explain the organization of Basic computer model with neat diagram. Jan/Feb 2023, Marks
8
2. Explain Input/Output statement in C Jan/Feb 2023, Marks 8
3. List and explain any two input-output devices. Jan/Feb 2023, Marks 4
4. Data types
5. Define Variable. Explain the rules to declare a variable with example. Jan/Feb 2023, Marks
6
6. With Suitable Example- Explain the basic structure of C Program. Jan/Feb 2023, Marks 8
7. Define Computer. Describe the various types of computers based on speed, memory and
cost. Model QP-1, Marks 8
8. Develop and algorithm to find the area and perimeter of a circle. Also define an algorithm.
Model QP-1, Marks 6
9. Write a short notes of characteristics of computer. Model QP-1, Marks 6
10. What is variable? What are the rules to construct variable. Classify the following as
valid/invalid identifiers. Model QP-1, Marks 8
i) Num2, ii) $num1 iii) +add iv) a_2 v) 199_space vi) _apple vii) #12
11. Draw a flow chart and C program which takes as input p,t,r. Compute the simple interest
and display the result. Model QP-1, Marks 6
12. Write a note on the following operators i) Relational ii) Logical iii) Conditional. Model
QP-1, Marks 6
13. Explain the structure of C program in detail. Write a simple program to demonstrate the
components in the structure of a C program. Model QP-2, Marks 8
14. Demonstrate formatted output of an integer in C with suitable example. Model QP-2, Marks
6
15. Discuss different types of error occur in program. Model QP-2, Marks 6
16. Explain the rules for forming identifiers names. Give examples for valid and invalid
identifiers for the same. Model QP-2, Marks 8
17. Mention various output devices and explain hardcopy devices. Model QP-1, Marks 6
18. Discuss the variants of microcomputer that are widely used today. Model QP-1, Marks 6
19. Explain the components of a computer with a neat diagram. Model QP3, Marks 6
20. Describe any three input devices. Model QP-3, Marks 6
21. Design an algorithm, flowchart and program to compute the area of a circle. Model QP-3,
Marks 8
22. Summarize the formatted input and output statements with suitable examples. Model QP-
3, Marks 6
23. Explain the SDLC life cycle for the efficient design of a program with a neat diagram.
Model QP-3, Marks 8
MODULE 2
MODULE 2
OPERATORS IN C, DECISION CONTROL AND LOOPING STATEMENTS
1.What is type casting? Explain its types with suitable examples (Feb23 6 marks)
TYPE CASTING
Definition: Type casting, also known as type conversion, is the explicit conversion of a variable
from one data type to another. This is done to ensure that operations are performed on compatible
data types or to optimize the use of memory.
In C, type casting can be categorized into two types:
2.Write a c program to find the largest of three numbers with trinary operator.(Feb 23
6marks)
int main()
{
int a, b, c;
int largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
printf("The largest number is: %d\n", largest);
return 0;
}
Output
Enter three numbers: 5 8 3
The largest number is: 8
(i).break Statement
The break statement is used to terminate loops or to exit from a switch.
Syntax
Jump-statement
Break;
Example:
#include<stdio.h>
void main()
{
int i=0;
while(i<=5)
{
i++;
if(i==3)
break;
printf(“%d\t”,i);
}
}
(ii).Continue statement:
The continue statement tellsthe compiler “Skip the following Statements and continue with the next
Iteration.
Syntax: Jump-statement;
Continue;
Example:
#include<stdio.h>
void main()
{
int i=0; while(i<=5)
{
i++;
if(i==3)
continue; printf(“%d\t”,i);
}
}
(iii).goto statement
C supports the “goto” statement to branch unconditionally from one pointto another in the program.
Syntax :
goto label;
.............
.............
.............
label: statement;
Example:
Write a program using goto statement
#include <stdio.h>
int main()
{
int i = 0;
loop: printf("i = %d\n", i);
i++; if (i < 3)
goto loop;
return 0;
}
(iv).return statement: The return statement terminates the execution of a function and returns
control to the calling function.
Syntax :
Jump-statement:
return expression;
Example:
(i)simple if: This is a one way selection statement which helps the programmer to execute orskip
certain block of statements based on the particular condition.
Syntax:
if(conditional_expression)
{
True block statements;
}
FLOW CHART
Example
#include <stdio.h>
int main()
{
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0)
printf("Positive\n");
return 0;
}
(ii) if-else statement: This is a two way selection statement which executes true block or falseblock
of statements based on the given condition.
Syntax:
if (conditional expression) FLOW CHART
{
True block statement;
}
else
{
False block statement;
}
Example:
#include <stdio.h>
int main()
{
int number;
scanf("%d", &number);
if (number > 0)
printf("Positive\n");
else if (number < 0)
printf("Negative\n");
else
printf("Zero\n");
return 0;
}
(iii) if-else if/Nested if Statement: An if statement within another if statement is called as a nested
if statement.
Syntax:
if(conditional_expression1)
{
if(conditional_expression2)
statement1;
} FLOW CHART
else
{
statement2;
}
}
else
{
statement 3;
}
statement x;
Example:
#include <stdio.h>
int main()
{
int number;
scanf("%d", &number);
if (number > 0)
printf("Positive\n");
else if (number < 0)
printf("Negative\n");
else printf("Zero\n");
return 0;
}
(iv) Switch Statement: A switch statement tests the value of a variable and compares it with
multiple cases. Once the case match is found, a block of statements associated with that particular
case is executed.
Syntax:
switch (expression)
{
case value1: if expression == value1
break;
case value2: if expression == value2
break;
default: if expression does not match any case
}
FLOW CHART
#include <stdio.h>
int main()
{
int num = 1;
switch (num)
{
case 1: printf("One\n");
break;
case 2: printf("Two\n");
break;
default: printf("Other\n");
}
return 0;
}
2.4 Operators
5.Explain any 5 types of operators in c language with the illustrative examples? (or) example
the various operators in c ( june23/jan 24 10marks)
1.Arithmetic Operators:
Example:
Write a program to perform arithmetic operations
int main()
{
int a, b;
input printf("Enter the first number: ");
scanf("%d", &a);
printf("Enter the second number: ");
scanf("%d", &b);
printf("Addition: %d + %d = %d\n", a, b, a + b);
printf("Subtraction: %d - %d = %d\n", a, b, a - b);
printf("Multiplication: %d * %d = %d\n", a, b, a * b);
printf("Division: %d / %d = %d\n", a, b, a / b);
printf("Modulus: %d %% %d = %d\n", a, b, a % b);
return 0;
}
2.Relational Operators:
Example:
Write a program using relational operator
#include <stdio.h>
int main()
{
int a, b;
printf("Enter the value for a: ");
scanf("%d", &a);
printf("Enter the value for b: ");
scanf("%d", &b);
printf("a == b: %d\n", a == b);
printf("a != b: %d\n", a != b);
printf("a > b: %d\n", a > b);
printf("a < b: %d\n", a < b);
printf("a >= b: %d\n", a >= b);
printf("a <= b: %d\n", a <= b);
return 0;
}
3.Equality operator
Example:
Write a c program to check equal or not
#include <stdio.h>
int main()
{
int a = 5;
int b = 10;
if (a == b)
{
printf("a is equal to b\n");
}
else
{
printf("a is not equal to b\n");
}
return 0;
}
4.Assignment Operators
Operator Syntax Description Example Result
Simple Assigns the value on the right to the
= x= 10; x becomes 10
Assignment variable on the left.
Example:
Write a simple program using assignment operator
#include <stdio.h>
int main()
{
int x = 5;
x += 3;
printf("x = %d\n", x);
return 0;
}
5.Conditional Operator:
Syntax
Expression1 ? Expression2 : Expression3
Expression1→ Condition
Expression2→ Statement followed if condition is true
Expression3→ Statement followed if condition is false
Example:
write a program using condition operator
#include <stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
const char* eligibility = (age >= 18) ? "eligible" : "not eligible";
printf("You are %s to vote.\n", eligibility);
6. write a c program to find roots of quadratic equation by accepting the coefficient . Print
appropriate message (June2023 /Feb 23
10marks)
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
float a,b,c,x1,x2,disc;
printf("Enter the values of a,b,c\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
printf("Invalid Input\n");
exit(0);
}
disc=b*b-4*a*c;
if(disc>0)
{
printf("Roots are Real and Distinct\n");
x1=((-b)+sqrt(disc))/(2*a);
x2=((-b)-sqrt(disc))/(2*a);
printf("Root1= %f\n Root2= %f\n",x1,x2);
}
else if(disc==0)
{
printf("Roots are Real and Equal\n ");
x=(-b)/(2*a);
printf("Root1=Root2=%f\n",x1);
}
else
{
printf("Roots are Imaginary\n");
x1=(-b)/(2*a);
x2=(sqrt(fabs(disc)))/(2*a);
printf("Root1= %f +i %f\n",x1,x2);
printf("Root2= %f -i %f\n",x1,x2);
}
}
Output:
Case 1:
Enter the values of a,b,c 1 -3 2
Roots are Real and Distinct
Root1= 2.000000
Root2= 1.000000
Case 2:
Enter the values of a,b,c 1 -4 4
Roots are Real and Equal
Root1=Root2= 2.000000
Case 3:
Enter the values of a,b,c 1 2 5
Roots are Imaginary
Root1= -1.000000 +i 2.236068
Root2= -1.000000 -i 2.236068
Syntax:
initialization;
while(test condition)
{
set of statements to be executed
FLOW CHART
(ii) do-while loop : A do-while loop is similar to the while loop except that the condition is always
executed after the body of a loop. It is also called an exit-controlled loop. The body is executed if and
only if the condition is true.If the condition is true, then it will again execute the body of a loop otherwise
control is transferred out of the loop.
Syntax
initialization;
do{
FLOW CHART
(iii)for loop : A for loop is a more efficient loop structure in 'C' programming which is used when the
loop has to be traversed for a fixed number of times.
Syntax:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
FLOW CHART
1
1 2
1 2 3
1 2 3 4
#include <stdio.h>
int main()
{
int i, j, k, n;
printf("Enter the number of rows: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n - i; j++)
{
printf(" ");
}
for (k = 1; k <= i; k++)
{
printf("%d", k);
if (k < i)
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
Output
1
12
123
1234
9. Write a C program to find the largest of 3 numbers using nested if statements (jan24
4marks)
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a >= b)
{
if (a >= c)
{
Output
Enter three numbers: 10 25 15
The largest number is 25
1.What is type casting? Explain its types with suitable examples (Feb23 6 marks)
2.Write a c program to find the largest of three numbers with trinary operator(Feb23 6marks)
3.List and explain unconditional branching statements with examples.(Feb23/Jan24 6/4
marks)
4.List the conditional branching statements in C. Explain with example (or) Explain the different
forms of if statements with flowcharts (Feb 23/Jan24 10/6marks)
5. Explain any 5 types of operators in c language with the illustrative examples? (or) example the
various operators in c ( June23/Jan24 10marks)
6. write a c program to find roots of quadratic equation by accepting the coefficient . Print
appropriate message (June2023 /Feb23 10marks)
7. what are iterative statements? explain 3 types of iterative statements with their syntax.
(Feb/june23 10/8 marks)
8. write a c program to print the following pattern ( June/July 2023 10marks)
1
1 2
1 2 3
1 2 3 4
9. Write a C program to find the largest of 3 numbers using nested if statements (Jan24 marks)
**********************************
Module 3
3.9 Recursion 3 – 22
MODULE 3
FUNCTIONS AND ARRAYS
3.1 Array- 2D array
1.Define an array. Explain with an example. how to declare and initialize 2D-array(Feb23
6marks)
Definition:-Array is a collection of elements of same data type. The elements are stored sequentially
one after the other in memory
Syntax
data_type array_name[size1][size2];
where,
data_type: is the type of data to be stored and processed in the computer’s memory
array_name: is a valid identifier representing name of the array.
[size1]: indicates number of rows in the array
[size2]: indicates the number of columns in the array.
Example:
int matrix[2][3] = {
{1, 2, 3}, // First row
{4, 5, 6} // Second row
}
2. Partial Initialization
Syntax:
type arrayName[rows][columns] = {
{value1, value2, ...}, {value1, ...},
...
};
Example:
int matrix[2][3] = {
{1, 2}, // First row (third element defaults to 0)
{4} // Second row (remaining elements default to 0)
};
type arrayName[][columns] = { {value1, value2, ..., valueN}, {value1, value2, ..., valueN}, ... };
Example:
Syntax:
type arrayName[rows][columns];
Example:
int matrix[2][3];
The feasible way of accessing elements in a two dimensional array is by using nested loops.
Example:
#include <stdio.h>
int main()
{
int array[2][2] = { {1, 2}, {3, 4} };
printf("%d %d\n%d %d\n", array[0][0], array[0][1], array[1][0], array[1][1]);
return 0;
}
Output:
1 2
2 4
Output
Enter the number to search: 10
Element 10 found at index 3.
Output
Enter elements for matrix A:
A[0][0]: 1 A[0][1]: 2 A[0][2]: 3 A[1][0]: 4 A[1][1]: 5 A[1][2]:6 A[2][0]: 7 A[2][1]: 8 A[2][2]: 9
Enter elements for matrix B:
B[0][0]: 9 B[0][1]: 8 B[0][2]: 7 B[1][0]: 6 B[1][1]: 5 B[1][2]: 4 B[2][0]: 3 B[2][1]: 2 B[2][2]: 1
Matrix A:
123
456
789
Matrix B:
987
654
321
Matrix Sum:
10 10 10
10 10 10
10 10 10
Example:
int n,x;
printf("Enter the value of n\n"); scanf("%d",&n);
x=sum(n);
printf("Sum of natural numbers=%d\n",x);
}
int sum(int n)
{
(ii) Call by reference or Argument passing by reference :- when the address of the variable is
passed to the function during its invocation such a function is called as call by reference.C does not
support directly passing by reference. It is done indirectly by passing the address of the variable and
changing the value of the variable through its address.
int a,b;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
printf("Before Swapping\n a=%d\t b=%d\n",a,b);
swap(&a, &b);
printf("After Swapping\n a=%d\t b=%d\n",a,b);
}
void swap(int *a, int *b)
{
int temp; temp=*a;
*a=*b;
*b=temp;
}
5.Write a C program to sort the elements using bubble sort technique by passing arrays as
function arguments(Feb24 6marks)
#include <stdio.h>
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-9
Principles of Programming using C BPOPS103/203
Output
Original array: 64 25 12 22 11
Sorted array: 11 12 22 25 64
syntax:
return_type function_name(argument _list);
Where,
return_type :- is the data type of the value that is returned or sent from the function.
function_name :-function should be given a descriptive name
argument _list :- contains type and names of the variables that must be passed to the function.
Example
#include <stdio.h>
int multiply(int a, int b);
int main()
{
int result = multiply(4, 5);
printf("Product: %d\n", result);
return 0;
}
int multiply(int a, int b)
{
return a * b;
}
(ii)Function definition or Defining a function :- The declared function must define the same to
perform the specific task.
Syntax
return_type function_name(argument _list)
{
local_variable_declaration;
Body of the function;
}
Where,
return type :- when the function is called the function may or may not return a value
If the function returns a value then the return_type will be any appropriate data type (int, float, char
etc) and we use the keyword “return” to return the value.
If the function does not return a value then the return_type will be “void” and no need to use the
keyword “return”
function_name:- is the name of the function.
argument _list :- these are also called as parameters. the argument_list refers to the type order and
number of parameters of the function.
local_variable_declaration:- these are temporary variables which are required only within this
function.
function _body: - The body of the function contains the collection of statements that define what the
function does.
when the program makes the function call the program control is transferred to the called function.
This called function performs the defined task and returns the program control back to the main( )
function.
Example:
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
int x = 5; int y = 10;
int sum = add(x, y);
printf("Sum: %d\n", sum);
return 0;
}
7.Write a c program to swap two numbers using call by reference method(June23 6marks)
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int num1 = 5, num2 = 10;
printf("Before swapping:\n");
printf("num1 = %d, num2 = %d\n", num1, num2);
swap(&num1, &num2);
printf("After swapping:\n");
printf("num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
Output:
Before swapping: num1 = 5, num2 = 10
After swapping: num1 = 10, num2 = 5
𝑛!
𝑛𝐶𝑟 =
(𝑛 − 𝑟)! 𝑟!
#include <stdio.h>
int factorial(int num)
{
int fact = 1;
for (int i = 1; i <= num; i++)
{
fact *= i;
}
return fact;
}
int combination(int n, int r)
{
return factorial(n) / (factorial(r) * factorial(n - r));
}
int main()
{
int n, r;
printf("Enter n and r: ");
scanf("%d %d", &n, &r);
printf("C(%d, %d) = %d\n", n, r, combination(n, r));
return 0;
}
Output
Enter n and r: 5 2
C(5, 2) = 10
Example
#include <stdio.h>
void show()
{
auto int value = 5;
printf("value = %d\n", value);
value++;
}
int main()
{
show();
return 0;
}
Example:
#include <stdio.h>
int main()
{
register int count;
for (count = 1; count <= 3; count++)
{
printf("%d ", count);
}
printf("\n");
return 0;
}
Example:
#include <stdio.h>
void show()
{
static int value = 0;
value++;
Example
#include <stdio.h>
int globalVar = 42;
void printGlobalVar()
{
printf("globalVar = %d\n", globalVar);
Declaring Arrays
An array is declared by specifying the type of its elements and the number of elements it can hold.
The general syntax for declaring an array is:
Syntax:
type arrayName[arraySize];
type: The data type of the elements (e.g., int, float, char).
arrayName: The name of the array.
arraySize: The number of elements the array can hold.
Initializing Arrays
You can initialize arrays either at the time of declaration or later in the code. Here are some ways to
Initialize arrays.
(i)Static Initialization:
You can initialize an array with specific values at the time of declaration using curly braces {}.
Example: int numbers[5] = {1, 2, 3, 4, 5};
(ii)Partial Initialization:
If you provide fewer initializers than the size of the array, the remaining elements are automatically
initialized to zero.
(iii)Implicit Size:
If you omit the size of the array during initialization, the compiler determines the size based on the
number of initializers.
(iv)Dynamic Initialization:
You can also initialize an array after declaration using a loop.
Example:
int numbers[5];
for (int i = 0; i < 5; i++)
{
}
return 0;
}
Output
Enter elements of the 3x3 matrix: 1 2 3 4 5 6 7 8 9
Matrix:
123
456
789
Transpose:
147
258
369
(i)Function Declaration or Function prototype :- It will inform the compiler about the return type,
function name and number of arguments along with the data types.
Syntax:
(ii)Function call or calling function :- invoking the function with valid number of arguments and
valid data type is called as function call.
Syntax:
function_name(argumement_list);
Example:-
large (m,n);
The function can be invoked in various ways
(iii)Function definition or Defining a function :- The declared function must define the same to
perform the specific task.
Syntax
return_type function_name(argument _list)
{
local_variable_declaration;
Body of the function;
}
Example:
C program to find area of circle using functions
#include<stdio.h>
Float area(float r);
void main();
{
float r,x;
printf("Enter the radius\n"); scanf("%f",&r);
x=area(r);
printf("Area ofcircle= %f\n",x);
}
float area(float r)
{
float x; x=3.142*r*r;
return x;
}
3.9 Recursion
14. Define recursion. write a c program to find factorial of ‘n’ using recursion(Jan24 5marks)
Recursion :- when a function calls itself again and again it is called as recursion.It is a powerful
technique of writing complex algorithms in an easier way.
int factorial(int n)
{
if(n==0)
return 1;
else
return n*factorial(n-1);
}
Output
Enter the value of n: 5
The factorial of 5 is 120
Here,
a[0] holds the first element in the arraya[1]
You can declare an array and set its initial values in one line.
2.Partial Initialization
If you provide fewer initializers than the array size, the remaining elements are automatically set to
0.
3.Implicit Size
You can let the compiler determine the size based on the number of initializers.
Example: int numbers[] = {10, 20, 30, 40, 50}; // Compiler sets size to 5
4.Dynamic Initialization
numbers[i] = i * 2; // Initializes to 0, 2, 4, 6, 8
#define ROW1 2
#define COL1 3
#define ROW2 3
#define COL2 2
int main()
printf("\n");
return 0;
1. Local Scope
Definition: Variables declared inside a function or block.
Accessibility: These variables are accessible only within the function or block where they are
declared.
Lifetime: The variable exists only while the function or block is executing. Once the function or
block exits, the variable is destroyed.
Example:
void myFunction()
{
int localVar = 10;
printf("%d\n", localVar);
}
2. Global Scope
Definition: Variables declared outside of any function or block.
Accessibility: These variables are accessible from any function or block in the file where they are
declared.
Lifetime: The variable exists for the entire duration of the program.
Example:
int globalVar = 20;
void myFunction()
{
printf("%d\n", globalVar);
}
5. Function Scope
Definition: This is specific to labels used with goto statements. Labels are not variables, but they
represent a form of scope in C.
Accessibility: Labels are accessible anywhere in the function where they are defined.
Lifetime: The lifetime is the entire duration of the function's execution.
Example:
void myFunction()
{
goto label;
printf("Label reached\n");
}
Bubble sort: The sorting algorithm is a comparison based algorithm in which each pair of adjacent
elements is compared and the elements are swapped if they are not in order. This algorithm is not
suitable for large datasets as its average and worst case time complexity areof O(n2). where n is the
number of items.
}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
/*C program to sort numbers in ascending order using selection sort technique*/
#include<stdio.h>
void main()
{
int a[20],n,i,j,temp;
printf("Enter total elements\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];a[i]=a[j]; a[j]=temp;
}
}
}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
The process of finding a particular element in the large amount of data is called searching.
Linear search:- A Linear search is also called as sequential Search. In this technique we searchfor a
given specific element called as key element in the large list of data in sequential order. If the key
element is present in the list of data then the search is successful otherwise search isunsuccessful.
Benefits:
• Simple approach
Disadvantages:
• Less efficient if the array is large
Binary Search: It is fast search algorithm which works on the principle of divide and conquer.for
this algorithm to work properly the data collection should be in the sorted form
3. Continue steps 1. and 2. until either the value is found or there are no more elements to
examine
Advantages:
• Very efficient searching technique.
Disadvantages:
• Array element should be sorted.
There are a number of operations that can be performed on arrays.These operations include the
following.
𝑛!
𝑛𝐶𝑟 =
(𝑛 − 𝑟)! 𝑟!
****************************
Table of Contents
MODULE: 4
MODULE: 4
STRINGS AND POINTERS
1. Define String. Explain any 4 string manipulation function with suitable example
5m, Aug 2022
● A string is a null-terminated character array. This means that after the last character, a
null character (‘\0’) is stored to signify the end of the character array.
● The general form of declaring a string is
char str[size];
● For example if we write,
char str[] = “HELLO”;
We are declaring a character array with 5 characters namely, H, E, L, L and O. Besides,
a null character (‘\0’) is stored at the end of the string. So, the internal representation of
the string becomes- HELLO’\0’.
Note that to store a string of length 5, we need 5 + 1 locations (1 extra for the null
character).
The string length function can be used to find the length of the string in bytes.
Syntax: length = strlen(str);
String length function has one parameter str which is a string. It returns an integer value.
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-1
Principles of Programming using C BPOPS103/203
Ex:
char str[10] = “CBIT”;
int length;
length = strlen(str); //4
Note: str = ‘\0’
length = strlen(str); //0
It is used to compare two strings. It takes the two strings as a parameter and returns an
integer value.
Syntax: result = strcmp(first, second);
result = 0 -> first = second
result > 0 -> first > second
result < 0 ->first < second
Example:
int res;
res = strcmp(“cat”, “car”); //res > 0
res = strcmp(“pot”, “pot”); //res = 0
res = strcmp(“big”, “small”); //res < 0
IV. strcat( ) – String Concatenate
It is used to concatenate or join two strings together. It has two parameters where the
combined string will be stored in the (destination) first parameter.
Syntax: strcat(destination, source);
Example: char first[30] = “Computer”;
char last[30] = “Programming”;
strcat(first, last);
Note: strcat( ) stops copying when it finds a NULL character in the second string.
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-2
Principles of Programming using C BPOPS103/203
null character (‘\0’) is stored at the end of the string. So, the internal representation of the
Note that to store a string of length 5, we need 5 + 1 locations (1 extra for the null
character).
The name of the character array (or the string) is a pointer to the beginning of the string.
str[0] 1000 H
str[1] 1001 E
str[2] 1002 L
str[3] 1003 L
str[4] 1004 O
str[5] 1005 \0
1. Explain how the strings are declared and initialized? 10m, Jan 2024
Declaration of a string:
A string is declared like an array of character.
Syntax: data type string name [size];
Example: char str [10];
Initialization of a string:
Syntax: data type string name [size]=value;
Example:
Char str []={‘H’, ’e’, ’l’, ’l’, ’o’, ’\0’};
Char str [10]=”HELLO”;
Char str[5]=”HELLO”;
The compiler created a character array of size 10, stores the value “HELLO” in it, and
finally terminates the value with a null character.
Rest of the element in the array is automatically initialized to NULL.
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-3
Principles of Programming using C BPOPS103/203
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-4
Principles of Programming using C BPOPS103/203
General form:
data_type *pointer_name;
The asterisk (*) tells that the variable pointer_name is a pointer variable.
Pointer_name is a identifier.
pointer_name needs a memory location.
pointer_name points to a variable of type data_type which may be int, float, double etc..
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-5
Principles of Programming using C BPOPS103/203
Initialization of pointers
Example:
int x;
int *p
p = &x;
1. What is pointer? Discuss pointer arithmetic with suitable C code . 10m,Jan 2021
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-6
Principles of Programming using C BPOPS103/203
2. Develop a program using pointer to compute the sum, mean and standard
deviation of all element stored in array of N real number 10m,Jan 2021
#include<stdio.h>
#include<conio.h>
#include<math.h> main()
{
float a[10], *ptr, mean, std, sum=0, sumstd=0;
int n,i;
printf("Enter the no of elements\n");
scanf("%d",&n);
printf("Enter the array elements \n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a; for(i=0;i<n;i++)
{
sum=sum+ *ptr; ptr++;
}
mean=sum/n; ptr=a; for(i=0;i<n;i++)
{
sumstd=sumstd + pow((*ptr - mean),2);
ptr++;
}
std = sqrt(sumstd/n); printf("Sum=%.3f\t",sum); printf("Mean=%.3f\t",mean);
printf("Standard deviation=%.3f\t", std);
}
4.6 Types of pointers,
1. Explain the difference between a null pointer and a void pointer. Or explain about
the types of pointers?
A null pointer which is a special pointer value that is known not to point anywhere. This
means that a NULL pointer does not point to any valid memory address.
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-7
Principles of Programming using C BPOPS103/203
To declare a null pointer you may use the predefined constant NULL,
int *ptr = NULL;
You can always check whether a given pointer variable stores address of some variable
or contains a null by writing,
if ( ptr == NULL)
{ Statement block;
}
Void Pointer
A generic pointer is pointer variable that has void as its data type.
The generic pointer, can be pointed at variables of any data type.
It is declared by writing
void *ptr;
You need to cast a void pointer to another kind of pointer before using it.
Generic pointers
Generic Pointers are used when a pointer has to point to data of different types at
different times.
#include<stdio.h>
int main()
{
int x=10;
char ch = ‘A’;
void *gp;
gp = &x;
printf("\n Generic pointer points to the integer value = %d", *(int*)gp);
gp = &ch;
printf("\n Generic pointer now points to the character %c", *(char*)gp);
return 0;
}
2. Differentiate between scanf() and gets()? 5m, jan2022
Scanf():
The string can be read using scanf() by writing scanf(“%s”,str);
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-8
Principles of Programming using C BPOPS103/203
The main drawback with this function is that it terminates as soon as it finds a blank
space.
Example: if the user enters “Hello world”, then str will contain only “Hello”. This is
because the moment a blank space is encountered, the string is terminated by the scanf()
function.
gets() function.
Syntax: gets(str);
gets() is a simple function that overcomes the drawbacks of scanf().
The gets() function takes the starting address of the string which will hold the input .
4. Write a C program to swap two variables (or two strings or two numbers) using
pointers?
Or Write a C program to swap two numbers using call by reference program?
10m, jan 2024
#include <stdio.h>
void swap_numbers(int *ptr1, int *ptr2) {
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-9
Principles of Programming using C BPOPS103/203
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
void main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
swap_numbers(&num1, &num2);
printf("The swapped numbers are: %d %d", num1, num2);
}
5. Write a C program to copy one string to another string using strcpy()? 5m,june 23
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "C programming";
char str2[20]; // copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
return 0;
}
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-10
Principles of Programming using C BPOPS103/203
*******************************************************
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-11
Dr. T. THIMMAIAH INSTITUTE OF TECHNOLOGY
(Estd. 1986) Oorgaum, Kolar Gold Fields, Karnataka – 563120
(Affiliated to VTU, Belgaum, Approved by AICTE - New Delhi)
NAAC Accredited 'A' Grade, NBA Accredited for CSE, ECE & Mining Engg Programs
Table of Contents
MODULE: 5
MODULE: 5
STRUCTURE DECLARATION:
➢ A structure is declared using the keyword struct followed by a structure name.
➢ All the variable of the structure is declared within the structure.
syntax.
struct tagname
{ data_type var-name;
data_type var-name;
...
};
struct student
{ int r_no;
char name[20];
char course[20];
float fees;
};
➢ Memory is allocated for the structure when we declare a variable of the structure.
➢ Each variable name declared within the structure is called member of the structure
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-1
Principles of Programming using C BPOPS103/203
INITIALIZATION OF STRUCTURES
➢ When the user does not explicitly initialize the structure then C automatically does
that.
➢ For int and float members, the values are initialized to zero and char and string
members are initialized to the ‘\0’ by default.
struct struct_name
{ data_type member_name1;
data_type member_name2;
data_type member_name3;
OR
struct struct_name
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................................
};
❖ Uses of structure:
➢ Related data items of dissimilar data types can be grouped under a common name.
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-2
Principles of Programming using C BPOPS103/203
➢ When more than one data has to be returned from the function, then structures can be used.
Typedef is a keyword that allows the programmer to create new data type name for an
already existing datatype.
Syntax:
Example:
#include<stdio.h>
void main( )
AMOUNT p,si;
TIME t;
RATE r;
scanf(“%f%f%f”,&p,&t,&r);
si=(p*t*r)/100;
printf(“si=%f\n”,si);}
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-3
Principles of Programming using C BPOPS103/203
Advantages of typedef:
3.A complex and lengthy declaration can be reduced to short and meaningful declaration
3. Implement structures to read, write and compute average- marks of the students,
list the students scoring above and below the average marks for a class of N
students.
#include<stdio.h>
student
{
char name[20];
float m1,m2,m3,total;
};
main()
{
int i,j,k,m,n,above avg[10],below avg[10]; float T=0,AVG=0;
struct student s[10];
printf("Enter number of students.\n"); scanf("%d",&n);
printf("Enter the details of students.\n"); for (i=0;i<n;i++)
{
printf("Enter the details of student %d \n",i+1); printf("Enter name \n");
scanf("%s",s[i].name); printf("Enter m1,m2,m3 \n");
scanf("%f%f%f",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=(s[i].m1+s[i].m2+s[i].m3); T=T+s[i].total;
}
printf("Details of Students.\n"); printf("Name\t m1\t m2\t m3\t total\n"); for
(i=0;i<n;i++)
printf("%s\t%f\t%f\t%f\t%f\t\n",s[i].name,s[i].m1,s[i].m2,s[i].m3,s[i].total);
AVG=T/n;
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-4
Principles of Programming using C BPOPS103/203
#include<stdio.h>
int main()
{ struct student
{ int roll_no;
char name[80];
float fees;
char DOB[80];
};
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-5
Principles of Programming using C BPOPS103/203
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-6
Principles of Programming using C BPOPS103/203
stud1.DOB.dd = 15;
stud1.DOB.mm = 09;
stud1.DOB.yy = 1990;
stud1.fees = 45000;
The code given below passes a structure to the function using call-by-value method.
#include<stdio.h>
typedef struct
{
int x;
int y;
}POINT;
void display(POINT);
main()
{
POINT p1 = {2, 3};
display(p1);
return 0;
}
void display( POINT p)
{
printf("%d %d", p.x, p.y);
}
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-7
Principles of Programming using C BPOPS103/203
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-8
Principles of Programming using C BPOPS103/203
➢ Here the structure node will contain two types of data- an integer val and next
that is a pointer to a node.
5.3 UNION
➢ Like structure, a union is a collection of variables of different data types. The only
difference between a structure and a union is that in case of unions, you can only
store information in one field at any one time.
➢ Thus unions are used to save memory. They are useful for applications that
involve multiple members, where values need not be assigned to all the members
at any one time.
a. DECLARING A UNION
union union-name
data_type var-name;
data_type var-name;
...
};
➢ Again, the typedef keyword can be used to simplify the declaration of union
variables.
➢ The most important thing to remember about a union is that the size of an
union is the size of its largest field. This is because a sufficient number of
bytes must be reserved to store the largest sized field.
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-9
Principles of Programming using C BPOPS103/203
only difference between a structure and a union is that in case of unions, you
can only store information in one field at any one time.
➢ Thus unions are used to save memory. They are useful for applications that
involve multiple members, where values need not be assigned to all the
members at any one time.
A member of a union can be accessed using the same syntax as that of a structure. To
access the fields of a union, use the dot operator(.). That is the union variable name
followed by the dot operator followed by the member name.
c. INITIALIZING UNIONS
➢ It is an error to initialize any other union member except the first member
{ int x, y;
};
int x;
int y;
};
main()
{ POINT1 P1 = {2,3};
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-10
Principles of Programming using C BPOPS103/203
POINT2 P2;
P2. x = 4;
P2.y = 5;
return 0;
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-11
Principles of Programming using C BPOPS103/203
RED (in our case), has the value of 0. The rest of the undefined constants have a value 1
more than its previous one. So in our example,
RED = 0, BLUE = 1, BLACK = 2, GREEN = 3, YELLOW = 4, PURPLE = 5, WHITE
=6
➢ The syntax for declaring a variable of an enumerated data type can be given as,
enumeration_name variable_name;
➢ So to create a variable of COLORS, we may write:
enum COLORS bg_color;
#include<stdio.h>
struct student
char name[20];
float m1,m2,m3,total;
};
main()
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-12
Principles of Programming using C BPOPS103/203
scanf("%f%f%f",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=(s[i].m1+s[i].m2+s[i].m3); T=T+s[i].total;
printf("%s\t%f\t%f\t%f\t%f\t\n",s[i].name,s[i].m1,s[i].m2,s[i].m3,s[i].total);
AVG=T/n;
k=0;
for (i=0;i<n;i++)
if (s[i].total> AVG)
aboveavg[j]=i; j++;
else
belowavg[k]=i; k++;
printf("%s %f\n",s[aboveavg[i]].name,s[aboveavg[i]].total);
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-13
Principles of Programming using C BPOPS103/203
printf("%s %f\n",s[belowavg[i]].name,s[belowavg[i]].total);
stdin
PROGRAM
stderr
SCREEN
stdout
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-14
Principles of Programming using C BPOPS103/203
MODE DESCRIPTION
Open a text file for reading. If the stream (file) does not exist then an error will be
r
reported.
Open a text file for writing. If the stream does not exist then it is created otherwise if
w
the file already exists, then its contents would be deleted
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-15
Principles of Programming using C BPOPS103/203
Open a text file for both reading and writing. The stream will be positioned at the
r+ beginning of the file. When you specify "r+", you indicate that you want to read the
file before you write to it. Thus the file must already exist.
Open a text file for both reading and writing. The stream will be created if it does not
w+
exist, and will be truncated if it exist.
Open a text file for both reading and writing. The stream will be positioned at the end
a+
of the file content.
❖ fscanf()
▪ The fscanf() is used to read formatted data from the stream. The syntax of
the fscanf() can be given as,
int fscanf(FILE *stream, const char *format,…);
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-16
Principles of Programming using C BPOPS103/203
▪ The fscanf() is used to read data from the stream and store them
according to the parameter format into the locations pointed by the
additional arguments.
#include<stdio.h>
main()
{ FILE *fp;
char name[80];
int roll_no;
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{ printf("\n The file could not be opened");
exit(1);
}
printf("\n Enter the name and roll number of the student : ");
fscanf(stdin, "%s %d", name, &roll_no); /* read from keyboard */
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);
// READ FROM FILE- Student.DAT
fscanf(fp, "%s %d", name, &roll_no);
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);
fclose(fp);}
❖ fgets()
➢ fgets() stands for file get string.
➢ The fgets() function is used to get a string from a stream.
➢ The syntax of fgets() can be given as:
char *fgets(char *str, int size, FILE *stream);
➢ The fgets() function reads at most one less than the number of characters
specified by size (gets size - 1 characters) from the given stream and stores them
in the string str. When all the characters are read without any error, a '\0'
character is appended to end the string.
FILE *fp;
char str[80];
fp = fopen("Student.DAT", "r");
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-17
Principles of Programming using C BPOPS103/203
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
while (fgets(str, 80, fp) != NULL)
printf("\n %s", str);
printf("\n\n File Read. Now closing the file");
fclose(fp);
❖ fgetc()
➢ The fgetc() function returns the next character from stream, or EOF if the end of
file is reached or if there is an error.
➢ The syntax of fgetc() can be given as
int fgetc( FILE *stream );
➢ fgetc returns the character read as an int or return EOF to indicate an error or end
of file.
➢ fgetc() reads a single character from the current position of a file (file associated
with stream). After reading the character, the function increments the associated
file pointer (if defined) to point to the next character.
FILE *fp;
char str[80];
int i, ch;
fp = fopen("Program.C", "r");
if(fp==NULL)
{ printf("\n The file could not be opened");
exit(1);
}
// Read 79 characters and store them in str
ch = fgetc(fp);
for( i=0; (i < 79 ) && ( feof( fp ) == 0 ); i++ )
{ str[i] = (char)ch;
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-18
Principles of Programming using C BPOPS103/203
ch = fgetc( stream );
}
str[i] = '\0';
printf( "\n %s", str);
fclose(fp);
❖ fread()
FILE *fp;
char str[11];
fp = fopen("Letter.TXT", "r+");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
fread(str, 1, 10, fp);
str[10]= '\0';
printf("\n First 9 characters of the file are : %s", str);
fclose(fp);
3. Write data to a file
C provides the following set of functions to read data from a file.
➢ fprintf()
➢ fputs()
➢ fputc()
➢ fwrite()
fprintf()
❖ The fpritnt() is used to write formatted output to stream. Its syntax can be given as,
int fprintf ( FILE * stream, const char * format, ... );
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-19
Principles of Programming using C BPOPS103/203
❖ The parameter format in the fprintf() is nothing but a C string that contains the text
that has to be written on to the stream.
FILE *fp;
int i;
char name[20];
float salary;
fp = fopen("Details.TXT", "w");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
for(i=0;i<10;i++)
{puts("\n Enter your name : ");
gets(name);
fflush(stdin);
puts("\n Enter your salary : ");
scanf("%f", &salary);
fprintf(fp, " (%d) NAME : [%-10.10s] \t SALARY " %5.2f", i, name, salary);
}
fclose(fp);
fputc()
❖ The fputc() is used to write a character to the stream.
int fputc(int c, FILE *stream);
❖ The fputc() function will write the byte specified by c (converted to an unsigned
char) to the output stream pointed to by stream.
#include<stdio.h>
main()
{
FILE *fp;
char feedback[100];
int i;
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-20
Principles of Programming using C BPOPS103/203
fp = fopen("Comments.TXT", "w");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
printf("\n Kindly give the feedback on this book : ");
gets(feedback);
for(i=0i<feedback[i];i++)
fputc(feedback[i], fp);
fclose(fp);
}
❖ fwrite()
➢ The fwrite() is used to write data to a file. The syntax of fwrite can be given
as,
int fwrite(const void *str, size_t size, size_t count, FILE *stream);
➢ The fwrite() function will write, from the array pointed to by str, up to count
objects of size specified by size, to the stream pointed to by stream.
➢ The file-position indicator for the stream (if defined) will be advanced by the
number of bytes successfully written. In case of error, the error indicator for
the stream will be set.
main(void)
{
FILE *fp;
size_t count;
char str[] = "GOOD MORNING ";
fp = fopen("Welcome.txt", "wb");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
count = fwrite(str, 1, strlen(str), fp);
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-21
Principles of Programming using C BPOPS103/203
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-22
Principles of Programming using C BPOPS103/203
1.Discuss the general syntax of structure variable declaration of structure to store book
information.
2. Write a program to write employees details in a file called employee.txt. Then read the record
of the nth employee and calculate his salary.
3. Discuss the general syntax of structure variable declaration of structure to store book
information.
4. Write a program to write employees details in a file called employee.txt. Then read the record
of the nth employee and calculate his salary.
5. Implement structure to read, write and compute average marks of the students. List the students
scoring above and below the average marks for a class of n students
6. Discuss the different modes of operation on files with suitable example
7. Write a short note on functions used to
Read data from a file
Write data to a file
8. How to detect END-OF-FILE ?
9. Differentiate between gets() and fgets().
******************************************************
Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-23
Program Outcomes (Pos)
At the end of the B.E program, students are expected to have developed the
following outcomes:
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one ‘s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
Vision of Computer Science and Engineering
To produce highly competent and innovative Computer Science professionals through
excellence in teaching, training and research