0% found this document useful (0 votes)
42 views158 pages

Principles of Programming Using C BPOPS103-203

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

Principles of Programming Using C BPOPS103-203

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

Afliated to Visvesvaraya Technological University, Belagavi | Approved by AICTE - New Delhi

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

Principles of Programming Using C


BPOPS103/203

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

As new subjects and topics are added in the current


syllabus, the student nds it difcult to cope up to study the
entire syllabus. Also, students don’t nd time to invest in
innovation or upskilling themselves to the requirements of
the industry.

Keeping this in mind our dedicated faculty members have


worked to bring out this guidebook which will help the
students to clear the courses easily. I extend my heartfelt
appreciation to the author for her tireless efforts in creating
a resource that not only educates but also inspires.

I encourage every student to approach this book as a


guide with curiosity and eagerness to learn and perform
better in examinations. May this guide serve as a
cornerstone in your academic journey, igniting a passion
towards communication that will illuminate your path
towards a brighter future.

Best wishes for an enriching and fullling learning


experience!

Dr. T. VENKAT VARDHAN


President, GVET
PREFACE

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.

This book covers the concepts of Principles of Programming using C such as


Structure of C language, Variables, Input and Output statements, Branching and
Looping statements, Functions, Arrays, Strings, Structures and Pointers. These
fundamentals are essential for a successful career, providing a solid foundation for
programming and computer applications.

To aid students’ preparation, important questions and answers based on


previous years' university papers are included. The language is simple and easy
to understand. Short answers to the points have been written to remember and
recall with ease.

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 denitely help the students to face the
exam with condence 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 benet of the students.

Dr. Jenitha A, IQAC Head


Prof. Ruckmani Divakaran, Dean Academics
Dr. H G Shenoy, Vice Principal
Dr. Syed Ariff, Principal
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

DEPARTMENT OF COMPUTER SCEINCE AND ENGINEERING


Table of Contents
MODULE: 1
Introduction to C

Topics Page No.

1.1 Introduction to Computer 1-1

1.1.1 Characteristics of Computer 1-1

1.1.2 Stored Program Concept 1-2

1.1.3 History of Computers 1-3

1.1.4 Classification of Computers 1-6

1.1.5 Application of Computers 1-10

1.1.6 Basic Organization of Computers 1-12

1.2 Input Output Devices 1-25

1.3 Designing Efficient programs 1-33

1.4 Introduction to C 1-43

1.4.1 Structure of a C Program 1-44

1.4.2 Basic Data types in C 1-51

1.4.3 Variables 1-52

1.4.4 Constants 1-53

1.4.5 Input/Output statements in C steams 1-54

1.5 Question Bank 1-59


Principles of Programming Using C BPOPS103/203

MODULE: 1
INTRODUCTION TO C

Q1) What is Computer?

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

In Simple terms computer can be defined as,

“An electronic device which accepts the data, performs the required mathematical and
logical operations at the high speed and outputs the result”.

Tasks of the Computer:

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

➢ Output: The result displayed by the computer is called as output.

➢ Storage: A place to save results inside or outside the computer is known as storage.
1.1.1 CHARACTERISTICS OF COMPUTER

Q2) Write a short notes of characteristics of computer. Model QP-1, Marks 6

The important characteristics of a computer are:

➢ 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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-1


Principles of Programming Using C BPOPS103/203

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.

➢ Diligence: Unlike humans, computers never get tired of repetitive tasks. It


continuously works for hours without creating errors and with same accuracy.

➢ Versatile: Computers are versatile devices as they can perform multiple tasks of
different nature at the same time

➢ Memory: Computers have internal or primary memory and External or secondary


memory. Primary or internal memory is very expensive and limited in size. The
secondary storage is cheaper and bigger in size.

➢ No IQ: Computers do not have any decision making abilities of their own. They need
guidance to perform various tasks.

Q3) What is difference between data and information?

➢ Data is a raw fact.


➢ Information is a processed data.
For example, the date of birth is the data and calculating the age using date of birth is
information.

1.1.2 STORED PROGRAM CONCEPT

➢ 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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-2


Principles of Programming Using C BPOPS103/203

Figure1.2 Von Neumann Architecture with separate memory for instructions and data

➢ Due to the disadvantage of previous architecture, Harvard University proposed


a stored program concept in which there was a separate memory to store data
and instructions as shown in Fig 2.
➢ Instructions are selected serially from the instruction memory and executed in
the processor.
➢ When an instruction needs data, it is selected from the data memory and hence
the execution becomes faster.

1.1.3 HISTORY OF COMPUTERS

First Generation (1942-1955): Vacuum Tubes

➢ These computers were manufactured using thousands of vacuum tubes.


➢ The Electromagnetic relay was used as primary memory and punch cards were
used to store data and instructions.
➢ Programming was done in machine or assembly level language.
Advantage:

➢ Fastest calculating devices of their time.

Disadvantage:

➢ Generated lot of heat, Consumed lot of electricity, Bulky in size, required


constant maintenance, Limited commercial use and very expensive.

Second Generation (1955-1964): Transistors


➢ These computers were manufactured using transistors which were reliable, cheaper,
smaller and cooler than vacuum tubes.
➢ Magnetic core memory was used as primary memory and magnetic tapes and disks were
used to store data and instructions.
➢ Programming was done in high level programming language.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-3


Principles of Programming Using C BPOPS103/203

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:

➢ Transistors were assembled manually which made commercial production difficult


and expensive

Third Generation (1964-1975): Integrated circuits

➢ These computers were manufactured using transistors integrated Chips(IC’S)


which consists of several components such as transistors, capacitors and resistors
on single chip to avoid wired connections between components.

➢ Large Magnetic core memory was used as primary memory and magnetic
tapes and disks were used to store data and instructions.

➢ Programming was done in high level programming language.

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.

Fourth Generation (1975-1989): Microprocessors

➢ These computers were manufactured using transistors integrated


chips(IC’s) with LSI’s and later with VLSI.

➢ Semiconductors memory was used as primary memory and


magnetic tapes and floppy disks were used as portable storage
devices.

➢ Programming was done in high level programming language such as C and


C++.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-4


Principles of Programming Using C BPOPS103/203

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.

Fifth Generation (1989-Present): Artificial Intelligence


➢ These computers were manufactured using transistors integrated
chips(IC’s) with ULSI’s(Ultra Large scale Integration) technology.
➢ Semiconductors memory was used as primary memory and
magnetic tapes and floppy disks were used as portable storage
devices.
➢ Programming is done in high level programming language such as Java,
Python, C#.
Advantage:

➢ Smaller, cheaper, faster, powerful and more reliable, Consumer


less power, generated less heat, high-end features available.

Table .1.1: Comparison of Generation of Computers

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-5


Principles of Programming Using C BPOPS103/203

1.1.4 CLASSIFICATION OF COMPUTERS

Figure: 1.1.4 Below shows the classification of Computers

Fiureg 1.1.4 Classification of computers


1) Supercomputers:

➢ It is the fastest, most powerful, and most expensive computer.

➢ It was first developed in 1980s to process large amounts of data and


solve complex scientific problems.

➢ They use parallel processing technology and can perform trillion


calculations in a second.

➢ A single supercomputer can support thousands of users at same time.

➢ They are used for weather forecasting, nuclear energy research,


aircraft design, automotive design, online banking etc.

➢ Examples of supercomputers are: CRAY-1, CRAY-2, ETA A-10.

2) Mainframe Computers:

➢ They are large scale computers but smaller than supercomputers.

➢ These are very expensive and need a very large clean room with air
conditioning, making them very costly to deploy.

➢ Mainframes can also support multiple processors.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-6


Principles of Programming Using C BPOPS103/203

Dumb terminals:

➢ It consists of only monitor and keyboard and uses mainframe’s system


CPU and storage device.

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.

➢ They are also used in organizations such as banks, airline companies,


universities where large number of people access the data frequently.

➢ Examples of Mainframe computers are: IBM S/390, Control Data CYBER


176, and Amdahl 580.

3) Minicomputers:

➢ They are smaller, cheaper, and slower than mainframes.

➢ They are also called Midrange computers.

➢ The capabilities of these fall between mainframe and personal computers.

➢ They are widely used in business, education, hospitals, government


organizations, etc.
➢ Some minicomputers are designed in such a way that it can be either
used by single user or multiple users.

➢ Single-user minicomputers are used for performing complex design tasks.

➢ The first Minicomputer was introduced by Digital Equipment


Corporation in mid- 1960’s.

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-7


Principles of Programming Using C BPOPS103/203

Laptops:

➢ They are small microcomputers that easily fit inside a briefcase.

➢ The memory and storage capacity of a laptop is almost equivalent to a


desktop computer.
➢ They also have hard disk drives.

➢ For input, laptops have built-in keyboard and touch pad.

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:

➢ High Resolution, Accelerated graphics cards- they are used in video


editing and animations, Powerful machines and used for architectural
or engineering design.

Disadvantages:
➢ Workstations are costly, Not Portable.

Network computers:
➢ Network computers have less processing power, memory, and storage
than a desktop computer.

➢ These are specially designed to be used as terminals in a networked


environment.

➢ For example, some network computers are specifically designed to


access data stored on a network (including the Internet and intranet).

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-8


Principles of Programming Using C BPOPS103/203

➢ 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:

➢ A smart phone is an electronic hand held device that has the


functionality of a mobile phone and PDA.
➢ This is achieved by adding mobile phone features to an existing PDA.
Advantages:

➢ Various software applications such as E-Mail, SMS, voice recognition, camera,


etc..
➢ It can be connected to internet for web browsing.
➢ Can be used to listen to music or radio.
➢ PC Compatibility.

Disadvantages:

➢ Generally larger than standard handsets, More expensive, High replacement


cost.

Tablet Computers:

➢ A tablet PC is a personal computer and looks like a standard slate.

➢ The display system can be rotated by 180 degree.

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-9


Principles of Programming Using C BPOPS103/203

Advantages:

➢ Notes can be written using our handwriting style.

➢ Paper work can be eliminated.

➢ They are very slim and light weight compared to laptops and hence they are portable.

Disadvantages:

➢ They are costlier and delicate. • High replacement cost

1.1.5 APPLICATION OF COMPUTERS

Q4) List out the applications of computers, 10m, Model QP2


1. Word Processing: Word Processing software enables user to read and
write documents.

2. Internet: The internet is a network that connects the computers all over the
world.

3. Digital video or Audio Composition: Computers make Audio and Video


editing very simple.

4. Desktop publishing: This software enables to create page layouts for entire
books.

5. E-Business: It is a process of conducting business via Internet.

6) Bioinformatics: Bioinformatics is an interdisciplinary field of science that


develops methods and software tools for understanding biological data,
especially when the data sets are large and complex.

7) Health care: In health care, it is used to store health records, surgical


procedures for better diagnosis and treatment.

8) Geographic Information System and Remote Sensing: It is a computer


