0% found this document useful (0 votes)
13 views76 pages

C Programming LabManual

The document is a master manual for the 'Principles of Programming using C' course (BPOPS103) offered by the Department of Computer Science and Engineering at AJ Institute of Engineering & Technology for the academic year 2023-24. It outlines the vision and mission of the institute and department, program educational objectives, outcomes, general lab guidelines, syllabus, and assessment details. The course aims to equip students with programming skills in C, focusing on problem-solving, data structures, and structured programming constructs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views76 pages

C Programming LabManual

The document is a master manual for the 'Principles of Programming using C' course (BPOPS103) offered by the Department of Computer Science and Engineering at AJ Institute of Engineering & Technology for the academic year 2023-24. It outlines the vision and mission of the institute and department, program educational objectives, outcomes, general lab guidelines, syllabus, and assessment details. The course aims to equip students with programming skills in C, focusing on problem-solving, data structures, and structured programming constructs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 76

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

JNANA SANGAMA, BELGAVI-590018, KARNATAKA

A J INSTITUTE OF ENGINEERING & TECHNOLOGY


(A unit of Laxmi Memorial Education Trust. (R))
NH - 66, Kottara Chowki, Kodical Cross - 575 006

Offering Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
(Accredited by NBA)

MASTER MANUAL

Course: Principles of Programming using C


Course Code: BPOPS103

I-SEMESTER

ACADEMIC YEAR: 2023-24


C Programming Laboratory BPOPS103

VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELAGAVI


B.E. in Computer Science and Engineering

Scheme of Teaching and Examinations 2022

Outcome-Based Education (OBE) and Choice Based Credit System (CBCS)

(Effective from the academic year 2021 - 22)

Integrated Professional Core Course (IPCC)


Refers to Professional Theory Core Course Integrated with Practical’s of the same course

Course: Principles of Programming using C

Course Code: BPOPS103


C Programming Laboratory BPOPS103

TABLE OF CONTENTS
Item Page No.

Vision, Mission and Program Educational Objectives


i

Program Outcomes (POs) and Program Specific Outcomes (PSOs)


ii

General Lab Guidelines- Do’s & Don’ts


iii-v

Syllabus- Course Objectives & Suggested Learning Resources


vi-viii

Course Outcomes- Mapping of Course Outcomes with POs & PSOs


ix

Assessment Details (both CIE and SEE) -Scheme of Evaluation


x-xii

Rubrics
xiii

List of Major Equipment


xiv

List of Experiment/Programs & Additional Experiment/Programs


xv
C Programming Laboratory BPOPS103

VISION OF THE INSTITUTE


“To produce top-quality engineers who are groomed for attaining excellence in their profession
and competitive enough to help in the growth of nation and global society.”

MISSION OF THE INSTITUTE


M1: To offer affordable high-quality graduate program in engineering with value education
and make the students socially responsible.
M2: To support and enhance the institutional environment to attain research excellence in
both faculty and students and to inspire them to push the boundaries of knowledge base.
M3: To identify the common areas of interest amongst the individuals for the effective
industry- institute partnership in a sustainable way by systematically working together.
M4: To promote the entrepreneurial attitude and inculcate innovative ideas among the
engineering professionals.

VISION OF THE DEPARTMENT


“To adapt the evolutionary changes in computer science and expose the students to the cutting-
edge technologies to produce globally competent professionals.”

MISSION OF THE DEPARTMENT


M1: To mould the students by providing quality computer education and by strengthening
the Industry -Academic interface.
M2: To impart the professional skills, innovative research activities and entrepreneurial
capabilities in students.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


After 4 years of graduation, graduates will be able to
PEO1: To develop in students, the ability to solve real life problems by applying fundamental
science and elementary strengths of computer science courses.
PEO2: To mould students, to have a successful career in the IT industry where graduates will
be able to design and implement the needs of society and nation.
PEO3: To transform students, to excel in a competitive world through higher education and
indulge in research through continuous learning process

AJIET, Dept. of CSE, Mangalore i


C Programming Laboratory BPOPS103

PROGRAM OUTCOMES (POs)


PO1: Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2: Problem Analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
PO3: Design/Development of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
PO4: 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.
PO5: 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.
PO6: 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.
PO7: Environment and Sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9: Individual and Team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
PO10: 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.
PO11: 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.
PO12: 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.

PROGRAM SPECIFIC OUTCOMES (PSOs)


At the end of the program, graduates will be able to
PSO1: Apply engineering principles, professional ethics and fundamental science in designing
systems and communication models (protocols).

AJIET, Dept. of CSE, Mangalore ii


C Programming Laboratory BPOPS103

PSO2: Design and develop smart and intelligent based applications in computational
environment.

GENERAL LAB GUIDELINES

Do's
1. Maintain discipline in the Laboratory.
2. Before entering the Laboratory, keep the footwear on the shoe rack.
3. Proper dress code has to be maintained while entering the Laboratory.
4. Students should carry a lab observation book, student manual and record book
completed in all aspects.
5. Read and understand the logic of the program thoroughly before coming to the
laboratory.
6. Enter the login book before switching on the computer.
7. Enter your batch member names and other details in the slips for hardware kits.
8. Students should be at their concerned places; unnecessary movement is restricted.
9. Students should maintain the same computer until the end of the semester.
10. Report any problems in computers/hardware kits to the faculty member in-
charge/laboratory technician immediately.
11. The practical result should be noted down into their observation and the result must
be shown to the faculty member in-charge for verification.
12. After completing the experiments, students should switch off the computers, enter
logout time, return the hardware kits and keep the chairs properly.

Don'ts
1. Do not come late to the Laboratory.
2. Do not enter the laboratory without an ID card, lab dress code, observation book and
record.
3. Do not leave the laboratory without the permission of the faculty in-charge.
4. Never eat, drink while working in the laboratory.
5. Do not handle any equipment before reading the instructions/instruction manuals.
6. Do not exchange the computers with others and hardware kits also.
7. Do not misbehave in the laboratory.
8. Do not alter computer settings/software settings.
9. External Disk/drives should not be connected to computers without permission, doing
so will attract fines.
10. Do not remove anything from the kits/experimental set up without permission. Doing
so will attract fines.
11. Do not mishandle the equipment / Computers.
12. Do not leave the laboratory without verification of hardware kits by the lab instructor.

AJIET, Dept. of CSE, Mangalore iii


C Programming Laboratory BPOPS103

13. Usage of Mobile phones, tablets and other portable devices are not allowed in
restricted places.

INSTRUCTIONS TO STUDENTS

● Students must bring Observation book, record and manual along with pen, pencil, and
eraser etc., no borrowing from others.
● Students must handle the trainer kit and other components carefully, as they are expensive.
● Before switch on the trainer kit, must show the connections to one of the faculties or
instructors.
● After the completion of the experiment should return the components to the respective lab
instructors.
● Before leaving the lab, should check whether they have switch off the power supplies and
keep their chairs properly.
● Be regular to the Lab Do not come late to the Lab
● Do not throw connecting wires on the Floor
● Wear your College ID card Do not operate the IC trainer kits without permission
● Avoid unnecessary talking while doing the experiment
● Avoid loose connection and short circuits
● Take the signature of the lab in charge before taking the components
● Do not interchange the ICs while doing the experiment
● Handle the trainer kit properly
● Do not panic if you do not get the output
● Keep your work area clean after completing the experiment.
● After completion of the experiment switch off the power and return the components
● Arrange your chairs and tables before leaving.

AJIET, Dept. of CSE, Mangalore iv


C Programming Laboratory BPOPS103

RULES FOR MAINTAINING LABORATORY RECORD