based tool for mapping and analyzing Earth’s features.

9) Meteorology: It is the study of atmosphere.

10) Multimedia and Animation: which combines still images, moving images,
text, sound.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-10


Principles of Programming Using C BPOPS103/203

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.

15) Simulation: Supercomputers that can process enormous amount of data


are widely used in simulation tests.

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.

17) Education: Teachers use computers to develop instructional material.

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-11


Principles of Programming Using C BPOPS103/203

1.1.6 Basic Organization of Computers

Q5) Explain the organization of Computers, 6m, Model QP

Figure:1.6 Block diagram of a Computer

What does a computer do?

A computer is an electronic device which performs 5 major operations.


➢ Accepting data or instructions.

➢ Storing data

➢ Processing data

➢ Displaying results

➢ Controlling and coordinating all operations inside a computer.

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.

➢ Note that computers understand binary language, which consists of


only two symbols (0 and 1), so it is the responsibility of the input
devices to convert the input data into binary codes.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-12


Principles of Programming Using C BPOPS103/203

Storage:

➢ Storage is the process of saving data and instructions permanently in the


computer so that they can be used for processing.

➢ A computer has 2 types of storage area:

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.

➢ Primary storage space is very expensive and therefore limited in capacity.

➢ Another drawback of main memory is that it is volatile in nature; that is, as


soon as the computer is switched off, the information stored gets erased.

➢ Hence, it cannot be used as a permanent storage of useful data and programs


for future use. An example of primary storage is random access memory (RAM).

2)Secondary storage

➢ Secondary storage is also known as auxiliary memory, this memory is just


the opposite of primary memory. It overcomes all the drawbacks of the primary storage
area.

➢ It is cheaper, non-volatile, and used to permanently store data and programs of


those jobs that are not being currently executed by the CPU.

➢ Secondary memory supplements the limited storage capacity of the primary


memory. An example is the magnetic disk used to store data, such as C and D
drives, for future use.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-13


Principles of Programming Using C BPOPS103/203

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.

➢ The intermediate results of processing may be stored in the main memory, as


they might be required again.

➢ When the processing completes, the final result is then transferred to the
main memory.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-14


Principles of Programming Using C BPOPS103/203

➢ Hence, the data may move from main memory to the ALU multiple times before
the processing is over.

Inside the Computers

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.

➢ More memory means more applications can be executed at the same


time without degrading the system's performance.

Hard Disk Drive(HDD)

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

➢ Many computers come with an in-built video chip.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-15


Principles of Programming Using C BPOPS103/203

➢ 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:

➢ A modem (modulator-demodulator) is a device that enables the computer to


use a telephone line to communicate and connect to the Internet.

➢ A modem (modulator-demodulator) is a device that enables the computer to


use a telephone line to communicate and connect to the Internet.

Network card:

➢ A network card is used to connect the computer either to other computers or to


the Internet (in case you are using a fast Internet connection such as cable or
DSL).

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-16


Principles of Programming Using C BPOPS103/203

1.2. Input and Output Devices


Input Devices
Q6) List and explain any two input-output devices. Jan/Feb 2023, Marks 4

Keyboard:

➢ A keyboard is the main input devices to the computer.

➢ A keyboard looks like a typewriter.


➢ A numeric keypad is located to the right of the keyboard. Numeric keys have
the same placement as a 10-key calculator, which allow the operator to enter
numbers rapidly.
➢ Keyboard also contains other types of keys such as typewriter keys, function
keys, cursor control keys, page-up and page-down keys, home and end keys,
Caps lock , shift etc.
Advantages:

➢ The Keyboard is easy to use and inexpensive.

Disadvantages:

➢ The keyboard cannot be used to draw figures.

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

➢ It is the key input device used in a graphical user interface (GUI).

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-17


Principles of Programming Using C BPOPS103/203

➢ Mouse is a hand held device that allows a user to control the


computer without typing instructions from the keyboard.

• Point: Placing the pointer over the word or the object on the
screen by moving the mouse on the desk is termed as pointing.

• Drag: Dragging means pointing to a desired location while


pressing the left button.

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-18


Principles of Programming Using C BPOPS103/203

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:

➢ A cordless or wireless mouse is not connected to the computer. The movement


of the mouse is detected using radio waves or infrared light waves.
Advantages:
➢ Low Priced
➢ Easy to use and can be used to quickly place the cursor.
Disadvantages:
➢ Needs extra desk space to be placed and moved easily.
➢ The ball in the mechanical mouse must be cleaned to remove dust from it
Trackball:
➢ A trackball is a pointing device that is used to control the position of the cursor on
the screen.
➢ It is usually used in notebook computers, where it is placed on the keyboard
Advantages:
➢ Provides better resolutions.
➢ Occupies less space.
➢ Easier to use as compared to mouse as its use involves less hand and
arm movements
Disadvantages:
➢ The trackball chamber is often covered with dust and must be cleaned
regularly.

TouchPad

➢ A touchpad (or trackpad) is a small, flat, rectangular stationary pointing device


with a sensitive surface of 1.5-2 square inches.
➢ The user has to slide his or her fingertips across the surface of the pad to
point to a specific object on the screen.
➢ The surface translates the motion and position of the user's fingers to a
relative position on the screen.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-19


Principles of Programming Using C BPOPS103/203

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.

➢ These displays can be connected to computers, laptops, PDAs, cell phones


etc.

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-20


Principles of Programming Using C BPOPS103/203

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

➢ Scanners come in hand-held, feed-in, and flatbed types.


➢ In the flat bed scanner, the object to be scanned is placed on a glass
pane and a sensor and light moves along the pane, reflecting off the
image placed on the glass.
➢ A hand image scanner has to be manually moved across an object or image to be
scanned.
➢ The scanner produces light from green LEDs which highlight and scan the image
onto a computer for further processing.
➢ Film scanners are usually used in photography and slides.
➢ The slide or negative film is first inserted in strips of six or less frames into the film
scanner, and then moved across a lens and censor to capture the image.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-21


Principles of Programming Using C BPOPS103/203

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):

➢ OCR is the process of converting printed materials into text or word


processing files that can be easily edited and stored.
➢ The steps involved in OCR include:
1. Scanning of the text character-by-character
2. Analyzing the scanned-in image to translate the character image into
character codes (ex ASCII)

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-22


Principles of Programming Using C BPOPS103/203

Optical Mark Recognition


➢ OMR is the process of electronically extracting data from marked fields, such
as checkboxes and fill-infields, on printed forms.
➢ The optical mark reader is fed with an OMR sheet to detect the presence of a
mark by measuring reflected light levels.
➢ The OM reader interprets this pattern marks and spaces and stores the
interpreted data in computer for storage, analysis and reporting.
➢ The error rate for OMR technology is less than 1%.
➢ It is used for applications in which large numbers of hand-filled forms have to
be quickly processed with great accuracy, such as surveys, reply cards,
questionnaires, ballots or sheets for multiple choice questions.

Advantages:
➢ Optical mark readers works with a very fast speed. They can read up to 9,000
forms per hour

➢ They are accurate machines with error rates of just 1%.

Disadvantages:

➢ Difficult to gather large amount of information.


➢ Some data may be missing in the scanned documents.
➢ It is a sensitive device that rejects the OMR sheet if it is folded, torn or crushed.

Magnetic Ink Character Reader (MICR)


➢ MICR is used to verify the legitimacy or originality of paper documents,
especially checks.
➢ MICR consists of magnetic ink printed characters which can be recognized by
high speed magnetic recognition devices .
➢ The printed characters provides important information (like check number, bank
routing number, checking account number and in some cases the amount of the
check) for processing to the receiving party.
➢ MICR is widely used to enhance security, speed up the
➢ sorting of documents and minimize the exposure to check fraud.

Audiovisual Input devices:


➢ Audio devices.
➢ Video Input devices

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-23


Principles of Programming Using C BPOPS103/203

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”

Video Input Devices


➢ Video input devices are used to capture video from the outside world into the computer.
➢ Digital camera is used to capture images or videos. It digitizes the image or
video and stores them on a memory card.
➢ The data can then be transferred to the computer using a cable which
connects computer to the digital camera.
➢ Web cameras also capture videos which can be transferred via internet in real
time.

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-24


Principles of Programming Using C BPOPS103/203

1.2 INPUT OUTPUT DEVICES

➢ Any device that outputs/gives information from a computer is called an


output device.
➢ Output devices are electromechanical devices which accept digital data
from the computer and convert them into human understandable language.

SOFT COPY DEVICES

➢ Soft copy output devices are those output devices which


produce an electronic version of an output.
➢ For example, a file which is stored on hard disk, CD, pen drive, etc
is displayed on the computer screen (monitor).
Features of a soft copy output include:

➢ The output can be viewed only when the computer is on.


➢ The user can easily edit the soft copy output
➢ Soft copy cannot be used by people who do not have a computer
➢ Searching data in a soft copy is easy and fast.
➢ Electronic distribution of a soft copy is cheaper. It can be done easily and
quickly
Monitors:
➢ The monitor is a soft copy output device used to display video and graphics
information generated by the computer through the video card.
➢ Monitors have 3 variants: Cathode Ray tube(CRT), Liquid Crystal
Display(LCD), and Plasma.

Cathode Ray Tube Monitors


➢ CRT monitors work by firing charged electrons at a phosphorus film.
➢ When electron hit the phosphor coated screen, it glows thereby enabling the
user to see the output.
➢ In a cathode ray tube, the "cathode" is a heated filament which is placed in a
vacuum created inside a glass "tube."
➢ The "ray" is a stream of electrons which comes out from a heated cathode into
the vacuum.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-25


Principles of Programming Using C BPOPS103/203

➢ 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:

➢ It provides images of good quality.

➢ These are cheapest when compared to LCD and plasma monitors.

➢ The images are clear even when we try to view in different angle.

Disadvantages:

➢ They occupy a large space on the desk.

➢ They are bigger in size and weight and therefore difficult to move from
one place to another when compared with other types of monitor.

➢ Power consumption is higher than the other monitors.

Liquid Crystal Display Monitors

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

➢ Simultaneously, the electrical currents cause the liquid crystal molecules


to align to allow varying levels of light to pass through to the second
substrate and create the colors and images are seen on the screen.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-26


Principles of Programming Using C BPOPS103/203

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

➢ There is little or no flicker of images.

➢ They are more reliable than CRTs and can be made in almost any size
or shape.

Disadvantages:

➢ They are more expensive than CRTs.

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

➢ The display electrode is covered by a magnesium oxide protective layer


and is arranged in horizontal rows along the screen while the address
electrodes are arranged in vertical columns thereby forming grid like
structure.

➢ 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

➢ An electric current begins to flow through the gas in the cell.

➢ The current creates a rapid flow of charged particles thereby stimulating


the gas atoms to release ultraviolet photons.

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-27


Principles of Programming Using C BPOPS103/203

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.

Disadvantages: Expensive, high power consumption.

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-28