● Put your name, USN and subject on the outside front cover of the record.
Put that same information on the first page inside.
● Update Table of Contents every time you start each new experiment or topic
● Always use pen and write neatly and clearly
● Start each new topic (experiment, notes, calculation, etc.) on a right-side
(odd numbered) page
● Obvious care should be taken to make it readable, even if you have bad handwriting
● Date to be written every page on the top right side corner
● On each right-side page
⮚ Title of experiment
⮚ Aim/Objectives
⮚ Components Required
⮚ Theory
⮚ Procedure described clearly in steps
⮚ Result
● On each left side page
⮚ Pin diagrams
⮚ Circuit diagram
⮚ Tables
⮚ Graphs
● Use labels and captions for figures and tables
● Attach printouts and plots of data as needed. Stick printouts (A4 Size) on
the right side of the lab record
● Strictly observe the instructions given by the Teacher/ Lab Instructor.

AJIET, Dept. of CSE, Mangalore v


C Programming Laboratory BPOPS103

SYLLABUS
PRINCIPLES OF PROGRAMMING USING C
[As per Choice Based Credit System (CBCS) scheme] (Effective
from the academic year 2022 -2023)
SEMESTER – I
Course Code BPOPS103 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 2:0:2:0 SEE Marks 50
Total Hours of Pedagogy 40 T + 20 P Total Marks 100
Credits 03 Exam Hours 03
Course Learning Objectives:
CLO 1. Elucidate the basic architecture and functionalities of a Computer
CLO 2. Apply programming constructs of C language to solve the real-world problems
CLO 3.Explore user-defined data structures like arrays, structures and pointers in implementing
solutions to problems
CLO 4. Design and Develop Solutions to problems using structured programming constructs such
as functions and procedures

Teaching-Learning Process (General Instructions)


These are sample Strategies, which teachers can use to accelerate the attainment of the various
course outcomes.
1. Lecturer method (L) does not mean only traditional lecture method, but different type of
teaching methods may be adopted to develop the outcomes.
2. Show Video/animation films to explain functioning of various concepts.
3. Encourage collaborative (Group Learning) Learning in the class.
4. Ask at least three HOT (Higher order Thinking) questions in the class, which promotes
critical thinking.
5. adopt Problem Based Learning (PBL), which fosters students’ Analytical skills, develop
thinking skills such as the ability to evaluate, generalize, and analyze information rather
than simply recall it.
6. Topics will be introduced in a multiple representation.
7. Show the different ways to solve the same problem and encourage the students to come up
with their own creative ways to solve them.
8. Discuss how every concept can be applied to the real world - and when that's possible, it
helps improve the students' understanding.
Laboratory Component

1 Simulation of a SimpleCalculator.
2 Compute the roots of a quadratic equation by accepting the coefficients.
Print appropriate messages.
3 An electricity board charges the following rates for the use of electricity: for
the first 200 units 80 paise per unit:
for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All

AJIET, Dept. of CSE, Mangalore vi


C Programming Laboratory BPOPS103

users are charged a minimum of Rs.


100 as meter charge. If the total amount is more than Rs 400, then an
additional surcharge of 15% of total amount
is charged. Write a program to read the name of the user, number of units
consumed and print out the charges.
4 Write a C Program to display the following by reading the number of rows as
input,
1
121
12321
1234321
---------------------------
nth row

5 Implement Binary Search on Integers.


6 Implement Matrix multiplication and validate the rules of multiplication.
7 Compute sin(x)/cos(x) using Taylor series approximation. Compare your
result with the built-in library function.
Print both the results with appropriate inferences.
8 Sort the given set of N numbers using Bubble sort.
9 Write functions to implement string operations such as compare, concatenate,
and find string length. Use the
parameter passing techniques.
10 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.
11 Develop a program using pointers to compute the sum, mean and standard
deviation of all elements stored in an array of N real numbers.
12 Write a C program to copy a text file to another, read both the input file name
and target file name.
Course outcome (Course Skill Set)
At the end of the course the student will be able to:
CO1: Elucidate the basic architecture and functionalities of a computer and also recognize the
hardware parts
CO2: Understand the working of loops, conditional statements and solve simple computational
problems
CO3: Design and Develop Solutions to problems using arrays and modular programming
constructs using functions and recursions.
CO4: Explore user-defined data structures like strings and pointers in implementing solutions to
problems like searching and sorting.
CO5:Explore user-defined data structures like structures, unions and enumerated data files in
implementing solutions.

AJIET, Dept. of CSE, Mangalore vii


C Programming Laboratory BPOPS103

Suggested Learning Resources:

Textbooks
1.Computer fundamentals and programming in c, “Reema Thareja”, Oxford University, Second
edition, 2017.

Reference Books:
1. E. Balaguruswamy, Programming in ANSI C, 7th Edition, Tata McGraw-Hill.
2. Brian W. Kernighan and Dennis M. Ritchie, The ‘C’ Programming Language, Prentice Hall of
India.

Weblinks and Video Lectures (e-Resources):


1. elearning.vtu.ac.in/econtent/courses/video/BS/15PCD23.html
2. https://nptel.ac.in/courses/106/105/106105171/ MOOC courses can be adopted for more
clarity in understanding the topics and verities of problem solving methods.

Activity Based Learning (Suggested Activities in Class)/ Practical Based learning


1.Quizzes
2.Assignments
3. Seminars

COURSE OUTCOMES

COs COURSE OUTCOMES PO PSO


MAPPING MAPPING
CO1 Elucidate the basic architecture and functionalities of a PO1,PO5, PSO1
computer and also recognize the hardware parts. PO8,PO12
CO2 Understand the working of loops, conditional statements PO1,PO2,PO3,P PSO1
and solve simple computational problems. O4,
PO8
CO3 Design and Develop Solutions to problems using arrays PO1,PO2,PO3,P PSO1
and modular programming constructs using functions and O4,
recursions. PO8
CO4 Explore user-defined data structures like strings and PO1,PO2,PO3,P PSO1
pointers in implementing solutions to problems like O4,
searching and sorting. PO8
CO5 Explore user-defined data structures like structures, unions PO1,PO2,PO3,P PSO1
and enumerated data files in implementing solutions. O4, PO8

AJIET, Dept. of CSE, Mangalore viii


C Programming Laboratory BPOPS103

Mapping of Course Outcomes with POs & PSOs

COs COURSE OUTCOMES PO PSO


MAPPING MAPPI
NG
CO Elucidate the basic architecture and functionalities of a computer and PO1,PO5, PSO1
1 also recognize the hardware parts. PO8,PO12
CO Understand the working of loops, conditional statements and solve PO1,PO2,PO3,PO4, PSO1
2 simple computational problems. PO8
CO Design and Develop Solutions to problems using arrays and modular PO1,PO2,PO3,PO4, PSO1
3 programming constructs using functions and recursions. PO8
CO Explore user-defined data structures like strings and pointers in PO1,PO2,PO3,PO4, PSO1
4 implementing solutions to problems like searching and sorting. PO8
CO Explore user-defined data structures like structures, unions and PO1,PO2,PO3,PO4, PSO1
5 enumerated data files in implementing solutions. PO8
Course Outcome addresses program outcome: 1 - Lightly, 2 – Moderately, 3 - Highly

ASSESSMENT DETAILS (BOTH CIE AND SEE)


● The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam
(SEE) is 50%.
● The minimum passing mark for the CIE is 40% of the maximum marks (20 marks).
● A student shall be deemed to have satisfied the academic requirements and earned the credits
allotted to each subject/ course if the student secures not less than 35% (18 Marks out of 50)
in the semester-end examination (SEE), and a minimum of 40% (40 marks out of 100) in
the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester End
Examination) taken together

CONTINUOUS INTERNAL EVALUATION (CIE):


CIE of Theory:
❖ Two Unit Tests each of 25 Marks (duration 01 hour)
-scale down the average marks to 15 marks.
❖ Two assignments each of 10 Marks(Any Two Assessment Methods are followed)
-scale down the average marks to 10 marks.
❖ Total CIE=25 Marks(minimum 10 marks)

AJIET, Dept. of CSE, Mangalore ix


C Programming Laboratory BPOPS103

CIE of Practical:
❖ Practical Sessions need to be assessed by appropriate rubrics and viva-voce method.
This will contribute to 25 marks(minimum 10 marks).
Note: Minimum of 80% of the laboratory components have to be coveredNote:
Minimum of 80% of the laboratory components have to be covered.

Split-up of Marks used Practical Sessions:

Split Practical Sessions- Continuation Evaluation (CE) Marks


up of Methodology / Process Steps per Experiment
Marks
#R1 Observation, Write up of Procedure / Algorithm/ Program and 20
Execution of experiment
#R2 Record writing 15
#R3 Viva – Voce (Questions & Answers on relevant Experiment /Topic) 15
Total Marks for each experiment 50(Scale down to
15 marks)
Practical Sessions-Internal Assessment (IA)

#R1 Write-up of Procedure/Program/Algorithm 20


#R2 Conduction/Execution 20
#R3 Viva-Voce 10
Total Marks 50(Scale down to
10 marks)

● The sum of two tests, two assignments, and practical sessions will be out of 50 marks
and will CIE methods /question paper has to be designed to attain the different
levels of Bloom’s taxonomy as per the outcome defined for the course
SEMESTER END EXAMINATION(SEE):

● Theory SEE will be conducted by University as per the scheduled timetable, with
common question papers for the subject (duration 03 hours)
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a
module (with a maximum of 3 sub-questions), should have a mix of topics under
that module.
● The students have to answer 5 full questions, selecting one full question from each
module

AJIET, Dept. of CSE, Mangalore x


C Programming Laboratory BPOPS103

RUBRICS FOR PRACTICAL SESSIONS

Practical Sessions- Continuous Evaluation (CE)


Evaluation Parameter Level of Achievement
#R1: Excellent (20-16) Good (15-11) Average (10-6) Poor (5-0)
Observation/ Conduction Observation neatly Observation Observation is written Observation is
(20 Marks) written. neatly written. in unclear manner. written in unclear
Handwriting is Handwriting is Handwriting is not manner.
clear. Programs clear. Programs very clear. Programs Handwriting is not
written with no written with very written with fewer clear, Programs
mistakes. Programs few mistakes. mistakes. Programs written with lot of
executed with no Programs executed with few mistakes. Programs
errors executed with errors executed with a
very less errors large number of
errors.
#R2: Excellent (20-16) Good (15-11) Average (10-6) Poor (5-0)
Record Record is neatly Record is neatly Record is written in Record is written in
(15 Marks) written, written, an unclear manner. an unclear manner.
handwriting is clear. handwriting is Handwriting is not Handwriting is not
Mistakes are clear. Most very clear. Mistakes very clear.
covered and mistakes are are sometimes Mistakes are not
corrected properly covered and corrected properly. corrected. Record
and neatly. Record corrected Record submitted submitted after a
submitted on time properly and with a delay of 4 to 5 delay of 1 week
neatly. Record days
submitted with a
delay of 1 - 3
days
#R3: Excellent (20-16) Good (15-11) Average (10-6) Poor (5-0)
Viva Answered all Answered most Answered a few Not able to answer
(15 Marks) questions with of the questions questions. Subject any of the
elaboration has Failed to knowledge is not questions. Subject
excellent elaborate some adequate knowledge not
understanding of of the concepts adequate
the topic.
Practical Sessions- Internal Assessment (IA)
#R1: Excellent (20-16) Good (15-11) Average (10-6) Poor (5-0)
Write-Up Program neatly Program neatly Program is written in Program is written
(20 Marks) written. written. unclear manner. in unclear manner.
Handwriting is Handwriting is Handwriting is not Handwriting is not
clear. Programs clear. Programs very clear. Programs clear, Programs
written with no written with very written with fewer written with lot of
mistakes. few mistakes. mistakes. mistakes.
#R2: Excellent (20-16) Good (15-11) Average (10-6) Poor (5-0)
Conduction/Execution (20 Execution of the Execution of the Execution of the Execution of the
Marks) program done as program done as program done as per program was not
per the procedure. per the the procedure. done as per the
Programs had less procedure. Programs had more procedure.
than 10 errors. The Programs had than 20 errors. The Programs was full
errors were less than 20 errors were debugged of syntax and
debugged without errors. The with the help of logical error. The
any help. The Result errors were instructor. The Result errors were

AJIET, Dept. of CSE, Mangalore xi


C Programming Laboratory BPOPS103

was tabulated for debugged with a was tabulated for few resolved by the
all the cases. little help. The of the cases instructor. The
Result was Result was
tabulated for tabulated only for
almost all the 1 or 2 Cases
cases
#R3: Excellent (20-16) Good (15-11) Average (10-6) Poor (5-0)
Viva Answered all Answered most Answered a few Not able to answer
(10 Marks) questions with of the questions questions. Subject any of the
elaboration has Failed to knowledge is not questions. Subject
excellent elaborate some adequate knowledge not
understanding of of the concepts adequate
the topic.

Course Instructor Domain Co-Ordinator Head of Department

AJIET, Dept. of CSE, Mangalore xii


C Programming Laboratory BPOPS103

LIST OF MAJOR EQUIPMENT

Name of the Laboratory: C PROGRAMMING LABORATORY

Sl. No. Name of the Equipment Specialization Quantity


Intel core i3-4170/i3-9100 Processor, 4
1 Desktops Computers GB/8 GB RAM, 500GB/1TB HDD, 18.5” 30
Acer Monitor, Acer Keyboard & Mouse.
2 UPS 10 KVA 1
3 Switches 24 Port Gigabytes 2
4 Internet 100mbps 1
5 Projector EPSON Projector with HDMI Port 1

List of Software’s:

Operating System Ubuntu 20 LTS

Programming Language Java, C, C++

Room Number : A-112


Total Area of the laboratory : 115 Sq. Meters
Total Amount Spent : Rs. 11,10,563/-
Name of the HOD : Dr. Antony P. J
Name of the lab in charge : Mrs. Vidya Myageri
Name of the lab instructor : Mrs. Nireeksha

AJIET, Dept. of CSE, Mangalore xiii


C Programming Laboratory BPOPS103

LIST OF EXPERIMENT/PROGRAMS
Experiment’s Page No.
1 Simulation of a SimpleCalculator. 6-10
2 Compute the roots of a quadratic equation by accepting the 11-16
coefficients. Print appropriate messages.
3 An electricity board charges the following rates for the use of 17-20
electricity: for the first 200 units 80 paise per unit:
for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per
unit. All users are charged a minimum of Rs.
100 as meter charge. If the total amount is more than Rs 400, then an
additional surcharge of 15% of total amount
is charged. Write a program to read the name of the user, number of
units consumed and print out the charges.
4 Write a C Program to display the following by reading the 21
number of rows as input,
1
121
12321
1234321
---------------------------
nth row
5 Implement Binary Search on Integers. 22-26
6 Implement Matrix multiplication and validate the rules of 27-32
multiplication.
7 Compute sin(x)/cos(x) using Taylor series approximation. 33-36
Compare your result with the built-in library function.
Print both the results with appropriate inferences.
8 Sort the given set of N numbers using Bubble sort. 37-40
9 Write functions to implement string operations such as 41-46
compare, concatenate, and find string length. Use the
parameter passing techniques.
10 Implement structures to read, write and compute average- marks of the 47-50
students, list the students scoring above and below the average marks
for a class of N students.
11 Develop a program using pointers to compute the sum, mean and 51-55
standard deviation of all elements stored in an array of N real numbers.
12 Write a C program to copy a text file to another, read both the input file 56-57
name and target file name.
Additional Experiment/Programs- Content Beyond Syllabus
1. C program to find factorial of a given number using recursion
2. C program to implement binary search and linear search
3. C program to implement transpose of a given matrix.

AJIET, Dept. of CSE, Mangalore xiv


C Programming Lab BPOPS103

Familiarization with computer hardware and programming environment,


concept of naming the program files, storing, compilation, execution and
debugging. Taking any simple C- code.

Computers are machines that perform tasks or calculations according to a set of


instructions, or programs. It is an electronic device that process data, converting it
into information that is useful to people.

The functions of a computer system can be carried out by using the three main units
namely input unit, system unit and output unit. The block diagram of a computer
system is as follows:

Central Processing Unit (CPU): is commonly known as “processor” that executes