Principles of Programming Using C BPOPS103/203

Hard Copy Output Devices

➢ Hard copy output devices produce a physical form of output. For


example, the content of a file printed on a paper is a form of hard copy
output.

Printers:

➢ Printer is a device that outputs text and graphics information obtained


from the computer and prints it on to a paper. Printers are available in the
market in a variety of size, speed, sophistication, and cost. The qualities
of printer which are of interest to users include:

• Color: Colored printouts are needed for presentations or maps and other pages
where color is part of the information. They are more expensive.

• Memory: Most printers have a small amount of memory that can be


expanded by the user. Having more memory makes enhances the speed
of printing

• Resolution: The resolution of a printer means the sharpness of text and


images on paper. It is usually expressed in dots per inch (dpi). Even the
least inexpensive printer provides sufficient resolution for most
purposes at 600 dpi.

• 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:

➢ They create characters by striking an inked ribbon against the paper.

➢ 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:

➢ Impact printers are slow.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-29


Principles of Programming Using C BPOPS103/203

➢ They offer poor printing quality and can be extremely noisy.

➢ They can print only using the standard format.

DOT MATRIX PRINTER

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

➢ It can only print lower-resolution graphics, with limited quality

➢ It is very slow and has poor print quality

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

Daisy Wheel Printer

➢ Daisy wheel printers use an impact printing technology to generate high-


quality output comparable to typewriters but three times faster.

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-30


Principles of Programming Using C BPOPS103/203

➢ 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 spoke containing the required character is then hit by a hammer


thereby striking the ribbon to leave an impression on the paper placed behind
the ribbon. Movement of all these parts is controlled by microprocessor
in the printer.

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

➢ They are widely used in datacenters and in industrial environments. Band


printer is a commonly used variant of line printers.

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.

Non Impact Printer:

➢ Non-impact printers are much quieter than impact printers as their


printing heads do not strike the paper.

➢ They offer better print quality, faster printing and the ability to create
prints that contain sophisticated graphics.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-31


Principles of Programming Using C BPOPS103/203

➢ Non-impact printers use either solid or liquid cartridge-based ink which is


either sprayed, dripped or electro statically drawn onto the page. The main
types of non-impact printer are: inkjet, printer, laser printer and thermal
printer.

Advantages:

➢ These produce prints of good quality and hence render sophisticated


graphics.

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

➢ The dots are extremely small (usually between 50 and 60 microns in


diameter) and are positioned very precisely, with resolutions of up to
1440x720 dots per inch (dpi).

➢ 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

➢ It is a non-impact printer that works at a very high speed and produces


high quality text and graphics. It uses the technology.

➢ When a document is sent to the printer, the following steps takes place:

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-32


Principles of Programming Using C BPOPS103/203

1. A laser beam "draws" the document on a drum (which is coated with a


photo- conductive material) using photocopier electrical charges.

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.

4. After the document is printed, the electrical charge is removed


from the drum and the excess toner is collected.
➢ While color laser printers are also available in the market but users prefer
only monochrome printers because a color laser printer is up to 10 times
more expensive than a monochrome laser

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.

1.3 DESIGNING EFFICIENT PROGRAMS

PROGRAMMING PARADIGMS

➢ A programming paradigm is a fundamental style of programming that defines


how the structure and basic elements of a computer program will be built.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-33


Principles of Programming Using C BPOPS103/203

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

➢ These paradigms, in sequence of their application, can be classified as follows:

1. Monolithic programming — emphasizes on finding a solution

2. Procedural programming—lays stress on algorithms

3. Structured programming—focuses on modules

4. Object-oriented programming—emphasizes on classes and objects.

Monolithic programming:

➢ Monolithic programs have just one program module as such programming


languages do not support the concept of subroutines.

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

➢ Programs written using monolithic programming languages consist of global


data and sequential code.
➢ The global data can be accessed and modified from any part of the program.
Examples are Assembly Language and BASIC.

Procedural programming:

➢ In procedural languages, a program is divided into subroutines that can access


global data.

➢ To avoid repetition of code, each subroutine performs a well-defined task.

➢ A subroutine that needs the service provided by another subroutine can call that
subroutine.

➢ Therefore, with ‘jump’,‘ goto’, and ‘call’ instructions, the sequence of


execution of instructions can be altered.

➢ FORTRAN and COBOL are two popular procedural programming languages.

Advantages
➢ The only goal is to write correct programs

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-34


Principles of Programming Using C BPOPS103/203

Disadvantages

➢ No concept of reusability
➢ Requires more time and effort to write programs

➢ Global data shared and therefore may get altered (mistakenly)


Structured programming:

➢ Structured programming employs a top-down approach in which the overall


program structure is broken down into separate modules.

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

➢ Structured programming is based on modularization which groups related


statements together into modules.
Advantages

➢ 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)

➢ The object-oriented paradigm is


task-based and data-based. In
this paradigm, all the relevant
data and tasks are grouped
together in entities known as
objects. It treats data as a
critical element in the program
development and restricts its
flow freely around the system.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-35


Principles of Programming Using C BPOPS103/203

➢ The striking features of OOP


include the following :

1. Programs are data centered.

2. Programs are divided in terms of objects and not procedures.

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.

6. Follow a bottom-up approach for problem.

1.3.2 DESIGN AND IMPLEMENTATION OF EFFICIENT PROGRAMS

Q7) Explain the SDLC life cycle for the efficient design of a program with a neat diagram.
Model QP-3, Marks 8

➢ The design and development of


correct, efficient and maintainable
programs depend on the approach
adopted by the programmer to
perform various activities that
need to be performed during the
development process.
➢ The entire programs and software
development process is divided
into a number of phases.
➢ This phase is the Software
Development Life cycle.
1. Requirement analysis:

➢ In this phase, user expectations are gathered to know why the


software/program has to be built.
➢ Then all the gathered requirements are analyzed to frame an objective.
➢ The last activity in this phase is to document all the requirements to avoid
any further doubts.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-36


Principles of Programming Using C BPOPS103/203

➢ The functionality, capability, performance, and availability of hardware


and software components are analyzed in this phase.

2. Design:

➢ In this phase, a plan of actions is made before the actual development


process could start.
➢ This plan will be followed throughout the development process.
➢ The core structure of the software/program is broken down into modules.
➢ The solution of the program is then specified for each module in the
form of algorithms, flowcharts, or pseudo codes.

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.

5. Software Deployment, Training and Support:

➢ Software Training and Support is a crucial phase which makes the end users
familiar with how to use the software.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-37


Principles of Programming Using C BPOPS103/203

➢ 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

➢ An algorithm provides a blueprint to writing a program to solve a particular


problem.

➢ It is considered to be an effective procedure for solving a problem in a finite


number of steps.

➢ A well-defined algorithm always provides an answer, and is guaranteed


to terminate.

➢ Algorithms are mainly used to achieve software re-use.

➢ A good algorithm must have the following characteristics


▪ Be precise
▪ Be unambiguous
▪ Not even a single instruction must be repeated infinitely
▪ After the algorithm gets terminated, the desired result must be obtained

Control Structures used in Algorithms


Sequence: Sequence means that each step of the algorithm is executed in the specified
order.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-38


Principles of Programming Using C BPOPS103/203

Step 1: Input the first number as A


Step 2: Input the Second number as B
Step 3: Set SUM= A+B
Step 4: PRINT SUM
Step 5: END

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.

Step 1: [Initialize] Set I=1, N=10


Step 2: Repeat steps 3 and 4 while I <=N
Step 3: Print I
Step 4: SET I = I + 1
[END OF LOOP]
Step 5: END

FLOWCHART

➢ Flowchart is a graphical or symbolic representation of a process.


➢ It is basically used to design and document virtually complex processes to
help the viewers to visualize the logic of the process, so that they can gain a
better understanding of the process and find flaws, bottlenecks, and other
less obvious features within it.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-39


Principles of Programming Using C BPOPS103/203

➢ When designing a flowchart, each step in the process is depicted by a different


symbol and is associated with a short description. The symbols in the
flowchart are linked together with arrows to show the flow of logic in the process.

Pseudocode:

➢ Pseudocode is a compact and informal high-level description of an algorithm that uses


the structural conventions of a programming Language.

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

➢ Pseudocodes are an outline of a program that can be easily converted into


programming statements.

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-40


Principles of Programming Using C BPOPS103/203

TYPES OF ERRORS

Q8) Discuss different types of error occur in program. Model QP-2, Marks 6

➢ While writing programs, very often we get errors in our program.


➢ These errors if not removed will either give erroneous output or will not let the
compiler to compile the program. Fig 8 below shows different types of error that can
occur in our program.

1. Run-time errors:

➢ Run-time Errors occur when the program is being run executed.

➢ Such errors occur when the program performs some illegal operation like

• Dividing a number by zero

• Opening a file that already

• Lack of free memory space

• Finding square or logarithm of negative numbers

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

➢ This ability to continue operation of a program despite of run-time errors is


called robustness.

2. Compile time errors:

➢ Compile-time Errors occur at the time of compilation of the program.


➢ Such errors can be further classified as follows:

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-41


Principles of Programming Using C BPOPS103/203

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

➢ Testing is an activity that is performed to verify correct behavior of a


program.

➢ It is specifically carried out with an intent to find errors.

➢ Unit testing is applied only on a single unit or module to ensure whether it


exhibits the expected behavior.
➢ Integration Tests are a logical extension of unit tests. In this test, two units
that have already been tested are combined into a component and the interface
between them is tested. This process is repeated until all the modules are tested
together. The main focus of integration testing is to identify errors that occur
when the units are combined.

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-42


Principles of Programming Using C BPOPS103/203

Debugging Approaches

➢ Debugging is an activity that includes execution testing and code


correction.
➢ It is done to locate errors in the program code.

➢ Once located, errors are then isolated and fixed to produce an error-free
code.

➢ Different approaches applied for debugging a code includes:

Brute-Force Method:

➢ In this technique, a printout of CPU registers and relevant memory locations


is taken, studied, and documented.

➢ It is the least efficient way of debugging a program and is generally done


when all the other methods fail.

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.

➢ However, the main drawback of this approach is that with increase in


number of source code lines, the possible backward paths become too large
to manage.

➢ Because Elimination lists all possible causes of an error is developed. Then


relevant tests are carried out to eliminate each of them.

1.4 INTRODUCTION TO C

➢ C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories.


➢ C was initially developed for writing system software
➢ Today, C has become a popular language and various software programs are
written using this language.
➢ Many other commonly used programming languages such as C++ and
Java are also based on C.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-43


Principles of Programming Using C BPOPS103/203

Characteristics of C

➢ C is a high level programming language which enables the programmer to


concentrate on the problem and not to worry about the machine code

➢ Small size: C has only 32 keywords. This makes it relatively easy to learn

➢ C makes extensive use of function calls

➢ C is well suited for structured programming. In this programming approach,


where it allows the user to think a problem in terms of modules where collection
of all these modules make up a complete program.

➢ Unlike PASCAL it supports loose typing (as a character can be treated as an


integer and vice versa)

➢ Stable Language

➢ Quick Language : Since C Programs make use of operators and data types, they are
fast and efficient.

➢ Facilitates low level (bitwise) Programming.

➢ Supports pointers to refer computer memory, array, structures and functions.

➢ C is a core language as many other programming languages are based on C

➢ C is a portable language which means C program written on one computer


can run on another computer with little or no modification.

➢ C is an extensible language as it enables the user to add his own functions to


the C library.
1.4.1 STRUCTURE OF A C PROGRAM

Q9) With Suitable Example- Explain the basic structure of C Program. Jan/Feb
2023, Marks 8

➢ A C program contains one or more functions

➢ The statements in a C program are written in a logical sequence to perform a


specific task.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-44


Principles of Programming Using C BPOPS103/203

➢ Execution of a C program begins at the main() function

➢ You can choose any name for the functions.

➢ Every program must contain one function that has its name as main().

➢ Figure 1.4.1 shows the structure of a C program. Where, #include refers to


the preprocessor statement used for the standard input/output functions
and it starts with the hash (#) symbol.
➢ main( ):- Refers to the function from where the execution of the program
begins.

Figure 1.4.1: Structure of a C Program


Table 1.4.1: Escape Sequences

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-45


Principles of Programming Using C BPOPS103/203

FILES USED IN C PROGRAM

There are different File types in C as shown in Figure 1.4.2.

Figure 1.4.2: File types in C

Source code file

➢ A source code is a list of commands that has to be assembled or compiled into an


executable computer program.

➢ 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

➢ When working with large projects, it is often desirable to make sub-routines


and store them in a different file known as header file. The advantage of
header files can be realized when

o The programmer wants to use the same subroutines in different


programs.
o The programmer wants to change, or add, subroutines, and have
those changes be reflected in all other programs.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-46


Principles of Programming Using C BPOPS103/203

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

Standard Header file

Examples of standard header files are:

1. string.h: for string handling functions.

2. stdlib.h: for some miscellaneous functions.

3. stdio.h: for standard input and output functions.

4. math.h: for Mathematical Functions.

5. alloc.h: for dynamic memory allocation.

6. conio.h: for clearing the screen

Object Files:

➢ Object files are generated by the compiler as a result of processing the source code
file.

➢ Object files contain compact binary code of the function definitions.

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

Binary Executable File

➢ The binary executable file is generated by the linker.

➢ The linker links the various object files to produce a binary file that can be
directly executed.

➢ On Windows operating system, the executable files have “.exe” extension.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-47


Principles of Programming Using C BPOPS103/203

COMPILING AND EXECUTING C PROGRAMS

Figure 1.4.3: Preprocessing before compilation

➢ 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).

➢ However, even the object file is not a executable file.

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

➢ The output of the linker is an executable or runnable file.

USING COMMENTS

➢ It is a good programming practice to place some comments in the code to help


the reader understand the code clearly.

➢ Comments are just a way of explaining what a program does. It is merely an


internal program documentation.

➢ The compiler ignores the comments when forming the object file. This means
that the comments are non-executable statements.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-48


Principles of Programming Using C BPOPS103/203

➢ C supports two types of commenting.

• // is used to comment a single statement. This is known as a line


comment. A line comment can be placed anywhere on the line and it does
not require to be specifically ended as the end of the line automatically
ends the line.

• /* is used to comment multiple statements. A /* is ended with */ and all


statements that lie within these characters are commented.

C TOKENS

➢ Tokens are the basic building blocks in C language.

➢ It is the smallest individual unit in C program.


➢ A program is constructed using a combination of these tokens. 6 main types of
tokens in C are as shown in Figure 14.4:

Figure 1.4.4: Tokens in C

CHARACTER SET IN C

➢ In C, character means any letter from English alphabet, a digit or a special


symbol used to represent information.
• The character set of C can therefore be given as:
1. English alphabet: Include both lower case (a-z) as well upper case(A-Z)
letters.
2. Digits: Include numerical digits from 0 to 9.
3. Special characters: Include symbols such as ~, @, %, ^, &, *, {, }, <,
>, =, _, +, -,$, /, (, ), \, ;, : , [, ], ‘, “, ?, ., !, |.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-49


Principles of Programming Using C BPOPS103/203

4. White space characters: These characters are used to print a blank


space on the screen like \b, \t, \v, \r, \f, \n.
5. Escape sequences.

KEYWORDS
Table 1.4: Keywords in C Language

➢ C has a set of 32 reserved words often known as keywords.

➢ All keywords are basically a sequence of characters that have a fixed meaning.

➢ By convention all keywords must be written in lowercase (small) letters.

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

Rules for forming identifier name

1. It cannot include any special characters or punctuation marks (like #, $, ^,


?,., etc) except the underscore"_".

2. There cannot be two successive underscores

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-50


Principles of Programming Using C BPOPS103/203

3. Keywords cannot be used as identifiers

4. The names are case sensitive. So, example, “FIRST” is different


from “first” and “First”.

5. It must begin with an alphabet or an underscore.

It can be of any reasonable length. Though it should not contain more


than 31 characters.

Example: roll_number, marks, name,emp_number, basic_pay,


HRA, DA, dept_code, a , sum, temp.

1.4.2 BASIC DATA TYPES IN C

Q10) What are the basic data types available in C? Jan/Feb 2023, Marks 6

Table 1.4.2: Basic data types in C

DATA TYPE SIZE IN BYTES RANGE


Char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
Int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed short int 2 -32768 to 32767
signed int 2 -32768 to 32767
Char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
Int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed short int 2 -32768 to 32767
signed int 2 -32768 to 32767

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-51


Principles of Programming Using C BPOPS103/203

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

➢ A variable is defined as a meaningful name given to the data storage


location in computer memory.

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

• While an integer value is a whole numbers without a fraction part or


decimal point, a floating point number, can have a decimal point in
them.

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

➢ Variable names should always be meaningful and must reflect the


purpose of their usage in the program.
➢ Variable declaration always ends with semicolon. Example,
int emp_num;

float salary,

double balance_amoutn,

unsigned short int acc_no,

Initializing Variables

➢ Assigning a value to a variable is called variable initialization.

➢ The syntax is variable_name=value; Initialization can be done in two ways:-

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-52


Principles of Programming Using C BPOPS103/203

• We can assign an initial value to a variable within the declaration part


itself called static initialization.

Ex:- int a=10;, float x=100.0000;

• We can assign an initial value to a variable during the program


execution called dynamic initialization.

Ex:- printf(Enter a value to a”); scanf(“%d”, &a);

1.4.4 CONSTANTS

➢ Constants are identifiers whose value does not change.

➢ Constants are used to define fixed values like PI or the charge on an


electron so that their value does not get changed in the program even by
mistake.

➢ There are mainly four types of constants in C:

1.Integer constants

2.Floating-point constants

3.Character constants

4.String constants

To declare a constant, precede the normal variable declaration with const


keyword and assign it a value. For example,

• const float pi = 3.14;

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

• #define PI 3.14159

1. The integer constants: represents a


whole number. Ex:- 10, -200, -3456.

2. The floating-point constants:-represents a number that has a

decimal point. Ex:- - 250.01, 67.73234.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-53


Principles of Programming Using C BPOPS103/203

3. The character constants: represents a single character enclosed


within a pair of single quotes.

Ex.:- ‘s’, ‘%’, ‘7’.

4. The string constants:-represents a sequence of characters enclosed


within a pair of double quotes.

Ex:- “Hello”, “z”

Declaring Constants

Rules that need to be applied to a #define statement which defines a constant.

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.

1.4.5 INPUT/OUTPUT STATEMENTS IN C STREAMS

➢ A stream acts in two ways. It is the source of data as well as the destination
of data.

➢ C programs input data and output data from a stream.

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

Figure 1.4.5: Streams in C

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-54


Principles of Programming Using C BPOPS103/203

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

➢ Although, we can do input/output from the keyboard/monitor or from any file


but here we will assume that the source of data is the keyboard and destination
of the data is the monitor.

Formatting Input/output:

Q12) Summarize the formatted input and output statements with suitable examples. Model
QP-3, Marks 6

➢ C supports two formatting functions.


➢ printf is used to convert data stored in the program into a text stream for
output to monitor.
➢ scanf is used to convert the text stream coming from the keyboard to data
values and store them in program variables.
printf():

➢ The printf() function is used to display information required to the


user and also prints the values and variables.
➢ The syntax can be given as printf(“Control string”, variable list);
➢ The prototype of the control string is given by
%[flags][width][.precision][modifier]type

Flags are an optional argument which specifies output justification such as


numerical sign, trailing zeros or octal, decimal, or hexadecimal

Table 1.4.5: Flags in printf() function

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-55


Principles of Programming Using C BPOPS103/203

Width is an optional argument which specifies minimum number of positions in the


output.
Precision is an optional argument which specifies the maximum number of
characters to print.
Table 1.4.6: Length Modifiers in printf()
Length Description
h When the argument is a short int or unsigned short int
l When the argument is long int or unsigned long int for integer specifiers.
L When the argument is a long double (used for floating point specifiers)

Table 1.4.7: type specifiers in printf()


Specifier Qualifying Input
c For single character
d For decimal values
F For floating point values
E,e Floating point numbers in exponential format
G,G Floating point numbers in the shorter of format
o For octal number
s For a sequence of ( string of) characters.
u For Unsigned decimal values
x,X For Hexadecimal value

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

• printf(“\n Result: %d%c%3.1f”,12,'a',2.3);


Output: Result: 12a2.3

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-56


Principles of Programming Using C BPOPS103/203