the instructions of a computer program. It has Control Unit (CU) and Arithmetic &
Logical Unit (ALU). These two units perform the basic arithmetic, logical, and
input/output operations.

a) Input unit: is used to enter data and information into a computer by user. The
devices like keyboard, mouse and scanner are commonly used input devices.
▪ A keyboard is used to enter alphanumeric characters and symbols.
▪ The mouse is used to pick or select a command from the monitor screen.
A scanner is used to scan an image or read a barcode and so on.
b) Arithmetic and Logic Unit (ALU): is a digital circuit that perform arithmetic
(Add, Sub, Multiplication, Division) and logical (AND, OR, NOT) operations. It

AJIET, Dept. of CSE, Mangalore 1


C Programming Lab BPOPS103

helps in fast computation of scientific calculations on floating-point number.


c) Control unit (CU): is the circuitry that controls the flow of information through
the processor and coordinates the activities of the other units within the processor.

d) Memory Unit (MU): is the unit where all the input data and results are stored
either temporarily or permanently. The memory of a computer has two types:
1. Main Memory / Primary Memory units
i. Random Access Memory (RAM): RAM constitutes internal memory of
the CPU for storing data, program and result. It is read/write memory. RAM
is volatile i.e. data stored in it is lost when we switch off the computer or if
there is power failure.
ii. Read Only Memory (ROM): ROM is a permanent memory that can be
read but not written. Memory access is faster in ROM compared to RAM.
ROM is non volatile. i.e. contents are not lost when the computer is switched
off. Used to store permanent programs that don‟t change
2. Secondary Memory: It is not directly connected to CPU. It is non-volatile.
Slower than primary memory but have larger capacities. Different Types of
Secondary Memory or storage devices are hard disk, Magnetic Tape, Optical
Disks – CD-ROM, DVD-ROM,
Flash memory

e) Output Unit: It is used to display or print results from a computer. Monitor,


printer and plotters are commonly used output devices.
f) Bus: A bus is a collection of wires that carries data/Instructions. It connects
physical components such as cables, printed circuits, CPU, Memory, Peripherals
etc., for sharing of Information and communication with one another.
g) Main Board or Mother Board: Mother Board is a set of Integrated Chips (ICs)
which are designed to work together. It controls the flow of data/instructionswithin
our computer. It is the main board on which other hardware componentsare
connected to enable the computer system to work as an integrated unit.
It mainly consists of, Processor, RAM Slots, CMOS Battery, IDE Controller,
Floppy Controller, BIOS, sockets, PCI slots, power connectors, different ports and
bus. Components of the ATX mother board is shown in the Figure 1.2.

AJIET, Dept. of CSE, Mangalore 2


C Programming Lab BPOPS103

Operating System: An Operating System (OS) is system software that controls and
supervises the hardware components of a computer system and it provides the
services to computer users. Examples: Windows –XP ,Windows 7, Windows 8,
Fedora, Ubuntu and Android, etc.

Figure 1.2: Components of ATX Motherboard

Compile and Run a C Program on Ubuntu Linux

Step 1: Open up a terminal

Search for the terminal application in the dash tool (Located as the topmost item in the
launcher). Open up a terminal by clicking on icon.

Step 2: Use a text editor to write the C source code

AJIET, Dept. of CSE, Mangalore 3


C Programming Lab BPOPS103

Type the command gedit hello.c (hello is the file name. .c is the c extension)

Step 3: Compile the program

Type the command gcc hello.c

gcc command will invoke the GNU C compiler to compile the file hello.c and create
the output (-o) file i.e. executable file called hello.

Step 4: Execute program

type command ./a.out

The compilation process, converts the source program instructions to a formwhich


is suitable for execution by computer. This process is carried out by a compiler.
The compiler used here is GNU C compiler. If the program is error free then the
translated program is stored on another file named fimename.o which is called as
object code.

Linking is the process of putting together other program files and functions that are
required by the program. For example if the sqrt() function is used then function
definition of this function should be brought from the math library and linked to
the main program.

The compiled and linked program is called executable object code and is stored
automatically in another file called a.out.

AJIET, Dept. of CSE, Mangalore 4


C Programming Lab BPOPS103

The command ./a.out would load the executable object code into the computer‟s
memory and execute the instructions. During the program execution, the program
may request for some data to be entered through the keyboard. Sometimes the
program does not produce the desired results if something is wrong with the
program logic or input data. Then it would be necessary to correct the source
program. In case if the source program is modified the entire process of compiling,
linking and executing the program should be repeated.

The entire process of compiling and running a C program is shown in figure below:

AJIET, Dept. of CSE, Mangalore 5


C Programming Lab BPOPS103

PROGRAM 1

Simulation of a Simple Calculator.

THEORY/LOGIC:
1. The program accepts two numbers and an operator
2. The following options are allowed
● Addition
● Subtraction
● Multiplication
● Division
● Modulo
3. Program performs the operation. Finally, it prints the results. Read the
expression from keyboard.
5. The C calculator options are implemented using the switch-case concept of C
language.
6. Whenever a case option matches the program perform those corresponding actions.

ALGORITHM:

STEP 1: START
STEP 2: [Enter an arithmetic expression]
Read num1, num2, operator value
STEP 3: [Evaluate choice with case statements]
Step 3.1: case „+‟ res=num1+num2, print res. goto step 4
Step 3.2: case „-„ res=num1-num2, print res. goto step 4
Step 3.3: case „*‟ res=num1*num2, print res. goto step 4
Step 3.4: case „/‟ if(num2==0)
print Divide by zero error . goto step 4
else
res=num1/num2, print div. goto step 4
Step 3.5: case „%‟ if(num2==0)
print “Divide by zero error”. goto step 4
else
res=num1%num2, print res. goto step 4
Step 3.6: default print “Invalid expression”
STEP 4: STOP

AJIET, Dept. of CSE, Mangalore 6


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 7


C Programming Lab BPOPS103

PROGRAM:

#include<stdio.h>
void main()
{
int num1,num2,res; char op;
printf("\n Enter a valid arithmetic expression:\n");
scanf("%d%c%d",&num1,&op,&num2);
switch(op)
{
case '+': res=num1+num2;
printf("\n Sum=%d", res);
break;
case '-': res=num1-num2;
printf("\n Difference=%d", res);
break;
case '*': res=num1*num2;
printf("\n Product=%d", res);
break;
case '/': if(num2==0)
{
printf(“Divide by zero error”);
}
else
{
res=num1/num2;
printf("\n Quotient=%d", res);
}
break;

case '%': if(num2==0)


{

AJIET, Dept. of CSE, Mangalore 8


C Programming Lab BPOPS103

printf(“Divide by zero error”);

}
else
{
res=num1%num2;
printf("\n Remainder=%d", res);

}
break;

default: printf("\a Invalid Expression");


}
}

EXPECTED OUTPUT:

OUTPUT 1

Enter a valid arithmetic expression: 14+25


Sum=39
OUTPUT 2
gcc Lab1.c
./a.out
Enter a valid arithmetic expression: 25-5
Difference=20
OUTPUT 3
gcc Lab1.c
./a.out
Enter a valid arithmetic expression: 55*19
Product=1045
OUTPUT 4
gcc Lab1.c
./a.out
Enter a valid arithmetic expression: 4/0
Divide by zero error

AJIET, Dept. of CSE, Mangalore 9


C Programming Lab BPOPS103

OUTPUT 5
gcc Lab1.c
./a.out
Enter a valid arithmetic expression: 12/0
Divide by zero error

QUESTIONS TO BE ANSWERED:

1) What is the use of header files as used in C programming?

Ans- Header files contain declarations of functions and variables that are
defined in other source files.

2) What does Structure of a C Program contain?

Ans- Documentation section, header files, preprocessor directives, function


prototype, main function, global variables, function definitions

3) What is the use of main() function?

The main function is the entry point of the program.

AJIET, Dept. of CSE, Mangalore 10


C Programming Lab BPOPS103

PROGRAM 2

Compute the roots of a quadratic equation by accepting the