• printf(“\n Result: %5d %x %#x”,232,232,232);


Output: Result: 232 e8 0xe8
• printf(“\n Result: %5d %X %#X”,232,232,232);
Output: Result: 232 E8 0XE8

• printf("the number is \n%d\n%2d\n%3d",1,1,1);

Output:

The number is
1

scanf():

➢ The scanf() function is used to read formatted data from the keyboard.

➢ The syntax is scanf(“control string”,arg1,arg2,arg3);

➢ The prototype of control string is

%[*][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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-57


Principles of Programming Using C BPOPS103/203

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.

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-58


Principles of Programming Using C BPOPS103/203

1.5 QUESTION BANK

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-59


Principles of Programming Using C BPOPS103/203

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

Sudha S, Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 1-60


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

MODULE 2

OPERATORS IN C, DECISION CONTROL AND LOOPING


STATEMENTS

Sl.No. Chapters Page


No.

2.1 Type casting 2-1

2.2 Unconditional branching statement 2-2

2.3 Conditional branching statement 2-5

2.4 Operators 2-9

2.5 Iterative statements 2-15

2.6 Question Bank 2-20


Principles of Programming using C BPOPS103/203

MODULE 2
OPERATORS IN C, DECISION CONTROL AND LOOPING STATEMENTS

2.1 Type Casting

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:

(a). Implicit Type Casting (Automatic Conversion):


 Definition: The compiler automatically converts one data type to another without explicit
instructions from the programmer. This usually happens when performing operations with
mixed data types.
 Example: When an int is assigned to a float, the int is implicitly converted to float.
Simple code
#include<stdio.h>
void main( )
{
char b= ‘A’; int a;
a=b; printf(“%d”,a);
}

(b). Explicit Type Casting (Type Casting):


 Definition: The programmer explicitly specifies the type conversion. This is done using a
cast operator to convert a variable from one type to another.
 Syntax: (target_type) variable
 Example: Converting a float to an int
float f = 9.7; int i = (int) f; // Explicit type casting, i will be 9
Simple code
#include<stdio.h>
void main()
{

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2 -1


Principles of C Programming BPOPS103/203

int a=4; float b;


b=1/(float)a;
printf(“%f”,b);
}

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

2.2 Unconditional branching statements


3.List and explain unconditional branching statements with examples.
(Feb 23/Jan 24 6/4 marks)
Unconditional statements are the statements which transfer the control or flow of execution
unconditionally to another block of statements. They are also called jump statements.
There are four types of unconditional control transfer statements.
(i) break (ii)continue (iii) goto (iv)return

(i).break Statement
The break statement is used to terminate loops or to exit from a switch.

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-2


Principles of C Programming BPOPS103/203

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);
}
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-3


Principles of C Programming BPOPS103/203

(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:

write a program using return statement


#include <stdio.h>
int main()
{
printf("Hello, World!\n");
return 0;
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-4


Principles of C Programming BPOPS103/203

2.3 Conditional branching statement


4.List the conditional branching statements in C. Explain with example (or) Explain the
different forms of if statements with flowcharts (Feb 23/Jan 24 10/6marks)

Conditional branching statements/decision making statements


These statements allow a program to make decisions and execute different blocks of code
depending on whether certain conditions are true or false.
Various conditional branching statements in C.
1.If statement
2.if-else statement
3.if-else if-else statement/nested if statement
4.Switch statement

(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()
{

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-5


Principles of C Programming BPOPS103/203

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;
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-6


Principles of C Programming BPOPS103/203

(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;
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-7


Principles of C Programming BPOPS103/203

(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

Write a program using switch statement

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-8


Principles of C Programming BPOPS103/203

#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)

The different operators supported in ‘C’ are:


(i) Arithmetic Operators
(ii) Relational Operators
(iii)Equality operators
(iv)Logical Operators
(v)Unary operators Increment and Decrement
(vi)Conditional operators/ Condition Operator
(vii)Bitwise operators
(viii)Assignment Operators
(ix)Comma Operator
(x)Sizeof Operator

1.Arithmetic Operators:

Operator Name Result Syntax Example (b=5, c=2)


+ Addition Sum a=b+c a=7
- Subtraction Difference a=b-c a=3

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-9


Principles of C Programming BPOPS103/203

* Multiplication Product a=b*c a = 10


/ Division Quotient a=b/c a=2
% Modulus Remainder a=b%c a=1

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:

Operator Name Syntax Example (b=5, c=2)


< Lesser than a=b<c a = 0 (False)
> Greater than a=b>c a = 1 (True)
<= Lesser than or Equal to a = b <= c a = 0 (False)
>= Greater than or Equal to a = b >= c a = 1 (True)
== Equal to a=b==c a = 0 (False)
!= Not equal to a = b!= c a = 1 (True)

Example:
Write a program using relational operator

#include <stdio.h>
int main()

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-10


Principles of C Programming BPOPS103/203

{
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

Operator Description Example Result


true if a equals
Equality
== a == b b, false
Operator
otherwise
true if a does
Inequality
!= a != b not equal b,
Operator
false otherwise

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");
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-11


Principles of C Programming BPOPS103/203

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.

Adds the right operand to the left


Addition x +=
+= operand and assigns the result to x becomes x + 5
Assignment 5;
the left operand.

Subtracts the right operand from


Subtraction
-= the left operand and assigns the x -= 3; x becomes x - 3
Assignment
result to the left operand.

Multiplies the left operand by the


Multiplication x *=
*= right operand and assigns the result x becomes x * 4
Assignment 4;
to the left operand.

Divides the left operand by the right


Division
/= operand and assigns the result to x /= 2; x becomes x / 2
Assignment
the left operand.

Computes the modulus of the left


Modulus operand by the right operand and x %=
%= x becomes x % 3
Assignment assigns the result to the left 3;
operand.

Performs a bitwise AND on the left


Bitwise AND operand with the right operand and x &=
&= x becomes x & 7
Assignment assigns the result to the left 7;
operand.

Performs a bitwise XOR on the left


Bitwise XOR x ^=
^= operand with the right operand and x becomes x ^ 5
Assignment 5;
assigns the result to the left operand.

Performs a left shift on the left


Left Shift
<<= operand by the number of bits x <<= 2; x becomes x << 2
Assignment
specified by the right operand and

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-12


Principles of C Programming BPOPS103/203

assigns the result to the left operand.

Performs a right shift on the left


Right Shift operand by the number of bits
>>= x >>= 1; x becomes x >> 1
Assignment specified by the right operand and
assigns the result to the left operand.

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);

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-13


Principles of C Programming BPOPS103/203

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");

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-14


Principles of C Programming BPOPS103/203

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

2.5 Iterative statement


7. what are iterative statements? explain 3 types of iterative statements with their syntax.
(Feb/june23 10/8 marks)
(i).while Loop: It is an entry-controlled loop. In while loop, a condition is evaluated before
processing a body of the loop. If a condition is true then and only then the body of a loop is execute.

Syntax:
initialization;
while(test condition)
{
set of statements to be executed

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-15


Principles of C Programming BPOPS103/203

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{

set of statements to be executed


}while(test condition);

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.

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-16


Principles of C Programming BPOPS103/203

Syntax:
for (initial value; condition; incrementation or decrementation )
{
statements;
}

FLOW CHART

8. write a c program to print the following pattern (June/July 2023


10marks)

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++)
{

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-17


Principles of C Programming BPOPS103/203

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)
{

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-18


Principles of C Programming BPOPS103/203

printf("The largest number is %d\n", a);


}
else
{
printf("The largest number is %d\n", c);
}
}
else
{
if (b >= c)
{
printf("The largest number is %d\n", b);
}
else
{
printf("The largest number is %d\n", c);
}
}
return 0;
}

Output
Enter three numbers: 10 25 15
The largest number is 25

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-19


Principles of C Programming BPOPS103/203

2.6 QUESTION BANK MODULE 2

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)

**********************************

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 2-20


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

Module 3

Functions and Arrays

Sl.No Chapters Page No

3.1 Array- 2D array 3–1

3.2 Binary search 3–4

3.3 Function parameter 3–7

3.4 Function declaration 3 – 10

3.5 Storage classes 3 - 14

3.6 Array declaration and initialisation 3 - 16

3.7 Array application 3 – 19

3.8 User defined functions 3 – 20

3.9 Recursion 3 – 22

3.10 1-D array 3 – 23

3.11 Scope of variables 3 – 26

3.12 Sorting techniques 3 – 27

3.13 Searching techniques 3 – 30

3.14 Operations on arrays 3 – 31

3.15 Question bank 3 - 32


Principles of Programming using C BPOPS103/203

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

Two dimensional array:


An array which has two subscripts are known as two dimensional arrays. The first subscript
represents rows and the second subscript represent column.

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.

Initialization of two dimensional array :


1.Basic Declaration and Initialization
Syntax:
type arrayName[rows][columns] = {
{value1, value2, ..., valueN}, {value1, value2, ..., valueN},
...
};

Example:

int matrix[2][3] = {
{1, 2, 3}, // First row
{4, 5, 6} // Second row
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-1


Principles of Programming using C BPOPS103/203

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)
};

3. Implicit Size Determination


Syntax:

type arrayName[][columns] = { {value1, value2, ..., valueN}, {value1, value2, ..., valueN}, ... };

Example:

int matrix[][3] = { {1, 2, 3}, {4, 5, 6} };

4. Dynamic Initialization Using Loops

Syntax:

type arrayName[rows][columns];

for (int i = 0; i < rows; i++)

for (int j = 0; j < columns; j++)

arrayName[i][j] = expression;// Set value dynamically }

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-2


Principles of Programming using C BPOPS103/203

Example:

int matrix[2][3];

for (int i = 0; i < 2; i++)

for (int j = 0; j < 3; j++)

matrix[i][j] = i * 3 + j + 1; // Example value

Example for declaring 2D array and representation


int[2][3]={{5,3,4} {6,1,2}} ;
this initialization can also be written as int a[2][3] ={5,3,4,6,1,2}

Accessing two dimensional array elements:-An element in a two dimensional array is


accessed by using the subscripts i.e. row index and column index of the array.

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;
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-3


Principles of Programming using C BPOPS103/203

Output:
1 2
2 4

3.2 Binary search


2.Write a c program to search an element using binary search technique(for
numericals)(Feb23 6marks)
#include <stdio.h>
int binarySearch(int arr[],int size,int target)
{
int left = 0;
int right = size - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == target)
{
return mid;
}
else if (arr[mid] < target)
{
left = mid + 1; }
else { right = mid - 1;
}
}
return -1;
}
int main()
{
int arr[] = {2, 3, 4, 10, 40};
int size = sizeof(arr) / sizeof(arr[0]);
int target;
printf("Enter the number to search: ");
scanf("%d", &target);

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-4


Principles of Programming using C BPOPS103/203

int result = binarySearch(arr, size, target);


if (result != -1)
{
print("Element found at index %d.\n", result);
}
else
{
printf("Element not found in the array.\n");
}
return 0;
}

Output
Enter the number to search: 10
Element 10 found at index 3.

3.Write a c program to perform addition of 2 dimensional matrix(considering 3X3 order


matrices A and B) (Feb24 8marks)
include <stdio.h>
int main()
{
int matrixA[SIZE][SIZE], matrixB[SIZE][SIZE], matrixSum[SIZE][SIZE];
printf("Enter elements for matrix A:\n");
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
printf("A[%d][%d]: ", i, j);
scanf("%d", &matrixA[i][j]);
}
}
printf("Enter elements for matrix B:\n");
for (int i = 0; i < SIZE; i++)
{

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-5


Principles of Programming using C BPOPS103/203

for (int j = 0; j < SIZE; j++)


{
printf("B[%d][%d]: ", i, j);
scanf("%d", &matrixB[i][j]);
}
}
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
matrixSum[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
printf("Matrix A:\n");
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
printf("%d ", matrixA[i][j]);
}
printf("\n");
}
printf("Matrix B:\n");
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
printf("%d ", matrixB[i][j]);
}
printf("\n");
}
printf("Matrix Sum:\n");
for (int i = 0; i < SIZE; i++)
{

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-6


Principles of Programming using C BPOPS103/203

for (int j = 0; j < SIZE; j++)


{
printf("%d ", matrixSum[i][j]);
}
printf("\n");
}
return 0;
}

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

3.3 Function parameter


4.Define function. Explain the type of functions based on parameters. (Feb24 8marks)
A function is a collection of statements that perform a specific task. These functions are very useful to
read write and debug complex programs.
There are two methods by which parameters or arguments can be passed to the function

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-7


Principles of Programming using C BPOPS103/203

(i) Call by value or Argument passing by value


(ii) Call by reference or Argument passing by reference

(i)Call by value or Argument passing by value :-When an variable or value is passed to an


function during its invocation such function invocation is called as call by value.

Example:

C program to demonstrate call by value or Argument passing by value


#include<stdio.h>
int sum(int n);
void main()
{

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)
{

int res=0,i; for(i=1;i<=n;i++)


res=res+i;
return res;
}

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

C program to demonstrate call by reference or Argument passing by reference


#include<stdio.h>
void swap(int *a,int *b);
void main()
{

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-8


Principles of Programming using C BPOPS103/203

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

printf("%d ", arr[i]);


printf("\n");
}
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
printArray(arr, n);
bubbleSort(arr, n);
printf("Sorted array:\n");
printArray(arr, n);
return 0;
}

Output
Original array: 64 25 12 22 11
Sorted array: 11 12 22 25 64

3.4 Function declaration


6.Explain the syntax of function declaration and function definition with example(June23
6marks)
(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:
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.

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-10


Principles of Programming using C BPOPS103/203

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.

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-11


Principles of Programming using C BPOPS103/203

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)

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-12


Principles of Programming using C BPOPS103/203

{
int temp = *a;
*a = *b;
*b = temp;
}
Output:
Before swapping: num1 = 5, num2 = 10
After swapping: num1 = 10, num2 = 5

8.Write a C program to find (June23 6marks)

𝑛!
𝑛𝐶𝑟 =
(𝑛 − 𝑟)! 𝑟!
#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;
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-13


Principles of Programming using C BPOPS103/203

Output
Enter n and r: 5 2
C(5, 2) = 10

3.5 Storage classes


9.Describe different types storage classes with examples (Jan24/June23 10/8marks)
storage classes define the scope, lifetime, and visibility of variables. Understanding storage classes
helps in managing the storage of variables and optimizing the performance of the program. The
main storage classes in C are:
1. Automatic Storage Class (auto)
2. Register Storage Class (register)
3. Static Storage Class (static)
4. External Storage Class (extern)

1. Automatic Storage Class (auto)


Description:
• The auto storage class is the default for local variables in functions.
• Variables declared with auto are created when the function is called and destroyed when
the function exits.
• They are stored in the stack.

Example
#include <stdio.h>
void show()
{
auto int value = 5;
printf("value = %d\n", value);
value++;
}
int main()
{
show();
return 0;
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-14


Principles of Programming using C BPOPS103/203

2. Register Storage Class (register)


Description:
• The register storage class suggests that a variable should be stored in a CPU register for
faster access.
• The register keyword is used for frequently accessed variables.
• Registers have a limited number of available slots, so not all register variables can
actually be stored in a register.

Example:
#include <stdio.h>
int main()
{
register int count;
for (count = 1; count <= 3; count++)
{
printf("%d ", count);
}
printf("\n");
return 0;
}

3. Static Storage Class (static)


Description:
• The static storage class makes a variable retain its value between function calls.
• For global variables, static restricts the visibility of the variable to the file in which it is
declared.
• For local variables, static preserves the variable’s value between function calls.

Example:
#include <stdio.h>
void show()
{
static int value = 0;
value++;

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-15


Principles of Programming using C BPOPS103/203

printf("%d ", value);


}
int main()
{
show();
show();
show();
return 0;
}

5. External Storage Class (extern)


Description:
• The extern storage class is used to declare a global variable or function that is defined in
another file or later in the same file.
• It allows multiple files to share a common variable or function.

Example

#include <stdio.h>
int globalVar = 42;
void printGlobalVar()
{
printf("globalVar = %d\n", globalVar);

3.6 Array declaration and initialisation


10.What is an array? Explain how arrays are declared and initialized with example(June23
8M) Array is a collection of elements of same data type.The elements are stored sequentially one
after the other in memory.
Any element can be accessed by using
name of the array
position of element in the array (index)

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:

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-16


Principles of Programming using C BPOPS103/203

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.

Example: int numbers[5] = {1, 2}; // Equivalent to {1, 2, 0, 0, 0}

(iii)Implicit Size:
If you omit the size of the array during initialization, the compiler determines the size based on the
number of initializers.

Example: int numbers[] = {1, 2, 3, 4, 5}; // The size of 'numbers' is 5

(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++)
{

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-17


Principles of Programming using C BPOPS103/203

numbers[i] = i + 1; // Initialize array with values 1 to 5


}

11. Write a C program to transpose a 3x3 matrix (June23 8marks)


#include <stdio.h>
#define SIZE 3
int main()
{
int matrix[SIZE][SIZE];
int transposed[SIZE][SIZE];
printf("Enter elements of the 3x3 matrix:\n");
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
scanf("%d", &matrix[i][j]);
}
}
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
transposed[j][i] = matrix[i][j];
}
}
printf("\nTransposed Matrix:\n");
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
printf("%d ", transposed[i][j]);
}
printf("\n");

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-18


Principles of Programming using C BPOPS103/203

}
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

3.7 Array application


12. List applications of array ( June23 4marks)
Arrays are a fundamental data structure in computer programming with a wide range of
applications.
1. Storing Data Collections
• Data Storage: Arrays are commonly used to store and manage collections of data items
such as numbers, strings, or objects.
• Example: A list of student grades, where each index represents a different student
2. Matrix Operations
• Mathematical Computations: Arrays are used to represent matrices in mathematical
computations, such as in linear algebra and statistics.
• Example: Performing operations like matrix addition, multiplication, and inversion.
3. Sorting and Searching Algorithms
• Algorithms: Arrays are often the underlying data structure for sorting algorithms (e.g.,
QuickSort, MergeSort) and searching algorithms (e.g., binary search).
• Example: Sorting a list of numbers in ascending order
4. Buffering and Caching
• Data Buffers: Arrays can be used to implement buffers for handling data streams and caching
frequently accessed data.
• Example: A buffer for holding data read from a file or network before processing it.

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-19


Principles of Programming using C BPOPS103/203

5. Data Structures Implementation


• Supporting Structures: Arrays are used to implement various data structures like heaps, hash
tables,
• and queues.
• Example: A priority queue implemented using a heap array.
6. Multidimensional Arrays
• Tabular Data: Multidimensional arrays (e.g., 2D arrays) are used to represent data in tabular
form.
• Example: A 2D array representing a chessboard where each cell contains information about the
piece present.
7. Game Development
• Game Boards: Arrays are used to represent game boards and keep track of game state.
• Example: An array to represent a tic-tac-toe board or a Sudoku puzzle.
8. Dynamic Programming
• Optimization Problems: Arrays are used in dynamic programming algorithms to store
intermediate results and avoid redundant computations.
• Example: The array used in the dynamic programming solution to the Fibonacci sequence.
9. Image Processing
• Pixel Data: Arrays represent images where each element corresponds to a pixel value.
• Example: A 2D array for a grayscale image where each value represents pixel intensity.
10. Graph Algorithms
• Graph Representation: Arrays are used to represent graphs, especially in adjacency matrices for
graph algorithms.
• Example: An adjacency matrix to represent a graph's edges.

3.8 User defined functions


13. Discuss in detailed the parts of a user defined function ( Jan24 10marks)
User defined functions: - The user defined function is defined by the user according to its
requirements instead of relying only on the built-in functions C allows us to create our own
function called user defined function

Parts of user defined function.


(i)Function Declaration or Function prototype
(ii)Function call or calling Function
(iii)Function Definition or defining a function

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-20


Principles of Programming using C BPOPS103/203

(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:

return_type function_name(argument _list);


Example:-
int large (int x, int y);
is a function declaration with function_name “large” with return _type “integer” and has two
arguments “x” and “y” of integer type.

(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

• large(m,n); //m and n are variables.

• large(5,8); //5 and 8 are constants

• large(5+2,6); // The first argument is an expression which is evaluated to 7

• large(2*3,5+3); //is an expression which is equivalent to large(6,8);

(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;
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-21


Principles of Programming using C BPOPS103/203

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.

C program to find factorial of the number using recursion


#include<stdio.h>
int factorial(int n);
void main()
{
int n,res;
printf("Enter the value of n\n");
scanf("%d",&n); res=factorial(n);
printf("The factorial of the number=%d\n",res);
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-22


Principles of Programming using C BPOPS103/203

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

3.10 1-D array


15. Explain the declaration and initialization of 1-D arrays(Jan24 5marks)
An Array which has only one subscript is known as Singledimensional array or One dimensional
array.The individual array elements are processed by using a common array name with different
index values that start with Zero and ends with array_size-1.

Syntax of Declaring Single Dimensional Arrays


data_type array_name[array_size];
where
data_type: can be int, float or char
array_name: is name of the array
array_size : an integer constant indicating the maximum number of data elements to be stored.
Example: int a[5];
Here a is an Integer Array that can hold up to 5 values in it.
Array Representation

Here,
a[0] holds the first element in the arraya[1]

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-23


Principles of Programming using C BPOPS103/203

holds second element in the array a[2] holds


third element in the array and so on…..

1.Declare and Initialize at the Same Time

You can declare an array and set its initial values in one line.

Example: int numbers[5] = {1, 2, 3, 4, 5};

2.Partial Initialization

If you provide fewer initializers than the array size, the remaining elements are automatically set to
0.

Example: int numbers[5] = {1, 2}; // Remaining elements are 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

You can initialize an array using a loop after declaring it.

Example: int numbers[5]; for (int i = 0; i < 5; i++)

numbers[i] = i * 2; // Initializes to 0, 2, 4, 6, 8

16. write a c program to perform matrix multiplication(Jan24 10marks)


#include <stdio.h>

#define ROW1 2

#define COL1 3

#define ROW2 3

#define COL2 2

int main()

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-24


Principles of Programming using C BPOPS103/203

int m1[ROW1][COL1] = {{1, 2, 3}, {4, 5, 6}};

int m2[ROW2][COL2] = {{7, 8}, {9, 10}, {11, 12}};

int res[ROW1][COL2] = {0};

for (int i = 0; i < ROW1; i++)

for (int j = 0; j < COL2; j++)

for (int k = 0; k < COL1; k++)

res[i][j] += m1[i][k] * m2[k][j];

for (int i = 0; i < ROW1; i++)

for (int j = 0; j < COL2; j++)

printf("%d ", res[i][j]);

printf("\n");

return 0;

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-25


Principles of Programming using C BPOPS103/203

3.11 Scope of variables


17. Explain the scope of the variables
The scope of a variable refers to the portion of the code where the variable is accessible. The scope
determines where a variable can be used or referenced.

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);
}

3. Static Local Scope

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-26


Principles of Programming using C BPOPS103/203

Definition: Variables declared inside a function with the static keyword.


Accessibility: These variables are only accessible within the function where they are declared.
Lifetime: The variable retains its value between function calls and exists for the entire duration of
the program, but is not accessible outside the function.
Example:
void myFunction()
{
if (1)
{
int blockVar = 30;
printf("%d\n", blockVar);
}
printf("%d\n", blockVar);
}

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");
}

3.12 Sorting techniques


18. explain various sorting techniques in C programming.
The Process of arranging the elements in ascending or descending order is called sorting.

Bubble sort: The sorting algorithm is a comparison based algorithm in which each pair of adjacent

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-27


Principles of Programming using C BPOPS103/203

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.

/*C program to sort n numbers using Bubble sort*/


#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("The entered elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n***** SORTING ******\n");
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1]; a[j+1]=temp;
}
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-28