coefficients. Print appropriate messages.

THEORY/LOGIC:
To read the coefficients a, b, c and check if any of coefficients value is zero, if so, print
appropriate messages and re-run the program.

Otherwise calculate discriminate and based on discriminate value classify and


compute all the possible roots with suitable message.

The Standard Form of a quadratic equation is ax + bx + c = 0.

Standard formula to solve the quadratic equations

b2 − 4ac, is called the discriminant.


Three things may occur regarding the discriminant

− 4ac > 0 then can‟t take the square root of this positive amount and there
i) If b2
will be two different real roots for the quadratic equation.

ii) If b2− 4ac < 0 then can‟t


take the square root of a negative number, so there
will be two imaginary roots.

iii) If b2−
4ac = 0 then the amount under the radical is zero and since the square
root of zero is zero, will get two real roots and they are equal.
fabs() is a built in function which purpose is: A negative value becomes positive,
positive value is unchanged. The return value is always positive

AJIET, Dept. of CSE, Mangalore 11


C Programming Lab BPOPS103

ALGORITHM:

STEP 1: START

STEP 2: [Input coefficient of quadratic equation a, b, c] Read a, b, c

STEP 3: [Check whether any of the coefficient value is zero] if a=0 and
b=0 then

print “Roots cannot be computed” end if goto step10

STEP 4: [Check for linear equation]

if a==0 then root1=-c/b

print root1 – Linear Equation end if goto step 10

STEP 5: [Calculate the discriminant value] disc = b*b-4*a*c

[Based on discriminate value classify and calculate all possible roots and
print them]

STEP 6: [Check for real and equal roots, if discriminate value is 0]


if(disc==0) then root1=root2 -b/(2*a);

print roots are real and equal, root1=root2 end if goto step10

STEP 7: [Check for real and distinct roots, if discriminate value is >0] else
if(disc>0) then root1=(-b+sqrt(disc))/(2*a); root2=(-b-sqrt(disc))/(2*a);

print The roots are real and distinct print root1 and print root2 end if goto
step10

STEP 8: [Check for real and imaginary roots, if discriminate value is <0]
if(disc<0) then real=-b/(2*a) img=sqrt(fabs(disc))/(2*a)
root1=real+i(imag) root2=real-i(imag)

print The roots are complex/imaginary print real

STEP 9: [Finished]STOP

AJIET, Dept. of CSE, Mangalore 12


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 13


C Programming Lab BPOPS103

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
float a,b,c,d,real,img,root1,root2;
printf("Enter the coefficients of a,b,c\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0 && b==0)
{
printf("Roots can't be computed\n \n");
exit(0);
}
if(a==0)
{
printf("The roots are linear\n");
root1=-c/b;
printf("root=%f\n",root1);
exit(0);
}
d=b*b-4*a*c;
if(d==0)
{
root1=-b/(2*a);
printf("Roots are Real and Equal\n Root1=Root2=%f\n",root1);
}
else if(d>0)
{
root1=(-b+sqrt(d))/(2*a);
root2=(-b-sqrt(d))/(2*a);
printf("Roots are Real and Distinct\n Root1=%f\n Root2=%f\n",root1,root2);
}
else
{
printf("Roots are Complex/Imaginary\n");
real=-b/(2*a);
img=sqrt(fabs(d))/(2*a);
printf("Root1= %f +i %f\n",real,img);
printf("Root2= %f -i %f\n",real,img);
}}

AJIET, Dept. of CSE, Mangalore 14


C Programming Lab BPOPS103

EXPECTED OUTPUT-
gedit Lab2.c
gcc Lab2.c -lm
./a.out
OUTPUT 1-
gedit Lab2.c
gcc Lab2.c -lm
./a.out
Enter the coefficients of a,b,c 0 0 5
Roots can't be computed
OUTPUT 2-
gcc Lab2.c -lm
./a.out
Enter the coefficients of a,b,c 0 7 3
The roots are linear
root=-0.428571
OUTPUT 3-
gcc Lab2.c -lm
./a.out
Enter the coefficients of a,b,c 1 2 1
Roots are Real and Equal
Root1=Root2=-1.000000
OUTPUT 4-
gcc Lab2.c -lm
./a.out
Enter the coefficients of a,b,c 1 5 2
Roots are Real and Distinct
Root1= -0.438447
Root2= -4.561553
OUTPUT 5-
gcc Lab2.c -lm
./a.out
Enter the coefficients of a,b,c 1 2 3
Roots are Complex/Imaginary Root1= -1.000000 +i 1.414214
Root2= -1.000000 -i 1.414214

AJIET, Dept. of CSE, Mangalore 15


C Programming Lab BPOPS103

QUESTIONS TO BE ANSWERED:

1. Define C- token.

Ans- Tokens are the basic elements that make up a C program.

2. Define variables.

Ans- Variables are used to store and manipulate data.

3. Briefly explain the different primary data types in C language.

Ans- primary data types represent the basic building blocks for storing and
manipulating data. Here are the main primary data types in C: int, float, char,
double, void.

4. What is conditional or decision-making statements in C language.

Ans- Conditional or decision-making statements in the C language allow the


program to make decisions based on certain conditions. Ex- if, if-else, nested if else

5. What is a quadratic equation ?

Ans- A quadratic equation is a second-order polynomial equation in a single


variable with the general form: ax2+bx+c=0

AJIET, Dept. of CSE, Mangalore 16


C Programming Lab BPOPS103

PROGRAM 3
An electricity board charges the following rates for the use of electricity: for the first
200 units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs
1 per unit. All users are charged a minimum of Rs. 100 as meter charge. If the total
amount is more than Rs 400, then an additional surcharge of 15% of the total amount is
charged. Write a program to read the name of the user, the number of units consumed,
and print out the charges.

ALGORITHM:

STEP 1: START
STEP 2: Read a customer name and the number of units

STEP 3: To check electricity unit is less than or equal to 200 and


calculate charges - if(unit<=200) then
charges=(unit*0.8)+100

STEP 4: [To check electricity unit is greater than 200 and less than or
equal to 300 and calculate charges] -

if(unit>200 && unit<=300) then


charges=(200*0.8)+(unit-200)*0.9+100

STEP 5: [To check unit is greater than 300 and


calculate charge] -if(unit>300)

charges=(200*0.8)+(100*0.9)+(unit-
300)*1+100

STEP 6: [To check and calculate if charges is


greater than 400] if(charges>400)

charges=charges+0.15*charges

STEP 7: Print name, units and charges

STEP 8: STOP

AJIET, Dept. of CSE, Mangalore 17


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 18


C Programming Lab BPOPS103

PROGRAM:
#include<stdio.h>
void main()
{
char name[20];
int unit;
float charge;
printf("Enter the name of consumer\n");
scanf("%s",name);
printf("Enter the number of units consumed\n");
scanf("%d",&unit);
if(unit<=200)
{
charge=(unit*0.80)+100;
}
else if(unit>200 && unit<=300)
{
charge=(200*0.80) + (unit-200)*0.90+100;
}
else
{
charge=(200*0.80) + (100*0.90) + (unit-300)*1+100;
}

if(charge>400)
{
charge=charge+0.15*charge;
}
printf("Consumer Name: %s\n”,name);
printf(“Number of Units consumed: %d\n”,unit);
printf(“ Total Rupees: %f \n"charge);
}

EXPECTED OUTPUT:

OUTPUT 1:
Enter the name of consumer
Rajesh
Enter the number of units
consumed 121
Consumer Name: Rajesh Units consumed: 121 Rupees: 196.80

OUTPUT 2:
gcc Lab4.c
./a.out
Enter the name of consumer

AJIET, Dept. of CSE, Mangalore 19


C Programming Lab BPOPS103

Mohan Enter the number of


units consumed 269
Consumer Name: Mohan Units consumed: 269 Rupees: 322.10

OUTPUT 3:
gcc Lab4.c
./a.out
Enter the name of consumer
Rahul Enter the number of
units consumed 350
Consumer Name: Rahul Units consumed: 350 Rupees: 400.00

OUTPUT 4:
gcc Lab4.c
./a.out
Enter the name of consumer
Smitha Enter the number of
units consumed 742
Consumer Name: Smitha Units consumed: 742 Rupees: 910.80

QUESTIONS TO BE ANSWERED:
1) Give the structure of if else statements?

Ans-if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

2) Which function is used to read input from the user in C?