Principles of Programming using C BPOPS103/203

}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}

Selection sort: This is an in-place comparison based algorithm It is comparison basedalgorithm in


which list is divided into 2 parts. The sorted part at left and unsorted part at right end. Initially
sorted part is empty and unsorted part is entire list. The smallest element is takenfrom the unsorted
array and swapped with the leftmost element and the element becomes the part of sorted array.

/*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;
}

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-29


Principles of Programming using C BPOPS103/203

}
}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}

3.13 Searching techniques


19.explain various searching techniques in c

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

• Works well for small arrays

• Used to search when the elements are not sorted

Disadvantages:
• Less efficient if the array is large

• If the elements are already sorted, linear search is not efficient.

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

1. Divides the array into three sections:


– middle element
– elements on one side of the middle element
– elements on the other side of the middle element
2. If the middle element is the correct value, done. Otherwise, go to step 1. using only thehalf

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-30


Principles of C Programming BPOPS103/203

of the array that may contain the correct value.

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.

3.14 Operations on Arrays


20.What are the various operations performed on arrays?

There are a number of operations that can be performed on arrays.These operations include the
following.

(i) Traversing an array


(ii) Inserting an element in an array
(iii) Deleting an element from an array
(iv) Merging two arrays
(v) Searching an element in an array
(vi) Sorting an array in ascending or descending order

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-31


Principles of C Programming BPOPS103/203

3.15 QUESTION BANK


1.Define an array. Explain with an example. how to declare and initialize 2D-array (Feb23 6marks)
2.Write a c program to search an element using binary search technique (for numericals) (Feb23
6marks)
3.Write a c program to perform addition of 2dimensional matrix (considering 3X3 order matrices A
and B) (Feb24 8marks)
4.Define function. Explain the type of functions based on parametersDefinition (Feb24 8marks)
5.Write a C program to sort the elements using bubble sort technique by passing arrays as function
arguments(Feb24 6marks)
6.Explain the syntax of function declaration and function definition with example (June23 6marks)
7.Write a c program to swap two numbers using call by reference method (June23 6marks)

8.Write a C program to find (June23 6marks)

𝑛!
𝑛𝐶𝑟 =
(𝑛 − 𝑟)! 𝑟!

9.Describe different types storage classes with examples (Jan24/June23 10/8marks)


10.What is an array? Explain how arrays are declared and initialized with example(June23 8marks)
11. Write a C program to transpose a 3x3 matrix (June23 8marks)
12. List applications of array ( June23 4marks)
13. Discuss in detailed the parts of a user defined function ( Jan24 10marks)
14. Define recursion. write a c program to find factorial of ‘n’ using recursion(Jan24 5marks)
15. Explain the declaration and initialization of 1-D arrays(Jan24 5marks)
16. write a c program to perform matrix multiplication(Jan24 10marks)
17. Explain the scope of the variables
18. explain various sorting techniques in C programming.
19.explain various searching techniques in C
20.What are the various operations performed on arrays.

****************************

Prof. Jerusha Madhurya.P, Asst.Prof., Dept of CSE, Dr.TTIT, KGF 3-32


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

DEPARTMENT OF COMPUTER SCEINCE AND ENGINEERING

Table of Contents

MODULE: 4

STRINGS AND POINTERS:

Topics Page No.

4.1 Introduction to Strings 4-1

4.2 String declaration and Initialization 4-3

4.3 Operations on strings 4-4

4.4 Pointers: Introduction to pointers 4-5

4.5 Pointer Arithmetic 4-6

4.6 Types of Pointers 4-7

4.7 Question Bank 4-11


Principles of Programming using C BPOPS103/203

MODULE: 4
STRINGS AND POINTERS

4.1 INTRODUCTION TO STRINGS

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

String manipulation function are as follows:-

 strcpy( ) – String Copy


It is possible to assign the value to a string variable using strcpy( ). It allows us to copy
one string from one location to another.
Syntax:
strcpy(destination, source);
Ex: char a[10], b[10];
strcpy(a, “TTIT”);
strcpy(b, a);
After two calls to strcpy( ) a, b contains TTIT.

 strlen( ) – String Length

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

 strcmp( ) – String Compare

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

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

1. Explain how strings are represented in main memory?


char str[] = “HELLO”;

 We are declaring a character array with 5 characters namely, H, E, L, L and O.

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

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 name of the character array (or the string) is a pointer to the beginning of the string.

 The above string can be represented as follows

str[0] 1000 H

str[1] 1001 E
str[2] 1002 L
str[3] 1003 L
str[4] 1004 O
str[5] 1005 \0

4.2 STRING DECLARATION AND INITIALISATION:

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

4.3 OPERATIONS ON STRINGS

1. Develop a C program to concatenate 2 strings without using built-in function?


5 m, June 2022
#include<stdio.h>
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0'){
str1[i]=str2[j];
j++;
i++;}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
2. Write a program to compare two strings without using built-in function?
10m, Aug 2022
#include<stdio.h>
#include<conio.h>
void main()
{
char string1[5],string2[5];
int i,temp = 0;
printf(“Enter the 1st string :\n”);
gets(string1);
printf(“\n Enter the 2nd String :\n”);
gets(string2);

Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 4-4
Principles of Programming using C BPOPS103/203

for(i=0; string1[i]!=’\0′; i++)


{
if(string1[i] == string2[i])
temp = 1;
else
temp = 0;
}
if(temp == 1)
printf(“Both the strings entered are same.”);
else
printf(“Both the strings entered are not same.”);
getch();
}

4.4 POINTERS: INTRODUCTION TO POINTERS


1. Define Pointer. Explain pointer variable declaration and initialization with suitable
example
Aug 2022,2019-20
 A pointer is a variable which contains the address of another variable

Declaring of a pointer variable

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

Initializing a pointer variable is a important thing, it is done as follows:


 Step 1: Declare a data variable
 Step 2: Declare a Pointer variable
 Step 3:Assign address of data variable to pointer variable using & operator and
assignment operator.

Example:
int x;
int *p
p = &x;

4.5 Pointer Arithmetic

1. What is pointer? Discuss pointer arithmetic with suitable C code . 10m,Jan 2021

 Pointer arithmetic operations are different from normal arithmetic operations.


 The operations allowed to on Pointers are:
 Add or subtract integers to/from a pointer. The result is a pointer. z
 Subtract two pointers to the same type. The result is an int.
 Comparison of two pointers
 Note: Multiplication, addition, division of two pointers not allowed.
C code:
int num1=2, num2= 3, sum=0, mul=0, div=1;
int *ptr1, *ptr2;
ptr1 = &num1;
ptr2 = &num2;
sum = *ptr1 + *ptr2;
mul = sum * *ptr1;
*ptr2 +=1;
div = 9 + *ptr1/*ptr2 - 30;

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 .

3. List the advantages and disadvantages of pointers. 10m, jan 2021


Advantages of pointers:
 Pointers provide direct access to memory
 Pointers provide a way to return more than one value to the functions
 Reduces the storage space and complexity of the program
 Reduces the execution time of the program
 Provides an alternate way to access array elements
 A pointer allows us to perform dynamic memory allocation and deallocation.
 Pointers helps us to build complex data structures like linked list, stack, queues,
trees, graphs etc.
Disadvantages of pointers:
 Uninitialized pointers might cause segmentation fault.
 Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
 Pointers are slower than normal variables.
 If pointers are updated with incorrect values, it might lead to memory corruption.

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

4.7 Question Bank

1. Explain any 5 string manipulation library function with example.


2. List the advantages and disadvantages of pointers.
3. Write a c program to swap two variables using pointers?
4. Write a c program to copy one string to another string using strcpy() ?
5. Discuss the pointer arithmetic?
6. Write a program to find sum of squared number using macro square(n)?
7. What is the purpose of null pointers in C strings?
8. How strings are represented in main memory?
9. What is pointer? Explain how to declare and initialize pointer variables?
10. Differentiate between gets() and fgets().
11. Develop a C program to concatenate 2 strings without using built-in function
12. Explain the difference between a null pointer and a void pointer
13. Develop a C program to find the largest of three numbers using pointer.

*******************************************************

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

DEPARTMENT OF COMPUTER SCEINCE AND ENGINEERING

Table of Contents

MODULE: 5

STRUCTURE, UNION, AND ENUMERATED DATA TYPE:

Topics Page No.

5.1 Introduction to Structure 5-1

5.2 Structures and Functions 5-7

5.3 Union 5-9

5.4 Enumerate Data Types 5-11

5.5 Introduction to Files 5-14

5.6 Reading and writing data files 5-16

5.7 Detecting End of Files 5-22

5.8 Question Bank 5-23


Principles of Programming using C BPOPS103/203

MODULE: 5

STRUCTURE, UNION, AND ENUMERATED DATA TYPE:

5.1 INTRODUCTION TO STRUCTURE

1. Define Structure. Explain declaration and initialization of structure.


➢ Structure is basically a user-defined data type that can store related information (even
of different data types) together.
➢ The major difference between structure and an array is that, an array contains related
information of the same data type.

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;
};

➢ The structure definition does not allocates any memory.

➢ 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

➢ For ex, we can define a variable of student by writing


➢ struct student stud1

Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-1
Principles of Programming using C BPOPS103/203

INITIALIZATION OF STRUCTURES

➢ Initializing a structure means assigning some constants to the members of the


structure.

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

The general syntax to initialize a structure variable is given as follows.

struct struct_name

{ data_type member_name1;

data_type member_name2;

data_type member_name3;

}struct_var = {constant1, constant2, constant 3,...};

OR

struct struct_name

data_type member_name1;

data_type member_name2;

data_type member_name3;

.......................................

};

❖ Uses of structure:

➢ Structures are used to represent more complex data structure.

➢ Related data items of dissimilar data types can be grouped under a common name.

➢ Can be used to pass arguments so as to minimize the number of function arguments.

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.

➢ Extensively used in applications involving database management.

2. Explain about the typedef definition? 10m,june2023

Typedef is a keyword that allows the programmer to create new data type name for an
already existing datatype.

Syntax:

typedef old datatype newdatype ;

Example:

typedef int MARKS;

typedef float AMOUNT;

Example: Program to compute simple interest using typedef definition

#include<stdio.h>

typedef float AMOUNT;

typedef float TIME;

typedef float RATE;

void main( )

AMOUNT p,si;

TIME t;

RATE r;

printf(“enter the value of p,t,r\n”);

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:

1.Provide a meaningful way of declaring variable

2.Increases readability of program

3.A complex and lengthy declaration can be reduced to short and meaningful declaration

4.Helps the programmer to understand source code easily.

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

printf("AVG = %f \n",AVG); j=0;


k=0;
for (i=0;i<n;i++)
{
if (s[i].total> AVG)
{
aboveavg[j]=i; j++;
}
else
{
belowavg[k]=i; k++;
}
}
printf("Students scoring above avg. \n"); for (i=0;i<j;i++)
{
printf("%s %f\n",s[aboveavg[i]].name,s[aboveavg[i]].total);
}
printf("Students scoring below avg. \n"); for (i=0;i<k;i++)
{
printf("%s %f\n",s[belowavg[i]].name,s[belowavg[i]].total);
}
}
4. Write a program using structures to read and display the information about a
student?

#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

struct student stud1;


printf(“\n Enter the roll number : “);
scanf(“%d”, &stud1.roll_no);
printf(“\n Enter the name : “);
scanf(“%s”, stud1.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud1.fees);
printf(“\n Enter the DOB : “);
scanf(“%s”, stud1.DOB);
printf(“\n ********STUDENT’S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud1.roll_no);
printf(“\n NAME. = %s”, stud1.name);
printf(“\n ROLL No. = %f”, stud1.fees);
printf(“\n ROLL No. = %s”, stud1.DOB);
}
5. Explain about nested structure in C? 6m, June 2022
A structure can be placed within another structure. That is, a structure may contain
another structure as its member. Such a structure that contains another structure as its
member is called a nested structure.
typedef struct
{ char first_name[20];
char mid_name[20];
char last_name[20];
}NAME;
typedef struct
{ int dd;
int mm;
int yy;
}DATE;
struct student stud1;
stud1.name.first_name = “Janak”;
stud1.name.mid_name = “Raj”;
stud1.name.last_name = “Thareja”;
stud1.course = “BCA”;

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;

5.2 STRUCTURE AND FUNCTION

1. Write a program for passing a structure to a function? 6m, June 2021


The general syntax for passing a structure to a function and returning a structure can be
given as,
struct struct_name func_name(struct struct_name struct_var);

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

1. Write a program using pointer to structure to initialize the members in the


structure.
#include<stdio.h>
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
main()
{ struct student stud1, *ptr_stud1;
ptr_stud1 = &stud1;
ptr_stud1->r_no = 01;
strcpy(ptr_stud1->name, "Rahul");
strcpy(ptr_stud1->course, "BCA");
ptr_stud1->fees = 45000;
printf("\n DETAILS OF STUDENT");
printf("\n ---------------------------------------------");
printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
printf("\n NAME = ", puts(ptr_stud1->name));
printf("\n COURSE = ", puts(ptr_stud1->course));
printf("\n FEES = %f", ptr_stud1->fees);
}

2. Explain about Self Referential Structures? 5m, jan 2022


➢ Self referential structures are those structures that contain a reference to data of its
same type. That is, a self referential structure in addition to other data contains a
pointer to a data that is of the same type as that of the structure. For example,
consider the structure node given below.
struct node
{
int val;
struct node *next; };

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

1 Define Union. Explain declaration and initialization of 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.

➢ To better understand union, think of it as a chunk of memory that is used to store


variables of different types. When a new value is assigned to a field, the existing
data is replaced with the new data.

➢ 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

The syntax for declaring a union is same as that of declaring a structure.

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.

➢ Like structure, a union is a collection of variables of different data types. The

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.

➢ To better understand union, think of it as a chunk of memory that is used to


store variables of different types. When a new value is assigned to a field, the
existing data is replaced with the new data.

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

b. ACCESSING A MEMBER OF A UNION

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

➢ A striking difference between a structure and a union is that in case of a union,


the field fields share the same memory space, so fresh data replaces any existing data.
#include<stdio.h>

typedef struct POINT1

{ int x, y;

};

typedef union POINT2

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 ={4,5}; Illegeal with union

POINT2 P2;

P2. x = 4;

P2.y = 5;

printf("\n The co-ordinates of P1 are %d and %d", P1.x, P1.y);

printf("\n The co-ordinates of P2 are %d and %d", P2.x, P2.y);

return 0;

2. Difference between structure and union. 5m,June 2022

5.4 ENUMERATED DATA TYPES

1. Explain about Enumerated data types in C? 5m, June 2023


➢ The enumerated data type is a user defined type.
➢ An enumeration consists of a set of named integer constants. That is, in an
enumerated type, each integer value is assigned an identifier.
➢ To define enumerated data types, enum keyword is used.

Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-11
Principles of Programming using C BPOPS103/203

➢ The syntax of creating an enumerated data type can be given as below.


enum enumeration_name { identifier1, identifier2, …..., identifiern };
➢ Consider the example given below which creates a new type of variable called
COLORS to store colors constants.

enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};

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;

2. Implement structures to read, write, compute average- marks and the


students scoring above and below the average marks for a class of N
students. 8m, June 2023

#include<stdio.h>

struct 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++)

Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-12
Principles of Programming using C BPOPS103/203

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;

printf("AVG = %f \n",AVG); j=0;

k=0;

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

if (s[i].total> AVG)

aboveavg[j]=i; j++;

else

belowavg[k]=i; k++;

printf("Students scoring above avg. \n"); for (i=0;i<j;i++)

printf("%s %f\n",s[aboveavg[i]].name,s[aboveavg[i]].total);

printf("Students scoring below avg. \n"); for (i=0;i<k;i++)

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);

5.5 INTRODUCTION TO FILES

1. Explain about files in C?


➢ A file is a collection of data stored on a secondary storage device like hard disk.
➢ A file is basically used because real life applications involve large amounts of data and
in such situations the console oriented I/O operations pose two major problems:
● First, it becomes cumbersome and time consuming to handle huge amount of data through
terminals.
● Second, when doing I/O using terminal, the entire data is lost when either the program is
terminated or computer is turned off. Therefore, it becomes necessary to store data on a
permanent storage (the disks) and read whenever necessary, without destroying the data
2. Explain about the three standard streams in C language?
stream is a logical interface to the devices that are connected to the computer.
The three standard streams in C languages are-
➢ Standard input (stdin): Standard input is the stream from which the program receives its
data. The program requests transfer of data using the read operation. However, not all
programs require input. Generally, unless redirected, input for a program is expected from
the keyboard.
➢ Standard output (stdout): Standard output is the stream where a program writes its
output data. The program requests data transfer using the write operation. However, not
all programs generate output.
➢ Standard error (stderr): Standard error is basically an output stream used by programs
to report error messages or diagnostics
● A stream is linked to a file using an open operation and disassociated from a file using a
close operation.
KEYBOARD

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

2. Explain about the types of files in C?


In C, the types of files used can be broadly classified into two categories- text files and
binary files.

ASCII Text files


➢ A text file is a stream of characters that can be sequentially processed by a computer in
forward direction. For this reason a text file is usually opened for only one kind of
operation (reading, writing, or appending) at any given time.
➢ In a text file, each line contains zero or more characters and ends with one or more
characters that specify the end of line. Each line in a text file can have maximum of 255
characters.
BINARY FILES
➢ A binary file is a file which may contain any type of data, encoded in binary form for
computer storage and processing purposes. Like a text file, a binary file is a collection of
bytes. Note that in C a byte and a character are equivalent. Therefore, a binary file is also
referred to as a char
➢ Like text file, binary file also ends with an EOF marker.
➢ This clearly indicates that binary files takes less space to store the same piece of data and
eliminates conversion between internal and external representations and are thus more
efficient than the text files.

2. Explain about the various modes of file?


➢ The various mode in which a file can be opened/created are:

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

a Append to a text file. if the file does not exist, it is created.

rb Open a binary file for reading. B indicates binary.

Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-15
Principles of Programming using C BPOPS103/203

wb Open a binary file for writing

ab Append to a binary file

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.

r+b/ rb+ Open a binary file for read/write

w+b/wb+ Create a binary file for read/write

a+b/ab+ Append a binary file for read/write

5.6 Reading and writing data files


1. Write a short note on functions used to
• Read data from a file
• Write data to a file 10m, jan 2022

❖ Read data from a file:


C provides the following set of functions to read data from a file.
● fscanf()
● fgets()
● fgetc()
● fread()

❖ 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()

➢ The fread() function is used to read data from a file.


➢ Its syntax can be given as
int fread( void *str, size_t size, size_t num, FILE *stream );

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

printf("\n %d bytes were written to the files”, count);


fclose(fp);
}

5.7 DETECTING THE END-OF-FILE


1. Explain about how to detect end of file?
In C, there are two ways to detect the end-of-file
➢ While reading the file in text mode, character by character, the programmer can
compare the character that has been read with the EOF, which is a symbolic constant
defined in stdio.h with a value -1.
while(1)
{ c = fgetc(fp);// here c is an int variable
if (c==EOF)
break;
printf("%c", c);
}
➢ The other way is to use the standard library function feof() which is defined in
stdio.h. The feof() is used to distinguish between two cases
➢ When a stream operation has reached the end of a file
➢ When the EOF ("end of file") error code has been returned as a generic error
indicator even when the end of the file has not been reached
➢ The prototype of feof() can be given as:
int feof(FILE *fp);
Feof() returns zero (false) when the end of file has not been reached and a one (true) if the
end-of-file has been reached.
while( !feof(fp)
{ fgets(str, 80, fp);
printf("\n %s", str);
}

Parvathi T.R., Asst. Prof., Dept. of CSE, Dr. TTIT, KGF 5-22
Principles of Programming using C BPOPS103/203

5.8. Question Bank

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:

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem analysis: Identify, formulate, research literature, and analyze complex


engineering problems reaching substantiated conclusions using rst principles of
mathematics, natural sciences, and engineering sciences.

3. Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specied needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

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.

7. Environment and Sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts and demonstrate the knowledge of need
for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

9. Individual and Teamwork: Function effectively as an individual, and as a member or leader


in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.

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

Mission of Computer Science and Engineering


To provide appropriate infrastructure to impart need-based technical education through
effective teaching and research.
To involve the students in innovative projects on emerging technologies to fulll industrial
requirements.
To render leadership skills and ethical responsibilities in students that leads them to
become globally competent professionals.

You might also like