Ans-scanf()

3) What is the purpose of the return statement in a function?

Ans- Returns a value from a function

4)What is the purpose of the else statement in C?

Ans-It specifies an alternative block of code to be executed if the if condition is false.

5)What is the role of the && operator in a conditional expression?


Ans- Logical AND (both conditions must be true)

AJIET, Dept. of CSE, Mangalore 20


C Programming Lab BPOPS103

PROGRAM 4

Write a C Program to display the following by reading the number of rows as input.

PROGRAM:
#include <stdio.h>
void main()
{
int i,j,rows;
printf("Input number of rows : ");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=1;j<=rows-i;j++)
printf(" ");
for(j=1;j<=i;j++)
printf("%d",j);
for(j=i-1;j>=1;j--)
printf("%d",j);
printf("\n");
}
}
EXPECTED OUTPUT:
Enter no of rows: 4

1
121
12321
1234321

AJIET, Dept. of CSE, Mangalore 21


C Programming Lab BPOPS103

QUESTIONS TO BE ANSWERED :

1)What are format specifier?


Ans-:format specifiers in C are used to take input and print the output of a type .

2)What are functions?


Ans-:A function is a set of statements enclosed within curly brackets that take inputs ,do the
computation, and provide the resultant output

AJIET, Dept. of CSE, Mangalore 22


C Programming Lab BPOPS103

PROGRAM 5

Implement Binary search on Integers/Names.

THEORY/LOGIC:

 Consider a list of numbers stored in an array and to check whether the given number
is present within the given list or not. If the number is found in the list, search is
Successful and the message is printed otherwise unsuccessful message is printed.
 Binary seaarch is applied if the items are arranged in either ascending or descending
order.
 In binary search first element is considered as low and last element is considered as
high.

● Position of middle element is found by taking first and last element is as follows.
mid=(low+high)/2
● Mid element is compared with key element, if they are same, the search is
successful. Otherwise if key element is less than middle element then searching
continues in left part of the array.
● If key element is greater than middle element then searching continues in right
part of the array.
The procedure is repeated till key item is found or key item is not found.

ALGORITHM:

STEP 1: START

STEP 2: READ the number of elements, n

STEP 3: READ the elements of array

AJIET, Dept. of CSE, Mangalore 23


C Programming Lab BPOPS103

STEP 4: READ the key element to be searched

STEP 5: Initialize low←0 and high← n-1

STEP 6: while low<= high do the following

mid← (low+high)/2

if a[mid] is equal to key

PRINT search is successful and print its position goto STEP 8

if key is greater than a[mid] then low←mid+1

else high←mid-1

STEP 7: PRINT Search is unsuccessful

STEP 8: STOP

AJIET, Dept. of CSE, Mangalore 24


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 25


C Programming Lab BPOPS103

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
void main()
{
int low, high, n, mid, i, a[50], key ;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the elements in ascending order\n");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key == a[mid])
{
printf("Successful Search & element is found at position = %d\n",mid+1);
exit(0);
}

if(key>a[mid])
{
low=mid+1;
}
else
{
high=mid-1;
}
}
printf("Unsuccessful Search\n");
}

AJIET, Dept. of CSE, Mangalore 26


C Programming Lab BPOPS103

EXPECTED OUTPUT:

OUTPUT 1:
gcc Lab5.c
./a.out
Enter number of elements
5
Enter array elements in ascending order
- 5 10 20 30 80
Enter the number to be searched 10
Search successful

OUTPUT 2:
gcc Lab5.c
./a.out
Enter number of elements 8
Enter array elements in ascending order 5 9 10 15 20 24 30 87
Enter the number to be searched 99
Search unsuccessful

QUESTIONS TO BE ANSWERED:

1. What is mean by searching?


Ans- Searching in C refers to the process of finding the location of a specific element or
value within a data structure.

2. What are the different searching techniques available?


Ans- Linear seach, Binary search

3. Describe how binary search work?


Ans- Binary search is an efficient algorithm for searching in sorted arrays. It works by
repeatedly dividing the search range in half until the target element is found or the range
becomes empty.

4. What is an array?
Ans- Array is a collection of elements of same data type.

5. Explain how 1D array is declared ?


Ans- Syntax- data_type array_name[size];
.

AJIET, Dept. of CSE, Mangalore 27


C Programming Lab BPOPS103

PROGRAM 6

Implement Matrix multiplication and validate the rules of multiplication.

THEORY/LOGIC:

Condition to satisfy for matrix multiplication: The number of columns of the 1st matrix must
be equal to the number of rows of the 2nd matrix. And the order of the resultant matrix will
have the same number of rows as the 1st matrix, and the same number of columns as the 2nd
matrix.

To read two matrices of the form A(m x n) and B(p x q) and if the compatibility is matched,
the multiplication for the defined matrices is carried out and displayed in the suitable matrix
format.

AJIET, Dept. of CSE, Mangalore 28


C Programming Lab BPOPS103

ALGORITHM:
Step 1 : Start
Step 2 : Read m,n,p,q
Step 3 : if(n!=p) then
Print “Matrix Multiplication is not Possible”
end if goto Step 8
Step 4 : Read Matrix a
for i←0 to m
for j←0 to n do
Read a[i][j]
end for
end for
Step 5 : Read Matrix b
for i←0 to p
for j←0 to q
Read b[i][j]
end for
end for
Step 6 : for i←0 to m
for j←0 to q
c[i][j] ← 0
for k←0 to n
c[i][j] ← c[i][j]+a[i][k]*b[k][j]
end for
end for
end for

Step 7: Print “Resultant Matrix”


for i←0 to m
for j←0 to q do
Print “ c[i][j]”
end for
end for
Step 8 : Stop

AJIET, Dept. of CSE, Mangalore 29


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 30


C Programming Lab BPOPS103

PROGRAM:

#include<stdio.h>
void main()
{
int a[50][50],b[50][50],c[50][50];
int m,n,p,q,i,j,k;
printf("Enter the order of Matrix A\n");
scanf("%d%d",&m,&n);
printf("Enter the order of Matrix B\n");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("Matrix Multiplication Not Possible\n");
}
else
{
printf("Enter the elements of Matrix A\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Matrix A is displayed as\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("Enter the elements of Matrix B\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("Matrix B is displayed as\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[i][j]);

AJIET, Dept. of CSE, Mangalore 31


C Programming Lab BPOPS103

}
printf("\n");
}
printf("\nMATRIX MULTIPLICATION \n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("The resultant Matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
}

EXPECTED OUTPUT:

OUTPUT 1:
Enter the order of Matrix A 2 2
Enter the order of Matrix B 2 2
Enter the elements of Matrix A 1 2 3 4
Matrix A is displayed as
1 2
3 4
Enter the elements of Matrix B 5 6 7 8 Matrix B is displayed as
5 6
7 8
The resultant Matrix is 19 22
43 50

OUTPUT 2:
gcc Lab8.c
./a.out
Enter the order of Matrix A 2 3
Enter the order of Matrix B 4 5

AJIET, Dept. of CSE, Mangalore 32


C Programming Lab BPOPS103

Matrix Multiplication Not Possible

QUESTIONS TO BE ANSWERED:
1. Differentiate row major and column major order matrices.
Ans- In row-major order, the elements of a matrix are stored row by row. The
consecutive elements of a row are placed next to each other in memory. In column-
major order, the elements of a matrix are stored column by column. The consecutive
elements of a column are placed next to each other in memory.

2. What is a two-dimensional array?


Ans- A two-dimensional (2D) array in C is a collection of elements organized in a
table or grid format, consisting of rows and columns.

3. Why do we need two for loops to read elements to a matrix?


Ans- Using two nested for loops to read elements into a matrix is a common
practice because a 2D array is essentially a table with rows and columns.

4. Under which condition two matrices can be multiplied.


Ans- Number of columns of first matrix should be equal to number of rows of
second matrix.

5. Why 2D arrays are required?


Ans- To store data in table/matrix format.

AJIET, Dept. of CSE, Mangalore 33


C Programming Lab BPOPS103

PROGRAM 7

Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the
built-in library function. Print both the results with appropriate inferences.

THEORY/LOGIC:

A Taylor Series is an expansion of a function into an infinite sum of terms, with


increasing exponents of a variable, like x, x2, x3, etc. The Taylor series for sin(x) is

sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + …….

● Input degree is converted to radian and computation of sine value takes place.
● Taylor series is a representation of a function as an infinite sum of
terms that are calculated from the values of the function's derivatives at
a single point.

ALGORITHM:

Step 1: START
Step 2: Read degree , number of terms
Step 3: Compute x = degree*3.14593/180;
term = x;
sum = x;
Step 4: Repeat the following steps for i = 1 to 10
term = term*x*x/(2*i*(2*i+1));

sum = sum+term;
Step 5: Print sum, sin(x)
Step 6: STOP

AJIET, Dept. of CSE, Mangalore 34


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 35


C Programming Lab BPOPS103

PROGRAM:
#include<stdio.h>
#include<math.h>
void main()
{
int i,n;
float degree,x,sum,term;
printf(“Enter the number of terms\n”);
scanf(“%d”,&n);
printf("Enter a value in degree\n");
scanf("%f",&degree);
x=degree*3.14593/180;
term=x;
sum=x;
for(i=1;i<=n;i++)
{
term= - term*x*x/(2*i*(2*i+1));
sum=sum+term;
}
printf("The calculated sum is = %f\n",sum);
printf("The Mathematical sine value is = %f\n",sin(x));
}

AJIET, Dept. of CSE, Mangalore 36


C Programming Lab BPOPS103

EXPECTED OUTPUT:
$gcc lab8.c -lm

$./a.out

Enter a
value in
degree 90

The calculated sum is = 1.000000

The Mathematical sine value is = 1.000000

QUESTIONS TO BE ANSWERED:
1. Why Taylor series approximation is important in science and engineering?
Ans- For function approximation, numerical analysis, error analysis.

2. What are the different loops in C?


Ans- for , while, do-while

3. What are built-in functions? Give an example.


Ans- Built-in functions, also known as library functions or standard library
functions, are predefined functions provided by programming languages or libraries
to perform common operations. Ex- printf(), scanf() etc.

4. Give out the formula to covert degree into radians.


Ans- radians=degree*3.14593/180;

5. What are the 3 components for a user defined function?


Ans- function declaration, functional call, function definition.

AJIET, Dept. of CSE, Mangalore 37


C Programming Lab BPOPS103

PROGRAM 8

Sort the given set of N numbers using Bubble sort.

THEORY/LOGIC:
□ The process of arranging elements in either ascending order or
descending order is called Sorting.

Bubble Sort
□ In this technique two successive elements of an array such as a[j] and
a[j+1] are compared.
□ If a[j]>=a[j+1] the they are exchanged, this process repeats till all
elements of an array are arranged in ascending order.
□ After each pass the largest element in the array is sinks at the bottom
and the smallest element in the array is bubble towards top. Bubble
Sort algorithm compares each pair of adjacent (neighbouring)
elements and the elements are swapped if they are not in ascending
order.

AJIET, Dept. of CSE, Mangalore 38


C Programming Lab BPOPS103

ALGORITHM:
Step 1: Start
Step 2 : Read n
Step 3: for i←0 to n
Read a[i]
end for
Step 4: for i← 1 to n
for j← 0 to n-i
if (a[j]>a[j+1]) then
temp←a[j]
a[j] ←a[j+1]
a[j+1] ←temp
end if
end for
end for
Step 5 : Print “Sorted Array”
for i←0 to n
Print “a[i]”
end for
Step 6 : Stop

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 39


C Programming Lab BPOPS103

PROGRAM:

#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]);
}
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;
}
}
}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}

EXPECTED OUTPUT:

gedit Lab10.c
gcc Lab10.c
./a.out
Enter the number of elements : 10
Enter 10 elements
12 -5 2 -30 8 -15 3 -10 6 0
The entered elements are
12 -5 2 -30 8 -15 3 -10 60
The sorted elements are
-30 -15 -10 -5 0 2 3 6 8 12

AJIET, Dept. of CSE, Mangalore 40


C Programming Lab BPOPS103

QUESTIONS TO BE ANSWERED:

1. What is mean by sorting?


Ans- Sorting is a common operation in computer science and programming that involves
arranging elements in a specific order.

2. What are the different sorting techniques available?


Ans- selection sort, merge sort, bubble sort

3. How bubble sort works? Why the name bubble?


Ans- Bubble Sort is a simple sorting algorithm that works by repeatedly stepping
through the list, comparing adjacent elements, and swapping them if they are in the
wrong order. The pass through the list is repeated until the entire list is sorted. The name
"bubble" comes from the way smaller elements "bubble" to the top of the list during each
pass.

4. What are the components of for loop?


Ans- Initialization, Condition, Update

5. What is mean by nested for loop?


Ans- A nested for loop is a loop inside another loop.

AJIET, Dept. of CSE, Mangalore 41


C Programming Lab BPOPS103

PROGRAM 9

Write functions to implement string operations such as compare, concatenate, and find
string length. Use the parameter passing techniques
.
ALGORITHM:
Step 1 : Start
Step 2 : Read str1, str2
Step 3:len1 = length(str1) and len2 = length(str2)
Step 4: Print len1, len2
Step 5: Compare(str1,str2)
Step 6: Concat(str1, str2)
Step 7: Stop

function length(str1)
for i←0 to str1[i]!= „\0‟ do
count←count+1
end for
return count

function compare(str1,str2) len1←length(str1)


len2←length(str2)
if(len1!=len2) then
Print “Strings are Different”
end if
for i←0 to str1[i]!= „\0‟ do
if(str1[i]!=str2[i]) then
Print strings are different.
end if
end for
else
Print “Strings are Same”
end if

function concat(str1,str2)
i=length(str1)
for j←0 to str2[j]!= „\0‟ do
str1[i] ←str2[j]
i=i+1
end for
print str1

AJIET, Dept. of CSE, Mangalore 42


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 43


C Programming Lab BPOPS103

AJIET, Dept. of CSE, Mangalore 44


C Programming Lab BPOPS103

AJIET, Dept. of CSE, Mangalore 45


C Programming Lab BPOPS103

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int length(char s[100]);
void compare(char str1[100],char str2[100]);
void concat(char str1[100],char str2[100]);

int length(char s[100])


{
int i,count=0;
for(i=0;s[i]!='\0';i++)
{
count ++;
}
return count;
}

void compare(char str1[100],char str2[100])


{
int i, flag=1;
if(length(str1)!=length(str2))
flag=0;
else
{
for(i=0;str1[i]!='\0';i++)
{
if(str1[i]!=str2[i])
{
flag=0;
break;
}
}

}
if(flag==1)
printf(“Strings are equal”):

AJIET, Dept. of CSE, Mangalore 46


C Programming Lab BPOPS103

else
printf(“Strings are different”);
}

void concat(char str1[100],char str2[100])


{
int i,j;
i=length(str1);
for(j=0;str2[j]!='\0';j++)
{
str1[i]=str2[j];
i++;
}
printf("The concatenated strings is %s\n",str1);
}

void main()
{
char str1[100],str2[100];
int len1,len2;
printf("Enter the 1st string\n");
scanf("%s",str1);
printf("Enter the 2nd string\n");
scanf("%s",str2);
len1=length(str1);
len2=length(str2);
printf("The length of first string is %d\n",len1);
printf("The length of second string is %d\n",len2);
compare(str1,str2);
concat(str1,str2);
}

AJIET, Dept. of CSE, Mangalore 47


C Programming Lab BPOPS103

PROGRAM 10

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


students scoring above and below the average marks for a class of N students.

ALGORITHM:

Step 1 : Start

Step 2 : Define a Structure Student with members


usn,name,marks, Define a structure variable s

Step 3 : Read n

Step 4: for i←0 to n do

Read s[i].usn,
s[i].name,s[i].marks
sum←sum+s[i].marks

end for

Step 5 : avg←sum/n

Step 6 : Print avg

Step 7 : Print “Details of student who scored above


average marks” for i←0 to n do

if(s[i].marks>=avg)then

Print s[i].usn,s[i].name,s[i].marks

end if

end for

Step 8 : Print “Details of student who scored below


average marks” for i←0 to n do
if(s[i].marks<avg)then

Print s[i].usn,s[i].name,s[i].marks end for


Step 9 : Stop

AJIET, Dept. of CSE, Mangalore 48


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 49


C Programming Lab BPOPS103

PROGRAM:

#include<stdio.h>
struct student
{
int marks,usn;
char name[100];
};
void main()
{
struct student s[100];
int i,n;
float sum=0.0,avg=0.0;
printf("Enter the number of students\n");
scanf("%d",&n);
printf("Enter the student details\n");
printf("\n usn\t name\t marks\n");
for(i=0;i<n;i++)
{
scanf("%d%s%d",&s[i].usn,s[i].name,&s[i].marks);
sum=sum+s[i].marks;
}
avg=sum/n;
printf ("Average marks is %f",avg);
printf("Students who scored above average marks:\n");
printf("\nusn \t name \t marks \n");
for(i=0;i<n;i++)
{
if(s[i].marks>=avg)
{
printf("%d\t%s\t%d\n",s[i].usn,s[i].name,s[i].marks);
}
}
printf("\nStudents scored below average marks:\n");
printf("\n usn\t name\t marks \n");
for(i=0;i<n;i++)
{
if(s[i].marks<avg)
{
printf("%d\t%s\t%d\n",s[i].usn,s[i].name,s[i].marks);
}
}
}

AJIET, Dept. of CSE, Mangalore 50


C Programming Lab BPOPS103

EXPECTED OUTPUT:
Enter the number of students 4
Enter the student details:
usn, name, marks
7 alen 75
9 priya 85
20 sidharth 91
25 zuman 82

Average Marks is 83.250000

Students scored above average marks:


usn, name, marks
9 priya 85
20 sidharth 91

Students scored below average marks:


usn, name, marks
7 alen 75
25 zuman 82

QUESTIONS TO BE ANSWERED:

1. Define structures
Ans- Structure is a collection of members of same or different data types.

2. Give syntax to declare structure variable.


Ans-struct structure_Name variable_Name;

3. How structure elements are accessed?


Ans- We can access the members of a structure using the dot (.) operator. The dot
operator allows you to access and manipulate the individual members of a structure.

4. What is array of structure?


Ans- An array of structures in C is a data structure that allows you to create and store
multiple instances of a structure in a contiguous block of memory.

5. What are the benefits of structure?


Ans-Grouping related data, code reusability, modularity

AJIET, Dept. of CSE, Mangalore 51


C Programming Lab BPOPS103

PROGRAM 11

Develop a program using pointers to compute the sum, mean and standard
deviation of all elements stored in an array of n real numbers.

THEORY/LOGIC:

● A pointer is a variable whose value is the address of another variable, i.e.,


direct address of the memory location.

● The mean is the average and is computed as the sum of all numbers divided
by the total numbers.

● Variance measures how far a set of numbers is spread out. A variance of


zero indicates that all the values are identical. Variance is always non-
negative.

Standard deviation (SD) (σ) is a measure that is used to quantify the amount of
variation or dispersion of a set of data values. A standard deviation close to 0
indicates that the data points tend to be very close to the mean (also called the
expected value) of the set, while a high standard deviation indicates that the

data points are

● sum=1+2+3+4+5=15.00

● Mean=15.00/5=3.00

● Standard deviation=sqrt((1-3.00)2+(2-3.00)2+(3-3.00)2+(4-3.00)2+(5-
3.00)2 / 5 )=1.41

AJIET, Dept. of CSE, Mangalore 52


C Programming Lab BPOPS103

ALGORITHM:

Step 1: Start

Step 2 : Read n, *ptr

Step 3 : for i← 0 to n do

Read a[i]

end for

Step 4 : ptr←a

Step 5 : for i←0 to n do

sum←sum+ *ptr ptr←ptr+1;

end for

Step 6 : mean←sum/n

Step 7 : for i←0 to n do

sumvar←sumvar+pow( (*ptr-mean),2)

ptr←ptr+1

end for

Step 8 : var←sumvar/n

Step 9 : sd←sqrt(num)

Step 10 : Print “sum,mean,sd”

Step 11 : Stop

AJIET, Dept. of CSE, Mangalore 53


C Programming Lab BPOPS103

FLOWCHART:

AJIET, Dept. of CSE, Mangalore 54


C Programming Lab BPOPS103

PROGRAM:

#include<stdio.h>
#include<math.h>
void main()
{
float a[50],sum=0.0,sumvar=0.0,mean,var,sd;
float *ptr;
int n,i;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter %d array elements\n",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++)
{
sumvar=sumvar+(pow((*ptr-mean),2));
ptr++;
}
var=sumvar/n;
sd=sqrt(var);
printf("Sum = %f\n",sum);
printf("Mean = %f\n",mean);
printf("Standard Deviation = %f\n",sd);
}

AJIET, Dept. of CSE, Mangalore 55


C Programming Lab BPOPS103

EXPECTED OUTPUT:
gedit Lab14.c
gcc Lab14.c
./a.out
Enter the number of elements 5
Enter 5 array elements
2.1 4.2 6.3 8.4 10.5
Sum = 31.500000
Mean = 6.300000
Standard Deviation = 2.969849

QUESTIONS TO BE ANSWERED:
1. Why standard deviation is calculated for a list of N related values.
Ans- To provide insights into the spread or distribution of the data points around the
mean (average) value.

2. Define pointers in C.
Ans-Pointer is a variable that holds address of another variable.

3. How do you declare a pointer?


Ans-data_type *pointer_name;

4. What does the dereference operator (*) do in C?


Ans- Accesses the value stored at the memory address pointed by a pointer.

5. What does the NULL pointer represent in C?


Ans- A pointer with a value of zero.

AJIET, Dept. of CSE, Mangalore 56


C Programming Lab BPOPS103

PROGRAM 12

Write a C program to copy a text file to another, read both the input file name and
target file name

Program:

#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *p1, *p2;
char filename[100], c;
printf("Enter the filename to open for reading\n");
scanf("%s", filename);
p1=fopen(filename,"r");
if(p1==NULL)
{
printf("Cannot open file %s\n", filename);
exit(0);
}
printf("Enter the filename to writing\n");
scanf("%s", filename);
p2=fopen(filename,"w");
c=fgetc(p1);
while(c!=EOF)
{
fputc(c,p2);
c=fgetc(p1);

}
printf("\n File copied successfully”);
fclose(p1);
fclose(p2);
}

AJIET, Dept. of CSE, Mangalore 57


C Programming Lab BPOPS103

EXPECTED OUTPUT-
To Execute :
Gedit file.c
Gcc file.c -o file.out
. / file.out

Outputs:
Enter the file name to open for reading.
Student.txt
Cannot open file student.txt

Enter the file name to open for reading

Student.txt

Enter the file name to open for writing

output.txt

Contents copied to output.txt


QUESTIONS TO BE ANSWERED:

1. What is a file in C programming?


Ans- A named collection of data stored on a disk or other storage device.

2. Which header file is used for file operations in C?


Ans- <stdio.h>

3. How do you open a file for writing in C?


Ans- fopen("file.txt", "w");

4. What function is used to write a character to a file in C?


Ans- fputc()

5.How do you close a file in


C?Ans-fclose(file)

AJIET, Dept. of CSE, Mangalore 58


C Programming Lab BPOPS103

AJIET, Dept. of CSE, Mangalore 59

You might also like