Pps II Course File Semester II 2020 21 Final
Pps II Course File Semester II 2020 21 Final
(UGC AUTONOMOUS)
DEPARTMENT OF
FRESHMAN ENGINEERING
Prepared by :
1) Name : S.Radha 1) Name : M. Ravinder
2) Design.: Asst. Prof 2) Design.: Asst. Prof
3) Sign : 3) Sign :
4) Date : 4) Date :
2) Sign :
3) Date :
2. SYLLABUS
Programming For Problem Solving-II
Code: 20CS12001 1st year Semester–II L-2, C-2
UNIT – I
Strings – Concepts, C Strings, String Input / Output functions, string manipulation functions,
arrays of strings, string / data conversion, C program examples.
Enumerated Types–The Type Definition (typedef), Enumerated types
Structure and Union Types – Declaration, initialization, accessing structures, operations on
structures, Complex structures, Structures and functions, passing structures through pointers,
self referential structures, unions, bit fields.
UNIT – II
Linear list - Singly linked list implementation, insertion, deletion and searching operations on
linear list
UNIT – III
Sorting –selection sort, Quick sort, insertion sort techniques (Using Arrays)
Searching- linear search, binary search techniques (Using Arrays)
UNIT - IV
Stacks – Introduction, Principle, Operations: Push and Pop, In-fix to Post-Fix Conversion and
Post-Fix evaluation. (Array implementation.)
Queues - Introduction, Principle, Operations: Enqueue and Dequeue. (Arrayimplementation.)
UNIT – V
File Input and Output – Concept of a file, text files and binary files, Differences between text
and binary files, State of a file, Opening and Closing files, file input / output functions (standard
library input / output functions for files), file status functions (error handling), Positioning
functions.
TEXT BOOKS:
1. Computer Science: A Structured Programming Approach Using C, B.A.Forouzan and
R.F. Gilberg, Third Edition, Cengage Learning.
REFERENCE BOOKS:
1. The C Programming Language, B.W. Kernighan and Dennis M.Ritchie, PHI.
2. Programming in C. P. Dey and M Ghosh , Oxford University Press.
3. Programming with C, B.Gottfried, 3rd edition, Schaum‘s outlines, TMH.
4. Problem Solving and Program Design in C, J.R. Hanly and E.B. Koffman, 7th
Edition, Pearson education.
5. C & Data structures – P. Padmanabham, 3rd Edition, BS. Publications.
1. Inculcate into the students, the technical and problem solving skills to ensure their
success in their chosen profession.
2. Impart the essential skills like teamwork, lifelong learning etc. to the students which
make them globally acceptable technocrats.
3. Facilitate the students with strong fundamentals in basic sciences, mathematics and
Information Technology areas to keep pace with the growing challenges in field.
4. Enrich the faculty with knowledge in the frontiers of the Information Technology area.
1. To prepare students with excellent comprehension of mathematics, Basic Sciences and Engineering
subjects facilitating them to find gainful employment or pursue post graduate program with an
appreciation for lifelong learning.
2. To inculcate problem solving capabilities in students with analysis, design and practical skills that are
Program Specific which would facilitate them to exhibit creativity and innovation that would enable
them to develop modern equipment with emerging technologies of multidisciplinary nature for societal
development.
3. To inculcate positive attitude, professional ethics, effective communication and interpersonal skills
which would facilitate them to succeed in the chosen profession through research and development both
as team member and as well as leader.
10
PO 2: 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.
PO 3: 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.
PO 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.
PO 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.
PO 7: 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.
PO 8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO 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.
PO 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..
11
12
PSO 1: Demonstrate competency in Programming and problem-solving skills and apply those skills in
solving computing problems.
PSO 2: Select appropriate programming languages, Data structures and algorithms in combination with
modern technologies and apply them in developing innovative solutions.
PSO 3: Demonstrate an ability in using IoT devices and protocols to develop IoT based solutions for real
world problems.
.
PSO 2: An ability to use modern Electronic Design Automation (EDA) tools, software and electronic
equipment to analyze, synthesize and evaluate Electronics and Communication Engineering systems for
multidisciplinary tasks.
PSO 3: Shall interact and collaborate with stakeholders; execute quality construction works applying Civil
Engineering tools namely, Total Station, Global Positioning System (GPS), ArcGIS, AutoCAD, STAAD
and other necessary tools.
PROGRAM SPECIFIC OUTCOMES (PSO’s) - ME
PSO 1: Apply Continuity, Energy and Momentum equations to mechanical systems, design and perform
experiments in all fields of mechanical engineering
PSO 2: Able to analyze, design and develop/model mechanical and its allied systems using software tools
such as AUTOCAD, ANSYS, Creo etc.
PSO 3: Able to design layouts for process and manufacturing industry taking into consideration optimization
of resources for effective operation and maintenance.
14
Course Objectives
Develop ability to
1. Understand the concepts of string, structure union, and enumerated types
2. Understand linear lists and their implementation using arrays and linked list.
3. Understand the classical approaches to sorting arrays: selection sort, Quick sort, insertion
sort; sequential and binary searching algorithms.
4. Concepts and principles of stacks and queues and their applications.
5. Understand the basic characteristics of text, binary files and C implementation of file I/O
using streams and command line arguments.
Course Outcomes
After completion of the course, student would be able to
CO1. Implement string ,functions and use enumerated types, define and use structures, unions in
programs using C language.
CO2. Ability to implement linear lists in programs using C Language.
CO3. Write programs that sort data using selection, Quick, insertion sort techniques and perform
search mechanisms either by sequential or binary search techniques using C language
program.
CO4. 4. Concepts and principles operations of stacks and queues using C program.
CO5. Write programs that read and write text, binary files using the formatting and character I/O
functions.
8. PREREQUISITES IF ANY
15
Upon completing this course, it is expected that a student will be able to do the following:
a) Coding in C: Create and work with strings and user defined data types using
structures.
b) Sorting and Searching: To work with unstructured data and use various sorting
techniques to structure the data. Search for elements within the given data.
c) Data Structures: Understand and implement the basic data structures used in C.
d) Files: Work with files using C programming concepts.
e) Modular approach: Can divide a program into several modules and make them
work together
UNIT 1
1. Use string to give a name to a data type.
2. Declare a user-defined data type and using enumerated type.
3. Different type of string function implementation.
4. Differentiate arrays and structures, declare, initialize and access structures.
5. Implement nested structures, array of structures, and arrays within a structure using C
programming.
6. Write programs by passing structures to functions using pass by value and pass by
address.
7. Declare a self-referential structure and its applications.
8. Understand the differences and similarities of a structure and union. Write C programs
using unions.
UNIT 2
1. Differentiate arrays and linked lists.
2. Implement insertion, deletion and search of nodes in a linked list.
16
UNIT 3
1. Write a program to sort data using selection sort, quick sort, insertion sort in C
language.
2. Understand different search techniques. Implement Sequential search and binary search
technique using C language program.
UNIT 4
1. Understand and 4. Concepts and principles operations of stacks(push and pop).
2. Convert a given infix expression into prefix and postfix expressions and implement
using C program.
3. Implement the evaluation of a postfix expression using a stack in C program.
4. Understand and 4. Concepts and principles operations of queues
(enqueue,dequeue) using C program.
UNIT 5
1. Understand the basic properties and characteristics of external files, C implementation of
file I/O using streams.
2. Understand differences between text files and binary files.
3. Understand different states and modes in which files can be opened.
4. Write programs that read and write text, binary files using the formatting and character
I/O functions.
5. Write programs that handle file status questions. Write programs that process files
randomly.
6. Pass arguments to the main function from the command line and understand how a
program can be controlled from outside.
7. Understand the advantage of bit-fields and implement it using C programming.
8. Use different preprocessor commands in the C program
17
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- CSE:
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Data Structures
CO1.1 Understand the 3 2 3 2 2 2 2 2 2 -
concepts of strings, structure
union, and enumerated types.
CO4.4.Concepts and 3 2 3 2 2 2 2 2 2 -
principles operations of stacks
and queues and their
applications.
CO 5. 5. Understand 3 2 3 2 2 2 2 2 2 -
the basic characteristics of
text, binary files and C
implementation of file I/O
using streams and command
line arguments.
18
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- CSE(DS):
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Data Structures
CO1.1 Understand the 3 2 3 2 2 2 2 2 2 -
concepts of string, structure
union, and enumerated types.
CO3.Understand the 3 2 3 2 2 2 2 2 2 -
classical approaches to
sorting arrays: selection sort,
Quick sort, insertion sort;
sequential and binary
searching algorithms.
program
19
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes-
CSE(IOT:
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Data Structures
CO1. Understand the 3 2 3 2 2 2 2 2 2 -
concepts of string, structure
union, and enumerated types.
20
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes-
CSE(AI&ML):
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Data Structures
CO1.1 Understand the 3 2 3 2 2 2 2 2 2 -
concepts of string, structure
union, and enumerated types.
CO3.3. Understand 3 2 3 2 2 2 2 2 2 -
the classical approaches to
sorting arrays: selection sort,
Quick sort, insertion sort;
sequential and binary
searching algorithms.
program
21
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- CSE(CS):
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Data Structures
CO1.1 Understand the 3 2 3 2 2 2 2 2 2 -
concepts of string, structure
union, and enumerated types.
CO3.3. Understand 3 2 3 2 2 2 2 2 2 -
the classical approaches to
sorting arrays: selection sort,
Quick sort, insertion sort;
sequential and binary
searching algorithms.
program
22
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- IT:
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2
Data Structures
CO1.1 Understand the 3 2 3 2 2 2 2 2 2
concepts of string, structure
union, and enumerated types.
CO3.3. Understand 3 2 3 2 2 2 2 2 2
the classical approaches to
sorting arrays: selection sort,
Quick sort, insertion sort;
sequential and binary
searching algorithms.
program
23
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- ECE:
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2
Data Structures
CO1.Use the type definition, 3 2 3 2 2 2 2 2
enumerated types, define and
use structures, unions in
pro3.grams using C
language.
CO3.3. Understand 3 2 3 2 2 2 2 2
the classical approaches to
sorting arrays: selection sort,
Quick sort, insertion sort;
sequential and binary
searching algorithms.
program
CO4.Concepts and 3 2 3 2 2 2 2 2
principles operations of
stacks and
queues using C program
CO5.Understand the basic 3 2 3 2 2 2 2 2
characteristics of text, binary
files and C implementation of
file I/O using streams and
command line arguments.
24
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- EEE:
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Data Structures
CO1.Use the type definition, 3 2 3 2 2 2 2 2
enumerated types, define and
use structures, unions in
pro3.grams using C
language.
CO3.Understand the 3 2 3 2 2 2 2 2
classical approaches to
sorting arrays: selection sort,
Quick sort, insertion sort;
sequential and binary
searching algorithms.
program
25
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- CE:
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Data Structures
CO1.Use the type definition, 3 2 3 2 2 2 2
enumerated types, define and
use structures, unions in
pro3.grams using C
language.
CO3.3. Understand 3 2 3 2 2 2 2
the classical approaches to
sorting arrays: selection sort,
Quick sort, insertion sort;
sequential and binary
searching algorithms.
program
26
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- ME:
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Data Structures
CO1.Use the type definition, 3 2 3 2 2 2 2
enumerated types, define and
use structures, unions in
pro3.grams using C
language.
CO3.Understand the 3 2 3 2 2 2 2
classical approaches to
sorting arrays: selection sort,
Quick sort, insertion sort;
sequential and binary
searching algorithms.
program
27
LUNCH
DM
BREAK
Wednesday SD PPS-II EG
Thursday MVC BEE PPS-II Lab
Friday DM SD BEE lab
Saturday _ _
EWS Lab
Course
S.No Subject(T/P) Faculty Name
Code
1 Semiconductor Devices(SD) 20PH12001 Mr. S. Rajesham
LUNCH
BREAK
Course
S.No Subject(T/P) Faculty Name
Code
Dr. G. Neeraja Rani/ Ms. V.
Semiconductor Devices(SD)
1 20PH12001 Manjula
2 Multi Variable Calculus(MVC) 20MA12001 Dr. V. S. Triveni
Programming for Problem Solving-
Dr. L. Venkateswarlu
3 II(PPS-II) 20CS12001
4 Basic Electrical Engineering(BEE) 20EE12001 Mr. M. Prashanth Kumar
Mr. N. Rajender, Mr. N. S.
5 Engineering Graphics(EG) 20ME12002 Raghavendra
6 Discrete Mathematics(DM) 20CS12002 Ms. K. Durga Kalyani
7 Semiconductor Devices Lab(SD Lab) 20PH12L01 Ms. V. Manjula, Ms. Ch. Kalyani
Programming for Problem Solving-II
Dr. L. Venkateswarlu
8 LAB (PPS-II LAB) 20CS12L01
Basic Electrical Engineering
Mr. M. Prashanth Kumar
9 Lab(BEE LAB) 20EE12L01
10 Engineering Workshop(EWS LAB) 20ME12L01 Mr. B. Subba Rao
Ms. V. Manjula, Dr. L. Venkateswarlu, Ms.
11 Mentors K. Durga Kalyani
29
LUNCH
BREAK
SD PPS-II Lab
Wednesday PPS-II BEE EG
Thursday MVC PPS-II SD Lab
Friday SD DM EG
Saturday _ _
EWS Lab
Course
S.No Subject(T/P) Faculty Name
Code
1 Semiconductor Devices(SD) 20PH12001 Ms. Ch. Kalyani
2 Multi Variable Calculus(MVC) 20MA12001 Ms. M.P. Molimol
Programming for Problem Solving-
Mr. M. Ravinder
3 II(PPS-II) 20CS12001
4 Basic Electrical Engineering(BEE) 20EE12001 Mr. S. Poornachandar Rao
5 Engineering Graphics(EG) 20ME12002 Mr. R. Sudarshan, Mr. B. Bhasker
6 Discrete Mathematics(DM) 20CS12002 Mr. B. Mamatha
Ms. Ch. Kalyani , Mr. S.
7
Semiconductor Devices Lab(SD Lab) 20PH12L01 Rajesham
Programming for Problem Solving-II
Mr. M. Ravinder
8 LAB (PPS-II LAB) 20CS12L01
Basic Electrical Engineering Lab(BEE Mr. S. Poornachandar Rao, Mr.
9 LAB) 20EE12L01 Ch. Adithya
10 Engineering Workshop(EWS LAB) 20ME12L01 Mr. M. Ravi Kumar
Ms. M.P. Molimol, Mr. A. Ramesh, Ms. Ch.
11 Mentors Kalyani
30
LUNCH
BREAK
Course
S.No Subject(T/P) Faculty Name
Code
1 Semiconductor Devices(SD) 20PH12001 Dr. J. Shankar
2 Multi Variable Calculus(MVC) 20MA12001 Ms.S. Lalitha
Programming for Problem Solving-
Mr. M. Ravinder
3 II(PPS-II) 20CS12001
4 Basic Electrical Engineering(BEE) 20EE12001 Mr. V. Rakesh
5 Engineering Graphics(EG) 20ME12002 Ms. B. Anitha, Mr. V. Rajashekar
6 Discrete Mathematics(DM) 20CS12002 Ms. B. Mamatha
Dr. J. Shankar, Mr. A. Shiva
Semiconductor Devices Lab(SD Lab)
7 20PH12L01 Kumar
Programming for Problem Solving-II
Mr. M. Ravinder
8 LAB (PPS-II LAB) 20CS12L01
Basic Electrical Engineering
Mr. V. Rakesh
9 Lab(BEE LAB) 20EE12L01
10 Engineering Workshop(EWS LAB) 20ME12L01 Mr. P. V.R. Girish Kumar
Dr. J. Shankar, Mr. M. Ravinder, Ms. G.
11 Mentors Padma
31
LUNCH
BREAK
Wednesday SD DM EG
Thursday PPS-II SD BEE lab
Friday MVC BEE PPS-II Lab
Saturday _ _
EWS Lab
Course
S.No Subject(T/P) Faculty Name
Code
1 Semiconductor Devices(SD) 20PH12001 Dr. J. Anjaiah
Multi Variable
Dr. G. Mahesh
2 Calculus(MVC) 20MA12001
Programming for Problem
Prof. V. V. Appaji
3 Solving-II(PPS-II) 20CS12001
Basic Electrical
Ms. B. Soujanya
4 Engineering(BEE) 20EE12001
Mr. P. Sudheer Rao, Mr. R. Mahipal
5 Engineering Graphics(EG) 20ME12002 Reddy
6 Discrete Mathematics(DM) 20CS12002 Ms. K. Vandhana
Semiconductor Devices
Dr. J. Anjaiah, Dr. Mohammad Ali
7 Lab(SD Lab) 20PH12L01
Programming for Problem
Prof. V. V. Appaji
8 Solving-II LAB (PPS-II LAB) 20CS12L01
Basic Electrical Engineering
Ms. B. Soujanya
9 Lab(BEE LAB) 20EE12L01
Engineering Workshop(EWS
Mr. R. Mahipal Reddy
10 LAB) 20ME12L01
11 Mentors Dr. G. Mahesh, Prof. V. V. Appaji, Dr. J. Anjaiah
32
LUNCH
BREAK
Course
S.No Subject(T/P) Faculty Name
Code
1 Semiconductor Devices(SD) 20PH12001 Mr.A. Shiva Kumar
LUNCH
BREAK
MVC BEE PPS-II Lab
Wednesday SD PPS-II BEE lab
Thursday BEE MVC EG
Friday DM SD EG
Saturday _ _
EWS Lab
Course
S.No Subject(T/P) Faculty Name
Code
1 Semiconductor Devices(SD) 20PH12001 Dr. SK. Mohammad Ali
LUNCH
BREAK BEE
Wednesday BEE MVC SD lab
Thursday DM SD PPS-II Lab
Friday PPS-II DM EG
Saturday _ _
EWS Lab
Course
S.No Subject(T/P) Faculty Name
Code
1 Semiconductor Devices(SD) 20PH12001 Dr. B. Mamatha
2 Multi Variable Calculus(MVC) 20MA12001 Ms. P. Sailaja
Programming for Problem Solving-
Mr. M. Ajay Kumar
3 II(PPS-II) 20CS12001
4 Basic Electrical Engineering(BEE) 20EE12001 Mr. S. Hareesh Reddy
Mr. D. Ramchander, Ms. P.
5 Engineering Graphics(EG) 20ME12002 Supriya
6 Discrete Mathematics(DM) 20CS12002 Mr. K. Ambedkar
Dr. B. Mamatha, Mr. A. Shiva
7
Semiconductor Devices Lab(SD Lab) 20PH12L01 Kumar
Programming for Problem Solving-II
Mr. M. Ajay Kumar
8 LAB (PPS-II LAB) 20CS12L01
Basic Electrical Engineering Mr. S. Hareesh Reddy, Ms. B.
9 Lab(BEE LAB) 20EE12L01 Sowjanya
10 Engineering Workshop(EWS LAB) 20ME12L01 Mr. K. Praveen
Ms. P. Sailaja, Dr. B. Mamatha, Dr.Sk.
11 Mentors Nuslin Bibi
LUNCH
BREAK
MVC DM
Wednesday BEE SD PPS-II Lab
Thursday DM MVC BEE Lab
Friday BEE PPS-II SD Lab
Saturday _ _ _
Course
S.No Subject(T/P) Faculty Name
Code
1 Semiconductor Devices(SD) 20PH12001 Dr. P. Raju
2 Multi Variable Calculus(MVC) 20MA12001 Dr. Mahesh
Programming for Problem Solving-
Ms.Fathima
3 II(PPS-II) 20CS12001
4 Basic Electrical Engineering(BEE) 20EE12001 Mr. K. Jayakar Babu
5 Engineering Graphics(EG) 20ME12002 Mr.G. Raju, Mr. G. Sampath
6 Discrete Mathematics(DM) 20CS12002 Ms. K. Vandhana
Dr.B. Mamatha, Ms. Ch.
Semiconductor Devices Lab(SD Lab)
7 20PH12L01 Kalyani
Programming for Problem Solving-II
Ms.Fathima
8 LAB (PPS-II LAB) 20CS12L01
Basic Electrical Engineering Lab(BEE Mr. K. Jayakar Babu, Mr. S.
9 LAB) 20EE12L01 Hareesh Reddy
10 Mentors Ms.Fathima, Dr. P. Raju, Mr. K. Nagaraju
LUNCH
BREAK
Saturday _ _ _
Course
S.No Subject Code Faculty Name
1 English(Eng) 20EN12001 Mr. V. Ramaiah Chary
2 Multi Variable Calculus(MVC) 20MA12001 Dr. N. Subhadra/Dr. Triveni
Programming for Problem Solving-
Ms. Keerthi
3 II(PPS-II) 20CS12001
4 Engineering Chemistry(EC) 20CH12001 Mr. K. Satheesh
Semiconductor Devices and
5 Circuits(SDC) 20EC12001 Mr. U.Appala Raju
English Language Communication Skills
6 Lab(ELCS LAB) 20EN12L01 Mr. V. Ramaiah Chary
Programming for Problem Solving-II
Ms. Keerthi
7 Lab (PPS-II LAB) 20CS12L01
Mr. K. Satheesh, Ms. J. Bhargavi
8 Engineering Chemistry Lab(EC Lab) 20CH12L01 Lakshmi
Semiconductor Devices and Circuits
9 Lab(SDC LAB) 20EC12L01 Mr. U.Appala Raju, Ms. M. Laxmi
Mr. V. Ramaiah Chary, Mr. K. Satheesh, Ms. J.
10 Mentors Bhargavi Lakshmi
LUNCH
Wednesday PPS-II BREAK EC ELCS LAB
Saturday _ _ _
Course
S.No Subject Code Faculty Name
1 English(Eng) 20EN12001 Dr. B. Nagamani
2 Multi Variable Calculus(MVC) 20MA12001 Dr. N. Subhadra
Programming for Problem Solving-
3 II(PPS-II) 20CS12001 Dr. Puja Prasad
4 Engineering Chemistry(EC) 20CH12001 Dr. J.V. Madhuri
Semiconductor Devices and
5 Circuits(SDC) 20EC12001 Ms. J. Mrudula
English Language Communication Skills
6 Lab(ELCS LAB) 20EN12L01 Dr. B. Nagamani
Programming for Problem Solving-II
7 Lab (PPS-II LAB) 20CS12L01 Dr. Puja Prasad
8 Engineering Chemistry Lab(EC Lab) 20CH12L01 Dr. J.V. Madhuri, Mr. K. Satheesh
Semiconductor Devices and Circuits
9 Lab(SDC LAB) 20EC12L01 Ms. J.Mrudula, Mr. Prasad
Dr. J.V. Madhuri, Dr. B. Nagamani, Dr. Puja
10 Mentors Prasad
38
LUNCH
BREAK
Wednesday EC ENG SDC LAB
Saturday _ _ _
Course
S.No Subject Code Faculty Name
1 English(Eng) 20EN12001 Dr. M. Upender
2 Multi Variable Calculus(MVC) 20MA12001 Ms. M. P.Molimol
Programming for Problem Solving-
3 II(PPS-II) 20CS12001 Ms.S. Radha
4 Engineering Chemistry(EC) 20CH12001 Dr.Anurag Gautam
Semiconductor Devices and
5 Circuits(SDC) 20EC12001 Ms.M.Laxmi
English Language Communication
6 Skills Lab(ELCS LAB) 20EN12L01 Dr. M. Upender
Programming for Problem Solving-II
7 Lab(PPS-II LAB) 20CS12L01 Ms. S. Radha
Dr.Anurag Gautam, Dr. K.
8 Engineering Chemistry Lab(EC Lab) 20CH12L01 Shashikala
Semiconductor Devices and Circuits
9 Lab(SDC LAB) 20EC12L01 Ms.M.Laxmi, Ms. M. Umarani
Dr. M. Upender, Dr.Anurag Gautam, Ms.S.
10 Mentors Radha
39
LUNCH
Tuesday SDC BREAKMVC EC
Wednesday ENG SDC PPS-II LAB
Thursday EC ENG SDC LAB
Friday MVC PPS-II EC LAB
Saturday _ _ _
Course
S.No Subject Code Faculty Name
1 English(Eng) 20EN12001 Mr. Y. Anil
2 Multi Variable Calculus(MVC) 20MA12001 Ms. P. Sailaja
Programming for Problem
3 Solving-II(PPS-II) 20CS12001 Ms. S. Radha
4 Engineering Chemistry(EC) 20CH12001 Dr. R. Sanjeev
Semiconductor Devices and
5 Circuits(SDC) 20EC12001 Mr. Prasad
English Language
Communication Skills
6 Lab(ELCS LAB) 20EN12L01 Mr. Y. Anil
Programming for Problem
7 Solving-II Lab (PPS-II LAB) 20CS12L01 Ms. S. Radha
Engineering Chemistry Lab(EC
8 Lab) 20CH12L01 Dr. R. Sanjeev, Dr. P. Sreedhar
Semiconductor Devices and
9 Circuits Lab(SDC LAB) 20EC12L01 Mr. Prasad, Dr. S. Vallisree
10 Mentors Mr. Y. Anil, Dr. R. Sanjeev, Ms.K. Swarupa
40
LUNCH
BREAK
Wednesda
EC MVC CM LAB
y
Thursday PPS-II SDC EC LAB
Friday CM SDC PPS-II LAB
Saturday _ _ _
Course
S.No Subject Code Faculty Name
1 Multi Variable Calculus(MVC) 20MA12002 Dr. Sk. Nuslin Bibi
2 Computational Mathematics(CM) 20MA12002 Dr. K.. Venkateswarlu
3 Engineering Chemistry(EC) 20CH12001 Dr. K. Shashikala
Programming for Problem Solving-
4 II(PPS-II) 20CS12001 Ms.S. Sudha
Semiconductor Devices and
5 Circuits(SDC) 20EC12001 Ms.M.Umarani
Computational Mathematics 20MA12L0
6 Lab(CM LAB) 1 Dr. K. Venkateswarlu
Dr. K. Shashikala, Dr. Anurag
7 Engineering Chemistry Lab(EC Lab) 20CH12L01 Gautam
Programming for Problem Solving-II
8 Lab(PPS-II LAB) 20CS12L01 Ms.S. Sudha
Semiconductor Devices and Circuits
9 Lab(SDC LAB) 20EC12L01 Ms.M.Umarani, Dr. S. Vallisree
10 Mentors Dr, K, Shashikala, Ms. S. Sudha
LUNCH
BREAK
Wednesday PPS-II E.GEO EC LAB
Thursday EC E.GEO ELCS LAB
Friday MVC ENG E. GEO LAB
Saturday _ _ _
Course
S.No Subject Code Faculty Name
1 English (Eng) 20EN12001 Ms. P. Mercy Kavitha
2 Multi Variable Calculus(MVC) 20MA12002 Dr. Sk. Nuslin Bibi
Programming for Problem Solving-
3 II(PPS-II) 20CS12001 Ms.Fathima
4 Engineering Chemistry(EC) 20CH12001 Dr. P. Sreedhar
5 Engineering Geology(E.Geo) 20CE12001 Dr. N. Mahendra
English Language Communication
6 Skills Lab( ELCS LAB) 20EN12L01 Ms. P. Mercy Kavitha
Programming for Problem Solving-II
7 Lab (PPS-II LAB) 20CS12L01 Ms.Fathima
8 Engineering Chemistry Lab(EC Lab) 20CH12L01 Dr. P. Sreedhar, Dr. R. Sanjeev
Design
9 Thinking(DT) 20CE12001 Ms. M. Priyanka
Engineering Geology
Lab (E.Geo Lab) 20CE12001 Dr. N. Mahendra
10
Ms. P. Mercy Kavitha, Dr. P. Sreedhar, Ms. M.
11 Mentors Priyanka
42
LUNCH
BREAK
Wednesday ENG DT PPS-II LAB
Thursday EC MMD DT
Friday PPS-II MVC EC LAB
Saturday _ _ _
Course
S.No Subject Code Faculty Name
1 English (Eng) 20EN12001 Ms. B. Vanaja Rani
2 Multi Variable Calculus(MVC) 20MA12002 Mr. K. Nagaraju
Programming for Problem Solving-
3 II(PPS-II) 20CS12001 Ms. S. Sudha
4 Engineering Chemistry(EC) 20CH12001 Ms. J. Bhargavi Lakshmi
Mechanics and Mechanical
5 Drives(MMD) 20ME12001 Mr. N. S. Raghavendra
English Language Communication
6 Skills Lab( ELCS LAB) 20EN12L01 Ms. B. Vanaja Rani
Programming for Problem Solving-II
7 Lab (PPS-II LAB) 20CS12L01 Ms. S. Sudha
Ms. J. Bhargavi Lakshmi, Dr. J. V.
8 Engineering Chemistry Lab(EC Lab) 20CH12L01 Madhuri
Design
9 Thinking(DT) 20ME12P01 Ms. V. Sandeepa
10 Mentors Mr. P. Sudheer Rao, Mr. R. Mahipal Reddy
LUNCH
BREAK
Tue ECE-B
Wed ECE-B
Thu
Fri ECE-B Laab
Sat _
LUNCH
BREAK
Tue
Wed ECE-D
Thu ECE-C
Fri ECE-C ECE-D
Sat _
LUNCH
BREAK
Wed CSE-B
Thu
Fri CSE-B
Sat _
Tue EEE
Wed ME
Thu EEE
Fri ME EEE
Sat _
Period 1 2 3
Mon ECE-A Lab
LUNCH
BREAK
Tue CSE-A ECE-A
Wed CSE-A
Thu ECE-A CSE-A Lab
Fri
Sat _
LUNCH
BREAK
Tue CSE-CS
Wed CSE-CS
Thu CSE-IoT
Fri CSE-IoT CSE-CS
Sat _
LUNCH
BREAK
Tue CE
Wed CE IT
Thu IT
Fri
Sat _
Prof. Appaji
PPS II
(AIML,DS)
45
LUNCH
BREAK
CSE-DS
Wed CSE-AIML
Thu CSE-DS
Fri CSE-DS
Sat _
Instructional learning
Period outcomes Students should be Mode of Remark
No. Topic to be covered able to BTL Date teaching s
UNIT I: Use string definition to give BB
C String a name to a data type
1 Concepts ,Input L1
output functions
Declare a user-defined data type BB
2 String manipulation and using enumerated type L2
function,string
conversion
Introduction to Differentiate union and BB
Structures, Structure structures, declare, initialize and
Initialization, access structures
Enumerated Types
3 Declaration and L2
Accessing
Implement nested structures, OHP/BB
Operations on array of structures, and arrays
Structures, Complex within a structure using C
4 Structures programming L3
Write programs by passing OHP/BB
Structures and structures to functions using
5 Functions pass by value L3,L4
Write programs by passing OHP/BB
Structures and structures to functions using
6 Functions pass by value L3,L4
Write programs by passing OHP/BB
Passing Structures structures to functions using
7 through pointers pass by address L3,L4
Self Referential Declare a self-referential OHP/BB
8 Structures structure and its applications L2
Understand the differences and OHP/BB
similarities of a structure and
union. Write C programs using
9 Unions unions. L2,L3
Understand the differences and OHP/BB
similarities of a structure and
union. Write C programs using
10 Unions unions. L2,L4
Understand the advantage of LCD/BB
bit-fields and implement it using
11 Bit Fields C programming L2,L3
UNIT II : LCD/BB
47
48
49
50
UNIT – I
Strings:
A string is a one dimensional array of characters terminated by a null character(\0).A string constant in C can be
represented by enclosing its characters with double quotes without a null character.
Strings are classified as
1.Fixed length strings:
2. Variable length strings:
Fixed length
• Reserves the fixed amount of memory for the string variable
• Disadvantages
Ex:
Char a[10]=“hello”; // waste memory
Variable length
• Size of storage can be expanded and compressed to accommodate the data
• There are two common techniques to use length-controlled strings and delimited strings
a. Length controlled string add a count that specifies the number of characters in the string. This count is used by
the string manipulation functions to determine the actual length of data.
7 T E S T I N G
b. Delimited Strings: C strings are delimited using the ASCII null character(\0).
51
S T R I N G \0
Difference between one character in memory and one-character string . The character requires only one
memory location, but a one character string requires two memory locations :one for data and one for the delimiter.
Char ‘H’ String “H” Empty string” “
H H \O \O
Difference between string and character array O O
String S T R I N G \0
Character array S T R I N G
Because strings are variable in length , the null character is used as an end-of-string
marker. Enough room must be provided to store the maximum length string , plus one for delimiter.
String literals
A string literal also known as string constant is a sequence of characters enclosed in double quotes.
Ex: “Hello”
“ C is a high level language”
C automatically creates an array of characters ,initializes it to a null-delimited string, and stores it, remembering
its address.
Referencing String Literals
A string literal is stored in memory. We can refer to it using pointers.
#include<stdio.h>
int main()
{
printf(“%c”,”HELLO”[1]);
return 0;
}
Output
E
“Hello”[0] “Hello”[1] “Hello”[2] “Hello”[3] “Hello”[4] “Hello”[5]
52
H E L L O \0
String Declaration
Syntax: char string_name[size];
Example: char student_name[20];
Whenever we declare a String, it will contain garbage values inside it. We have to initialize String or Character
array before using it. Process of assigning some legal default data to String is Called Initialization of String.
There are different ways of initializing String in C Programming –
1. Initializing Unsized Array of Character
2. Initializing String Directly
3. Initializing String Using Character Pointer
1. Unsized Array : Array Length is not specified while initializing character array using this approach
2. Array length is Automatically calculated by Compiler
3. Individual Characters are written inside Single Quotes , Separated by comma to form a list of characters.
Complete list is wrapped inside Pair of Curly braces
4. Please Note : NULL Character should be written in the list because it is ending or terminating character in the
String/Character Array
1. In this method we are directly assigning String to variable by writing text in double quotes.
2. In this type of initialization, we don’t need to put NULL or Ending / Terminating character at the end of
string. It is appended automatically by the compiler.
1. Declare Character variable of pointer type so that it can hold the base address of “String”
2. Base address means address of first array element i.e (address of name[0] )
3. NULL Character is appended Automatically
53
name
1. scanf(): In C Programming we can use scanf function from stdio.h header file to read string. scanf function is
commonly used for accepting string.
Syntax:
scanf("%s",Name_Of_String_Variable);
Example
#include<stdio.h>
int main()
{
char name[20];
printf("\nEnter the Name : ");
scanf("%s",name);
printf("Name of the Company : %s",name);
return(0);
}
The scanf( ) function can have a scanset, which defines a set of characters to be read by the scanf().
For example, the following scanset tells scanf( ) to read only the characters X, Y, and Z:
%[XYZ]
When using a scanset, scanf( ) continues to read characters until it encounters a character outside the scanset.
To specify an inverted set, append ^ in front of the set. ^ tells scanf( ) to read characters that are not in the
scanset.
To specify a range in the scan set, use a hyphen. For example, this tells scanf( ) to accept the characters A
through Z:
%[A-Z]
The scanset is case sensitive. To scan for both upper- and lowercase letters, you must specify them
individually.
#include <stdio.h>
int main(void)
{
int i;// ww w.j av a 2 s . c o m
char str[80], str2[80];
return 0;
}
Result
scanf(”%81[^\n]”,line); //scanf reads until it finds the newline and then stops.
2.getchar()
getchar() function is also one of the function which is used to accept the single character from the user.
Syntax
char ch = getchar();
Example
#include<stdio.h>
main()
{
char ch[10],c,i=0;
while((c = getchar())!=’\n’)
{
ch[i]=c;
i++;
}
ch[i]=’\0’;
printf("Accepted string : %s",ch);
}
Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or
the end-of-file is reached.
Syntax
Function Declaration
The gets function takes a line(terminated by a newline) from the input stream and makes a null-terminated string
out of it. The newline is converted to end-of-string character(\0).
56
Example
#include<stdio.h>
void main()
{
char name[20];
printf("\nEnter the Name : ");
gets(name);
printf(“%s”,name);
}
C Language supports 3 output functions are there to read a string. They are
1. printf():
Syntax
printf (" Type your Message / Instruction " ) ;
and
57
Example
Justification flag(-) is used to left justify the output. It is used only when a width is also specified, and the length
of the string is less than the specified width(minimum width).
printf(“|%-30s|\n”,”This is a string”);
Output:
|This is a string |
2.putchar():
putchar() is used to print one character at a time. To print more than one character, write the putchar() in loop.
Syntax
putchar (char variable name);
Example
#include< stdio.h>
void main()
{
char string[]="This is an example string\n";
int i=0;
while(string[i]!='\0')
58
{
putchar(string[i]);
i++;
}
}
3.puts()/fputs()
puts() is used to print multiple characters including white spaces at a time. It takes a null-terminated string form
the memory and writes it to a file or the monitor. The null character is replaced by a newline.
Declaration Syntax
int puts(const char* strptr);
Example
#include< stdio.h>
void main()
{
char string[] = "This is an example string\n";
puts(string); // String is variable Here
puts("String"); // String is in Double Quotes
}
Output:
This is an example string
String
C – String functions
Syntax:
size_t strlen(const char *str)
size_t represents unsigned short
It returns the length of the string without including end character (terminating char ‘\0’).
Example of strlen:
60
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Geethanjali";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:
strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns the total allocated size
assigned to the array. So if I consider the above example again then the following statements would return the
below values.
strlen(str1) returned value 11.
sizeof(str1) would return value 20 as the array size is 20 (see the first statement in main function).
Syntax:
#include <stdio.h>
#include <string.h>
int main()
61
{
char str1[20] = " Geethanjali";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1,
30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1,
10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 11
Length of string str1 when maxlen is 10: 10
Have you noticed the output of second printf statement, even though the string length was 11 it returned only
10 because the maxlen was 10.
It compares the two strings and returns an integer value. If both the strings are same (equal) then this function
would return 0 otherwise it may return a negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 >
string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
62
Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = " Geethanjali";
char s2[20] = " Geethanjali College ";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
63
Example of
strncmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = " Geethanjali";
char s2[20] = " Geethanjali College";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of
strcat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
65
Example of strncat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:
Example of strcpy:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna be copied into s1";
66
Example of strncpy:
#include <stdio.h>
67
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:
68
It searches string str for character ch (you may be wondering that in above definition I have given data type of
ch as int, don’t worry I didn’t make any mistake it should be int only. The thing is when we give any
character while using strchr then it internally gets converted into integer for better searching.
Example of
strchr:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:
f function strchr
69
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strrchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:
function strrchr
Why output is different than strchr? It is because it started searching from the end of the string and found
the first ‘f’ in function instead of ‘of’.
Example of strstr:
70
#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C at Geethanjali";
printf ("Output string is: %s", strstr(inputstr, 'Geetha'));
return 0;
}
Output:
#include<stdio.h>
#include<string.h>
int main()
{
char str[]=”CONCATENATION”;
int len;
71
len=strspn(s1,”AEIOUCN”);
printf(“%d”,len);
return 0;
}
Output:
5
b. Complemented String Span: This is a string complement span; its functions stops at the first character that
matches one of the characters in the set. If none of the characters in the string match the set, they return the
length of the string.
72
#include <stdio.h>
#include <string.h>
int main ()
{
char string[50] ="Test,string1,Test,string2:Test:string3";
char *p;
printf ("String \"%s\" is split into tokens:\n",string);
p = strtok (string,",:");
while (p!= NULL)
{
printf ("%s\n",p);
p = strtok (NULL, ",:");
}
return 0;
}
OUTPUT:
String “Test,string1,Test,string2:Test:string3” is split into tokens:
Test
string1
Test
string2
Test
string3
String to Number:
These functions are available in stdlib.h library.
The C library function long int strtol(const char *str, char **endptr, int base) converts the initial part of the
73
string in str to a long int value according to the given base, which must be between 2 and 35 inclusive, or be
the special value 0 It stops with the first non-numeric character, which is considered to be the start of a
trailing string. The address of the trailing string is stored in the second parameter, unless it is a null pointer. A
third parameter determines the base of the string number.
Declaration
Following is the declaration for strtol() function.
long int strtol(const char *str, char **endptr, int base);
Parameters
str − This is the string containing the representation of an integral number.
endptr − This is the reference to an object of type char*, whose value is set by the function to the next
character in str after the numerical value.
base − This is the base, which must be between 2 and 35 inclusive, or be the special value 0.
The letters a.....z or A......Z represent the values 10.....35.Only the numeric and alphabetic characters
less than the base are permitted in any string.
If the base is 0, the format is determined by the string as follows:
a. If the number begins with 0x or oX, the number is a hexadecimal constant.
b. If the first digit is 0 and the second digit is not x or X , the number is an octal constant.
c. If the first digit is a nonzero, the number is a decimal constant.
Return Value
This function returns the converted integral number as a long int value, else zero value is returned if the string
does not begin with a valid number and the trailing string pointer is set to the beginning of the string.
Example
The following example shows the usage of strtol() function.
Ex1:
#include <stdio.h>
#include <stdlib.h>
int main () {
char str[30] = "2030300 This is test";
char *ptr;
long ret;
ret = strtol(str, &ptr, 10);
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);
return(0);
}
The number(unsigned long integer) is 2030300
String part is | This is test|
Ex2:
#include <stdio.h>
#include <stdlib.h>
int main () {
long num;
char *ptr;
num = strtol(“12345 Decimal constant:”, &ptr, 0);
printf("%s %ld\n",ptr,num);
num = strtol(“11001 Binary constant:”, &ptr, 2);
printf("%s %ld\n",ptr,num);
num = strtol(“13572 Octal constant:”, &ptr, 8);
printf("%s %ld\n",ptr,num);
74
75
void main()
{
char *str=”834.41”;
printf(“string=%s\n\n integer data value=%d\n\n float data value=%.2f”,str,atoi(str),atof(str));
}
Output:
String=834.41
Integer data value=834
Float data value=834.41
String/Data Conversion
Description
sscanf() function is a file handling function in C programming language which is used to read formatted input
from a string/buffer.
The C library function int sscanf(const char *str, const char *format, ...) reads formatted input from a string.
Declaration
Following is the declaration for sscanf() function.
76
1 *
This is an optional starting asterisk, which indicates that the data is
to be read from the stream but ignored, i.e. it is not stored in the
corresponding argument.
2 width
This specifies the maximum number of characters to be read in the
current reading operation.
3 modifiers
Specifies a size different from int (in the case of d, i and n), unsigned
int (in the case of o, u and x) or float (in the case of e, f and g) for
the data pointed by the corresponding additional argument: h : short
int (for d, i and n), or unsigned short int (for o, u and x) l : long int
(for d, i and n), or unsigned long int (for o, u and x), or double (for
e, f and g) L : long double (for e, f and g)
4 type
A character specifying the type of data to be read and how it is
expected to be read.
Data/String Conversion
sprintf() function is a file handling function in C programming language which is used to write formatted output
77
to the string.
File
operation Declaration & Description
where,
string – buffer to put the data in.
value – int variable, c – char variable and flt – float variable.
There are for example only. You can use any specifiers.
sprintf()
#include <stdio.h>
#include <string.h>
int main( )
{
int value = 50 ;
float flt = 7.25 ;
char c = 'Z' ;
char string[40] = {‘\0’} ;
printf ( "int value = %d \n char value = %c \n " \
"float value = %f", value, c, flt ) ;
78
Topic:Arrays of strings
An array of strings is a special form of a two-dimensional array. • The size of the left index determines the number
of strings. • The size of the right index specifies the maximum length of each string. For example, the following
declares an array of 30 strings, each having a maximum length of 80 characters (with one extra character for the
null terminator): Arrays of strings are commonly used for handling tables of information.
Two Dimensional Array Of Strings
It is also referred as table of strings. This can be initialized as follows:
type variable-name[][];
• char a[10][10]; // declaration of 2-D array
The first subscript gives the number of names in the array.The second subscript gives the length of each
item of the array.
Example:
char list[6][10]={ “akshay”, “parag”,“raman”,“srinivas”, “gopal”,“rajesh”};
The names would be stored in the memory as shown in the below figure
Example: Two dimensional arrays of strings
79
C program to read N names, store them in the form of an array and sort them in alphabetical order. Out
put the given names and the sorted names in two columns side by side.
#include <stdio.h>
#include <string.h>
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("\n----------------------------------------\n");
printf("Input NamestSorted names\n");
printf("------------------------------------------\n");
for(i =0; i < n; i++)
{
printf("%s\t\t%s\n", tname[i], name[i]);
}
printf("------------------------------------------\n");
}
C program examples.
#include<stdio.h>
int main()
{
char name[30], ch;
int i =0;
printf("Enter name: ");
while(ch !='\n')// terminates if user hit enter
{
ch= getchar();
name[i]= ch;
i++;
}
name[i]='\0';// inserting null character at end
81
return0;
#include <stdio.h>
#include <ctype.h>
void main()
{
char sentence[100];
int count, ch, i;
printf("Enter a sentence \n");
for(i =0;(sentence[i]=getchar())!='\n'; i++)
sentence[i]='\0';
/* shows the number of chars accepted in a sentence */
count = i;
printf("The given sentence is : %s", sentence);
printf("\n Case changed sentence is: ");
for(i =0; i < count; i++)
{
ch=islower(sentence[i])?toupper(sentence[i]):
tolower(sentence[i]);
putchar(ch);
}
}
3. C program to count the number of vowels, consonants
#include<stdio.h>
int main()
{
char line[150];
int i, vowels, consonants, digits, spaces;
82
for(i=0; line[i]!='\0';++i)
{
if(line[i]=='a'|| line[i]=='e'|| line[i]=='i'||
line[i]=='o'|| line[i]=='u'|| line[i]=='A'||
line[i]=='E'|| line[i]=='I'|| line[i]=='O'||
line[i]=='U')
{
++vowels;
}
elseif((line[i]>='a'&& line[i]<='z')||(line[i]>='A'&& line[i]<='Z'))
{
++consonants;
}
elseif(line[i]>='0'&& line[i]<='9')
{
++digits;
}
elseif(line[i]==' ')
{
++spaces;
}
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);
return0;
}
#include<stdio.h>
83
int main()
{
char s[1000], i;
#include<stdio.h>
int main()
{
char s1[100], s2[100], i;
84
Typedef
The typedef is an advance feature in C language which allows us to create an alias or new
name for an existing type or user defined type.
• typedef: It is a keyword.
• data_type: It is the name of any existing type or user defined type created using
structure/union.
• new_name: alias or new name you want to give to any existing type or user defined
type.
85
Enumerated types(enum)
enum is a user defined enumerated data type supported by ANSI C.
Syntax:
enum identifier {value1,value2,….value n};
The identifier is a user defined enumerated data type which can be used to declare variables
that can have one of the values enclosed within the braces. After this definition we can declare
variables of new type as
enum identifier v1,v2,….vn;
The enumerated variables v1,v2,….vn can only have only one of the values
value1,value2,…valuen.
v1=value3;
v5=value1;
Example:
enum day {Monday,Tuesday,….Sunday};
enum day week_st,week_end;
week_st=Monday;
week_end=Friday;
If(week_st==Tuesday)
week_end=Saturday;
86
C provides the enum construction for the special case where you want to have a sequence of
named constants of type int, but you don‘t care what their actual values are, as in
enum color { RED, BLUE, GREEN, MAUVE, TURQUOISE };
This will assign the value 0 to RED, 1 to BLUE, and so on. These values are effectively of type
int, although you can declare variables, arguments, and return values as type enum color to
indicate their intended interpretation.
Despite declaring a variable enum color c (say), the compiler will still allow c to hold arbitrary
values of type int.
So the following code works just fine:
#include<stdio.h>
#include<stdlib.h>
enum foo { FOO };
enum apple { MACINTOSH, CORTLAND, RED_DELICIOUS };
enum orange { NAVEL, CLEMENTINE, TANGERINE };
int main(int argc, char **argv)
{
enum foo x;
if(argc != 1)
{
printf( "Usage: %s\n", argv[0]);
return 1;
}
printf("FOO = %d\n", FOO);
printf("sizeof(enum foo) = %d\n", sizeof(enum foo));
x = 127;
printf("x = %d\n", x); /* note we can add apples and oranges */
printf("%d\n", RED_DELICIOUS + TANGERINE);
return 0;
}
Specifying particular values
It is also possible to specify particular values for particular enumerated constants, as in
enum color { RED = 37, BLUE = 12, GREEN = 66, MAUVE = 5, TURQUOISE };
87
Anything that doesn‘t get a value starts with one plus the previous value; so the above definition
would set TURQUOISE to 6. This may result in two names mapping to the same value.
In practice, enums are seldom used, and we will more commonly see a stack of #defines:
#define RED (0)
#define BLUE (1)
#define GREEN (2)
#define MAUVE (3)
#define TURQUOISE (4)
The reason for this is partly historical—enum arrived late in the evolution of C—but partly
practical: a table of #defines makes it much easier to figure out which color is represented by
3, without having to count through a list. But if you never plan to use the numerical values,
enum may be a better choice, because it guarantees that all the values will be distinct.
A structure is a user defined data type. Structure is a collection of different data types
referenced under one name, which keeps related information together. The variables which
make up a structure are called structure elements.
Structure Declaration
struct addr
{
char name[30];
char street[40];
int postalcode;
};
Tagged Structure:
Variables may also be declared as the structure is defined. This can be done as follows:
88
struct addr
{
char name[30];
char street[40];
int postalcode;
} addr_info, binfo, cinfo;
Structure Variable
The structure tag is not needed, if only one variable is declared for example:
struct
{
char name[30];
char street[40];
int postalcode;
} addr_info;
Tagged Structure
struct book
{
char title[20];
char publisher[20];
char author[20];
int year;
int pages;
};
typedef struct book Book;
After this declaration, Book is an alias of struct book. So instead of using struct book to
declare new structure variables we can use just use Book.
Book b1 = {"The Alchemist", "TDM Publication" , "Paulo Coelho", "1978", 331 };
89
char title[20];
char publisher[20];
char author[20];
int year;
int pages;
} Book;
Initialization
name=XYZ
street=Paradise
postalcode=500056
Accessing Structures
The only operation that can be applied to struct variable is assignment. If a and b are structure
variables and if both of them consist of same member name then one variables member value
can be copied to another variables member.
Complex structures
A Structure can be defined to be a group of logically related data items, which may be of
different types, stored in contiguous memory locations, sharing a common name, but
distinguished by its member. So far structures used built-in data types char, int, float, etc. Let
us now explore the possibility of making a group of data items of user-defined types also.
struct date
{
-
-
-
};
struct student
{
-
-
-
struct date doa;
};
90
Nested Structure
Nested structure in C is nothing but structure within structure. One structure can be declared
inside other structure as we declare structure members inside a structure.
The structure variables can be a normal structure variable or a pointer variable to access the
data. You can learn below concepts in this section.
1.Structure within structure in C using normal variable
2.Structure within structure in C using pointer variable
#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,"Osmania University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n", stu_data.clg_data.college_id);
printf(" College Name is: %s \n", stu_data.clg_data.college_name);
return 0;
}
Output
91
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Osmania University
#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data, *stu_data_ptr;
int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,"Osmania University"};
stu_data_ptr = &stu_data;
printf(" Id is: %d \n", stu_data_ptr->id);
printf(" Name is: %s \n", stu_data_ptr->name);
printf(" Percentage is: %f \n\n", stu_data_ptr->percentage);
printf(" College Id is: %d \n", stu_data_ptr->percentage);
printf(" College Name is: %s \n", stu_data_ptr->clg_data.college_name);
return 0;
}
Output
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Osmania University
92
For structures to be fully useful, we should pass them to functions and return them.
In order to refer the individual members for Actual parameters, we must use the direct
selection operator (.) to refer the individual members of the structure.
struct fraction
{
int nr,dr;
…….
……..
};
main()
{
struct fraction fr1,fr2,res;
………
……….
res.nr=multiply(fr1.nr,fr2.nr);
res.dr=multiply(fr1.dr,fr2.dr);
}
multiply(int x,int y)
{
return x*y;
}
Example:
#include<stdio.h>
/*
structure is defined above all functions so it is global.
*/
struct student
{
char name[20];
int roll_no;
int marks;
};
93
int main()
{
struct student stu = {"Tim", 1, 78};
print_struct(stu.name, stu.roll_no, stu.marks);
return 0;
}
Passing the whole structure is a much better solution to complete the job in one call. since
structure is a type , we simply specify the type in formal parameters of the called function.
Similarly the function can return the structure. It is necessary to specify the structure as return
type.
struct student
{
int sno;
float per;
};
Main()
{
struct student s1;
………
……….
Display(s1);
}
Display(struct student a);
{
…….
…….
}
Example:
#include<stdio.h>
/*
structure is defined above all functions so it is global.
*/
struct student
94
{
char name[20];
int roll_no;
int marks;
};
int main()
{
struct student stu = {"George", 10, 69};
print_struct(stu);
return 0;
}
Pointer variable holds the address of other variables of basic data types such as integer,
float, character etc.
A pointer also holds the address of structure variables. Pointers along with structures are used
to make linked list, binary trees etc. Following declaration shows the pointer as an object of a
structure.
struct data
{
char name[30];
---
---
};
struct data *p1;
*p1 is a pointer variable which holds the address of the structure named data. Pointer is declared
as any object of a structure. Pointer structure variable can be accessed and processed by two
methods.
• (*p1).fieldname=variable
• p1->fieldname=variable
Example
#include<stdio.h>
95
/*
structure is defined above all functions so it is global.
*/
struct employee
{
char name[20];
int age;
char doj[10]; // date of joining
char designation[20];
};
int main()
{
struct employee dev = {"Jane", 25, "25/2/2015", "Developer"};
print_struct(&dev);
return 0;
}
A self referential structure creates data structures like linked lists, stacks, etc.
Following is an example :
struct tag_name
{
datatype datatypename;
struct tag_name * pointer_name;
};
A self-referential structure is one which refers to another structure of same type. For example,
a linked list is a self-referential data structure in which next node of a node is being pointed to
same struct type. For example,
struct list_node
96
{
int data;
struct list_node *next;
} linked_list;
In the above example, the list_node is a self-referential structure – because the *next is of the
type struct list_node.
Example
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Intialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
30
40
97
UNIONS
Unions are similar to structures and have same syntax as structures. But the difference
between them is in terms of storage. Structure members have their its own storage locations,
whereas all members of union use the same location. That is, union can handle only one
member at a time and that depends on highest size. Union can be declared sing the keyword
union
Declaring Union
union union-name
{
data_type var-name;
data_type var-name;
};
Example:
union student
{
int id;
float marks;
}code;
This declares a variable code of type union item. Union contains three members. For
accessing a union member, we use the same syntax that we use for structure variables.
98
The union tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the union's
definition, before the final semicolon, you can specify one or more union variables but it is
optional. Here is the way you would define a union type named Data which has the three
members i, f, and str. Now, a variable of Data type can store an integer, a floating-point
number, or a string of characters. This means that a single variable ie., same memory location
can be used to store multiple types of data. You can use any built-in or user defined data
types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in the example Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by character string.
Dot operator can be used to access a member of the union . The member access operator is
coded as a period between the union variable name and the union member that we wish to
access. You would use union keyword to define variables of union type.
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Output
size of union = 32
size of structure = 40
99
BIT FIELDS
Till now we have used integer fields of size 16 bits to store data. But there are some
situations where data variables require much less than 16 bits of space. In such cases we waste
memory space. To avoid this we use bit fields whose size can be from 1 to 16 bits in length.
Syntax:
struct tagname
{
datatype var1:bit_length;
...
datatype var n:bit_length
}
100
The data type is either int or unsigned int or signed int and the bit length is number of bits
used.
Example: Personal information of employees
The range of values for each field is as follows :
Bit field bit length range of values
sex 1 0 or 1
age 7 0 or 127(2 (7)-1)
m_status 1 0 or 1
children 3 0 to 7(2(3)-1)
To assign values to bitfields :
emp.sex=1
emp.age=50;
We cannot use scanf() to read values into a bit field. We have to read into a temporary
variable and then assign its value to bit field.
For example
scanf(%d%d",&eage,&echildren);
emp.age=eage;
emp.children=echildren;
One restriction in accessing bit fields is that a pointer cannot be used.It is possible to
combine normal structure elements with bit field elements.
For example:
struct personal
{
char name[20];
unsigned sex : 1;
unsigned age : 7;
....
....
}emp[100];
Example
Declaration of date without use of bit fields.
#include <stdio.h>
101
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
Size of date is 12 bytes
Date is 31/12/2014
#include <stdio.h>
// A space optimized representation of date
struct date
{
// d has value between 1 and 31, so 5 bits are sufficient
unsigned int d: 5;
// m has value between 1 and 12, so 4 bits are sufficient
unsigned int m: 4;
unsigned int y;
};
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
Output:
Size of date is 8 bytes
Date is 31/12/2014
102
2) We cannot have pointers to bit field members as they may not start at a byte boundary.
#include <stdio.h>
struct test
{
unsigned int x: 5;
unsigned int y: 5;
unsigned int z;
};
int main()
{
struct test t;
// Uncommenting the following line will make the program compile and run
printf("Address of t.x is %p", &t.x);
// The below line works fine as z is not a bit field member
printf("Address of t.z is %p", &t.z);
return 0;
}
Output:
error: attempt to take address of bit-field structure member 'test::x'
103
};
int main()
{
struct test t;
t.x = 5;
printf("%d", t.x);
return 0;
}
Output:Implementation-Dependent
4) Array of bit fields is not allowed. For example, the below program fails in compilation.
struct test
{
unsigned int x[10]: 5;
};
int main()
{
}
Output:error: bit-field 'x' has invalid type
Sometimes it is very useful to pass information into a program when we run it from the
command prompt. The general method to pass information into main() function is through the
use of command line arguments. It follows the program‘s name on the command prompt of the
operating system.
They are:
The first argument is argc (argument count) must be an integer value, which represents
the number arguments in the command prompt. It will always be at least one because the name
of the program qualifies as the first argument.
When an array is used as an argument to function, only the address of the array is passed, not
a copy of the entire array. When a function is called with an array name, a pointer to the first
element in the array is passed into a function. (In C, an array name without as index is a pointer
to the first element in the array).Each of the command line arguments must be separated by a
space or a tab.
104
char *argv[];
The env parameter is declared the same as the argv parameter, it is a pointer to an array of
strings that contain environmental setting.
Recall that argv in main is declared as char **; this means that it is a pointer to a pointer to a
char, or in this case the base address of an array of pointers to char, where each such pointer
references a string. These strings correspond to the command-line arguments to your program,
with the program name itself appearing in argv[0]
The count argc counts all arguments including argv[0]; it is 1 if your program is called with
no arguments and larger otherwise.
#include<stdio.h>
int main(int argc, char **argv)
{
int i;
printf("argc = %d\n\n", argc);
for(i = 0; i < argc; i++)
{
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
Preprocessor commands
• Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor. This process is called preprocessing.
• Commands used in preprocessor are called preprocessor directives and they begin with
―#‖ symbol.
Below is the list of preprocessor directives that C programming language offers.
Preprocessor Syntax/Description
Syntax: #define
This macro defines constant value and can be any
Macro of the basic data types.
105
Syntax: #include<file_name>
Header file The source code of the file ―file_name‖ is included in
inclusion the main program at the specified place.
106
UNIT-II
Data Structure is a way of collecting and organizing data in such a way that we can perform
operations on these data in an effective way. Data Structures is about rendering data elements
in terms of some relationship, for better organization and storage. For example, we have data
player's name "Virat" and age 26. Here "Virat" is of String data type and 26 isof integer data
type.
We can organize this data as a record like Player record. Now we can collect and store player's
records in a file or database as a data structure. For example: "Dhoni" 30, "Gambhir" 31,
"Sehwag" 33
In simple language, Data Structures are structures programmed to store ordered data, so that
various operations can be performed on it easily.
Basic types of Data Structures
As we discussed above, anything that can store data can be called as a data strucure, hence
Integer, Float, Boolean, Char etc, all are data structures. They are known as Primitive Data
Structures.
Then we also have some complex Data Structures, which are used to store large and connected
data. Some example of Abstract Data Structure are :
• Linked List
• Tree
• Graph
107
108
• Stack,
• Queue etc.
All these data structures allow us to perform different operations on data. We select these data
structures based on which type of operation is required. We will look into these data structures
in more details in our later lessons.
Abstract Data Type:
It can be defined as a collection of data items together with the operations on the
data. The word ―abstract‖ refers to the fact that the data and the basic operations defined on
it are being studied independently of how they are implemented. It involves what can be
done with the data, not how has to be done.
An implementation of ADT consists of storage structures to store the data items and
algorithms for basic operation. All the data structures i.e. array, linked list, stack, queue etc
are examples of ADT.
DATA STRUCTURE
109
110
Linked List is a sequence of links which contains items. Each link contains a connection to
another link. It is the second most-used data structure after array.
Following are the important terms to understand the concept of Linked List.
• Link − Each link of a linked list can store a data called an element.
• Next − Each link of a linked list contains a link to the next link called Next.
• LinkedList − A Linked List contains the connection link to the first link called First.
Linked list can be visualized as a chain of nodes, where every node points to the next node.
As per the above illustration, following are the important points to be considered.
Basic Operations
• Insertion − Adds an element at the beginning,end and after a specific node of the list.
• Deletion − Deletes an element at the beginning and at position of the list.
• Display − Displays the complete list.
• Search − Searches an element using the given key.
111
In a linked list the ordered sequence of nodes with links do not reside in sequential locations.
The locations of the nodes may change on different runs.
112
};
list_pointer ptr =NULL
list_pointer create2( )
{
/* create a linked list with two nodes */
list_pointer first, second;
first = (list_pointer) malloc(sizeof(list_node));
second = ( list_pointer) malloc(sizeof(list_node));
second -> link = NULL;
second -> data = 20;
first -> data = 10;
first ->link = second;
return first;
}
list_pointer temp;
temp = (list_pointer) malloc(sizeof(list_node));
if (IS_FULL(temp)) //if, temp==NULL
{
fprintf(stderr, ―The memory is full\n‖);
exit (1);
}
temp->data = 50;
if (*ptr) { // nonempty list
temp->link =node ->link;
113
node->link = temp;
}
else { // empty list
temp->link = NULL;
*ptr =temp;
}
}
List Deletion
a) Before b) After deletion
114
printf(―\n‖);
}
Node
The operations that can be performed on single linked lists includes: insertion,
deletion and traversing the list.
3. Inserting at end.
begin
return (first)
else
new avail;
avail link(avail)
115
info(new) x
link(new) first
return (new);
end.
In the algorithm, first, the memory for a new node is available or not is checked out.
Here avail is a pointer to the available memory.
If it is NULL then there is no memory. Otherwise a new node is created from available
memory and it is stored in new. The new contains the address of the new node and avail moves
forward to point to next available memory location. In the info field of new, x is stored and the
link field of new points to the first element address of the list. Now, new becomes the pointer
to the whole list.
(a)
(b)
First is having value of 100, means it is Pointing the 100th memory location. The node
at 100th location is having info as 10 and containing the address 200 of the next node. The
second node at 200th location, contains 20 and address 300 of the next node. At,300th memory
location, the node contains info as 30 and its link field is NULL. That means it is no more
having any nodes. That is, the list is having 3 nodes with a starting address of 100.
Now, we created another node new that is having the address of 50 and its info is 40
and its link field is NULL.
116
After the call to insertbeg( ) function the list will look like.
The insertbeg( ) function, inserts a node by storing the address of the first node of list
in the link field of new and making the new address as the pointer to the list.
begin
return(first);
avail link(avail)
link(new) NULL
return(new);
return (first)
117
end;
(a)
(b)
(c)
first (100) address is stored in Save to go through the end of the list, after reaching to the last
node, set the address of new node in the link field of last node.
118
In this process, the address of first is stored in Save to go to the particular node at which
the insertion is to be done. After reaching the particular node, set the link to point to new node,
and set the link of new node to connect the remaining nodes.
begin
return (first)
new avail
link(new) first
Save first
Info(link(Save)) info(new)
link(Save) new
return(first)
end
119
(a)
(b)
(c)
(d)
120
(e)
Procedure:
Algorithm:
begin
if first = NULL then /* Checking whether the list is empty */
write(‗ Underflow‘);
return
temp first /* Initializing search for x */
while((temp x ) and
(link(temp) NULL))
begin
pred temp
temp link(temp)
end
if temp x then /* if the node not found */
write(‗node not found‘)
return
if (x = first) then / is x first node */
first link(first) /* delete the node at x */
else link(pred) link(x)
link(x) avail /* Return node to availability area */
avail x
121
return:
end.
In the algorithm, it first checks whether the list is empty, if it is empty it prints
underflow message. Otherwise, it initializes a temporary pointer to first. Until the Predecessor
of x node found, the temporary pointer is moved forward. If it reaches the end of the list, without
finding the node of address x, it flashes an error message, stating ‗node not found‘. If x is the
first address, then first node is deleted and now first points to second node. Otherwise it sets
the links so that it deletes the node of address x.
The original list is:
(a)
(b)
The node which is 100th memory address will be added to free space
(ii) if x = 200
122
(b)
(c)
(a)
(b)
123
This includes, visiting the node and printing the data of that node one at a time and moving
forward until it reaches end of the list. (i.e., link becomes NULL)
Procedure(first)
begin
end.
124
UNIT-III
Sorting –selection sort, Quick Sort, insertion sort techniques (Using Arrays)
Searching - linear search, binary search techniques (Using Arrays)
Introduction to Sorting
Internal Sorts:-This method uses only the primary memory during sorting process. All data
items are held in main memory and no secondary memory is required this sorting process. If
all the data that is to be sorted can be accommodated at a time in memory is called internal
sorting. There is a limitation for internal sorts; they can only process relatively small lists due
to memory constraints. There are 3 types of internal sorts.
External Sorts:-Sorting large amount of data requires external or secondary memory. This
process uses external memory such as HDD, to store the data which does not fit into the main
memory. So, primary memory holds the currently being sorted data only. All external sorts are
based on process of merging. Different parts of data are sorted separately and merged together.
Ex:- Merge Sort
1. Selection Sort
In selection sort the list is divided into two sub-lists:- sorted and unsorted. These two lists
are divided an imaginary wall. We find the smallest element from unsorted sub-list and
swap it to the beginning. And the wall moves one element ahead, as the sorted list
increases and unsorted list decreases.
Assume that we have a list on n elements. By applying selection sort, the first element is
compared with all remaining (n-1) elements. The smallest element is placed at the first
location. Again, the second element is compared with remaining (n-1) elements. At the time
of comparison, the smaller element is swapped with larger element. Similarly, entire array
is checked for smallest element and then swapping is done accordingly. Here we
125
Algorithm: Selection_Sort ( A [ ] , N )
126
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[j] > a[min])
min=j;
}
t=a[i];
a[i]=a[min];
a[min]=t;
}
OUTPUT
How many elements you want to
sort? : 5
2. Quick Sort:
127
series of pairwise comparisons, the pivot is brought to its final place, with smaller elements on
its left and greater elements to the right. Elements equal to pivot can be on either or both sides.
As we shall see, there are numerous partitioning schemes, and while the details
of them are not central to this thesis, we should describe the basic ideas. A straightforward and
natural way (see e.g. uses two pointers – a left pointer, initially at the left end of the array and a
right pointer, initially at the right end of the array. We pick the leftmost element of the array as
pivot and the right pointer scans from the right end of the array for a key less than the pivot. If it
finds such a key, the pivot is swapped with that key. Then, the left pointer is increased by one
and starts its scan, searching for a key greater than 7 the pivot: if such a key is found, again
the pivot is exchanged with it. When the pointers are crossed, the pivot by repeated exchanges
will “float” to its final position and the keys which are on its left are smaller and keys on its right
are greater.
128
3. Insertion Sort:
Both the selection and Quick Sort sorts exchange elements. But insertion sort does not
exchange elements. In insertion sort the element is inserted at an appropriate place similar
to card insertion. Here the list is divided into two parts sorted and unsorted sub-lists. In each
pass, the first element of unsorted sub list is picked up and moved into the sorted sub list by
inserting it in suitable position. Suppose we have ‗n‘ elements, we need n-1 passes to sort
the elements.
1. We start with an empty left hand [sorted array] and the cards face down on the table
[unsorted array].
2. Then remove one card [key] at a time from the table [unsorted array], and insert it
into the correct position in the left hand [sorted array].
3. To find the correct position for the card, we compare it with each of the cards already
in the hand, from right to left.
INSERTION_SORT (A)
FOR j ← 2 TO length[A]
DO key ←A[j]
ofj indicated. j indexes the "current card" being inserted into the hand.
Read the figure row by row. Elements to the left of A[j] that are greater than A[j] move one
position to the right, and A[j] moves into the evacuated position.
Ex:- A list of unsorted elements are: 78 23 45 8 32 36 . The results of insertion sort foreach
pass is as follows:-
Write a program to explain insertion sort . Which type of technique does it belong.
(or)
Write a C-program for sorting integers in ascending order using insertion sort.
#include<stdio.h>
void main( )
{
int
a[10],i,j,k,n;
printf("How many elements you want to sort?\n");
scanf("%d",&n);
printf("\nEnter the Elements into an array:\n");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
k=a[i];
printf("%d\n", a[i]);
OUTPUT:
How many elements you want to sort ? :
6
Linear Search
Linear search technique is also known as sequential search technique. The linear search
is a method of searching an element in a list in sequence. In this method, the array is searched
for the required element from the beginning of the list/array or from the last element to first
element of array and continues until the item is found or the entire list/array has been searched.
Algorithm:
Advantages:
1. It is simple and conventional method of searching data. The linear or sequential name
implies that the items are stored in a systematic manner.
2. The elements in the list can be in any order. i.e. The linear search can be applied on
sorted or unsorted linear data structure.
Disadvantage:
Write a C program that searches a value in a stored array using linear search.
#include<stdio.h>
int linear(int [ ],int,int);
void main( )
{
int a[20], pos = -1, n, k, i;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0; i<n ;i++)
scanf("%d",&a[i]);
printf("\nEnter the element to be searched:");
scanf("%d",&k);
pos=linear(a,n,k);
if(pos != -1)
printf("\n Search successful element found at position %d",pos);
Else
printf("\n Search unsuccessful, element not found");
getchar( );
}
int linear(int a[ ],int n,int k)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==k)
return(i);
}
return -1;
}
Output:-
Enter the n value : 5
Enter elements for an array : 11 2 23 14 55
Enter the element to be searched: 14
Search successful element found at position : 3
Write a C program that searches a value in a stored array using recursive linear search.
#include<stdio.h>
int linear(int [ ],int,int);
void main( )
{
int a[20],pos=-
1,n,k,i;
printf("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Enter the element to be searched:");
scanf("%d",&k);
pos=linear(a,n,k);
if(pos!=-1)
printf("\n Search successful, Element found at Position %d",pos);
else
printf("Search unsuccessful, element not found "
}
int linear(int a[ ],int n,int k)
{
int i;
for(i=n-1;i>=0;i--)
{
if(a[i]==k)
return(i);
else
{
n = n-1;
return (linear(a.n.k);
}
}
return -1;
}
Output:-
Enter ‗n‘ value : 6
Enter elements for an array : 10 32 22 84 55 78
Enter the element to be searched : 55
Binary search
Binary search is the most popular Search algorithm.It is efficient and also one of the most
commonly used techniques that is used to solve problems.
If all the names in the world are written down together in order and you want to search for the
position of a specific name, binary search will accomplish this in a maximum of 35 iterations.
Binary search works only on a sorted set of elements. To use binary search on a collection,
the collection must first be sorted.
When binary search is used to perform operations on a sorted set, the number of iterations
can always be reduced on the basis of the value that is being searched.
By using linear search, the position of element 8 will be determined in the 9th iteration.
Let's see how the number of iterations can be reduced by using binary search. Before we start
the search, we need to know the start and end of the range. Lets call them Low and High.
Low = 0
High = n-1
Now, compare the search value K with the element located at the median of the lower and
upper bounds. If the value K is greater, increase the lower bound, else decrease the upper
bound.
Referring to the image above, the lower bound is 0 and the upper bound is 9. The median of
the lower and upper bounds is (lower_bound + upper_bound) / 2 = 4. Here a[4] = 4. The value
4>2, which is the value that you are searching for. Therefore, we do not need to conduct a
search on any element beyond 4 as the elements beyond it will obviously be greater than 2.
Therefore, we can always drop the upper bound of the array to the position of element 4. Now,
we follow the same procedure on the same array with the following values:
Low: 0
High: 3
Repeat this procedure recursively until Low > High. If at any iteration, we get a[mid]=key, we
return value of mid. This is the position of key in the array. If key is not present in the array,
we return −1.
Write a C program that searches a value in a stored array using iterative binary search.
#include<stdio.h>
int bsearch(int [ ],int,int);
void main( )
{
int a[20],pos,n,k,i;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the key value:");
scanf("%d",&k);
pos=bsearch(a,n,k);
if(pos!= -1)
printf("Search successful, element found at position %d",pos);
else
printf("Search unsuccessful, element not found");
getch( );
}
i(k<a[mid])
ub=mid-1;
else if(k>a[mid])
lb=mid+1;
else if(k==a[mid])
return(mid);
return -1;
OUTPUT
Write a C program that searches a value in a stored array using recursive binary
search.
#include <stdio.h>
if (r >= l)
{
int mid = l + (r - l)/2;
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
UNIT -IV
Stacks and Queues are very useful in numerous applications. For eg. Stacks are used in
computers in parsing an expression by recursion; in memory management in operating system;
etc. Queues find their use in CPU scheduling in printer spooling, in message queuing in
computer network etc.
STACKS:
Stack is an ordered collection of data in which data is inserted and deleted at one end
(same end). In stack the most recent elements are inserted first. For eg.plates are pushed on to
the top and popped off the top. Such a processing strategy is referred to as Last-in-First-out or
LIFO. A Stack is a data structure which operates on a LIFO basis, it is used to provide
temporary storage space for values. Stack is most commonly used as a place to store local
variables, parameters and return addresses. When a function is called the use of stack is critical
where recursive functions, that are function that call them are defined.
Stack uses a single pointer ‗top‘ to keep track of the information in the stack.
A stack pointer keeps track of the current position on the stack. When an element is placed
on the stack, it is said to be pushed on the stack when an object is removed from the stack, it is
said to be popped from the stack. Stack ‗Overflow‘ occurs when one tries to push more
information on a stack, and ‗Underflow‘ occurs when we try to pop an item off a stack which
is empty.
Representation Of Stack:
Two standard methods of representing a stack are in terms of an array and a pointer
linked list which is a way of representation using pointer.
The Stack pointer is pointing to the top of the stack (called the top of the stalk). The
size of the array is fixed at the time of its declaration itself. But, as the definition shows, stacks
are dynamic data structures. They can grow and shrink during the operation. However, stack
can be implemented using arrays by specifying a maximum size. We require two things to
represent stacks. First one is array to hold the item and second an integer variable to hold the
index of the top element conveniently in C, we can declare stack as a structure to represent
these two
#define max 50
struct stack
{
int top:
I int items [max]:
};
Now the stack s can be declared as struct stack S;
Note that the type of array elements in the above declaration is integer, but actually it can be of
any other type. Since array subscripts starts from 0, the 50 stack elements in the above example
reside in the location S.item[0] through S.items[49]. The top element can be accessed as
S.item[top].
Push Operation
The process of putting a new data element onto stack is known as a Push Operation. Push
operation involves a series of steps −
• Step 3 − If the stack is not full, increments top to point next empty space.
• Step 4 − Adds data element to the stack location, where top is pointing.
If the linked list is used to implement the stack, then in step 3, we need to allocate space
dynamically.
Example
Pop Operation
Accessing the content while removing it from the stack, is known as a Pop Operation. In an
array implementation of pop() operation, the data element is not actually removed, instead
top is decremented to a lower position in the stack to point to the next value. But in linked-list
implementation, pop() actually removes data element and deallocates memory space.
• Step 3 − If the stack is not empty, accesses the data element at whichtop is pointing.
if stack is empty
return null
endif
data← stack[top]
top← top -1
return data
end procedure
if(!isempty()){
data= stack[top];
top= top -1;
return data;
}else{
printf("Could not retrieve data, Stack is empty.\n");
}
}
Since a stack can contain only a finite number of elements, an error called a ‗stack
overflow‘ occurs when the stack is full and a push operation is performed. Similarly, an error
called a stack underflow occurs when the stack is empty and a pop operation is performed.
These two conditions need to be checked before doing the respective operations.
ALGORITHM
STEP3: if it is not empty then define a node pointer and set it to top
Display():
STEP3: if it is not empty then define a node pointer and initialize with the top.
STEP4: Display temp-->data and move it to the next node.repet this until temp reaches the
first node in the stack(temp—>next=NULL).
There is an algorithm to convert an infix expression into a postfix expression. It uses a stack;
but in this case, the stack is used to hold operators rather than numbers. The purpose of the
stack is to reverse the order of the operators in the expression. It also serves as a storage
structure, since no operator can be printed until both of its operands have appeared.
In this algorithm, all operands are printed (or sent to output) when they are read. There are
more complicated rules to handle operators and parentheses.
Example:
1. A * B + C becomes A B * C +
The order in which the operators appear is not reversed. When the '+' is read, it has lower
precedence than the '*', so the '*' must be printed first.
We will show this in a table with three columns. The first will show the symbol currently being
read. The second will show what is on the stack and the third will show the current contents of
the postfix string. The stack will be written from left to right with the 'bottom' of the stack to
the left.
1 A A
2 * * A
3 B * AB
6 AB*C+
The rule used in lines 1, 3 and 5 is to print an operand when it is read. The rule for line 2 is to
push an operator onto the stack if it is empty. The rule for line 4 is if the operator on the top of
the stack has higher precedence than the one being read, pop and print the one on top and then
push the new operator on. The rule for line 6 is that when the end of the expression has been
reached, pop the operators on the stack one at a time and print them.
2. A + B * C becomes A B C * +
Here the order of the operators must be reversed. The stack is suitable for this, since operators
will be popped off in the reverse order from that in which they were pushed.
1 A A
2 + + A
3 B + AB
4 * +* AB
5 C +* ABC
6 ABC*+
In line 4, the '*' sign is pushed onto the stack because it has higher precedence than the '+' sign
which is already there. Then when the are both popped off in lines 6 and 7, their order will be
reversed.
3. A * (B + C) becomes A B C + *
1 A A
2 * * A
3 ( *( AB
4 B *( AB
5 + *(+ AB
6 C *(+ ABC
7 ) * ABC+
8 ABC+*
Since expressions in parentheses must be done first, everything on the stack is saved and the
left parenthesis is pushed to provide a marker. When the next operator is read, the stack is
treated as though it were empty and the new operator (here the '+' sign) is pushed on. Then
when the right parenthesis is read, the stack is popped until the corresponding left parenthesis
is found. Since postfix expressions have no parentheses, the parentheses are not printed.
4. A - B + C becomes A B - C +
When operators have the same precedence, we must consider association. Left to right
association means that the operator on the stack must be done first, while right to left
association means the reverse.
1 A A
2 - - A
3 B - AB
4 + + AB-
5 C + AB-C
6 AB-C+
In line 4, the '-' will be popped and printed before the '+' is pushed onto the stack. Both operators
have the same precedence level, so left to right association tells us to do the first one found
before the second.
5. A * B ^ C + D becomes A B C ^ * D +
Here both the exponentiation and the multiplication must be done before the addition.
1 A A
2 * * A
3 B * AB
4 ^ *^ AB
5 C *^ ABC
6 + + ABC^*
7 D + ABC^*D
8 ABC^*D+
When the '+' is encountered in line 6, it is first compared to the '^' on top of the stack. Since it
has lower precedence, the '^' is popped and printed. But instead of pushing the '+' sign onto the
stack now, we must compare it with the new top of the stack, the '*'. Since the operator also
has higher precedence than the '+', it also must be popped and printed. Now the stack is empty,
so the '+' can be pushed onto the stack.
6. A * (B + C * D) + E becomes A B C D * + * E +
1 A A
2 * * A
3 ( *( A
4 B *( AB
5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
9 ) * ABCD*+
10 + + ABCD*+*
11 E + ABCD*+*E
12 ABCD*+*E+
2. If the stack is empty or contains a left parenthesis on top, push the incoming operator onto
the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the operators until you
see a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack, push it on the stack.
6. If the incoming symbol has equal precedence with the top of the stack, use association. If
the association is left to right, pop and print the top of the stack and then push the incoming
operator. If the association is right to left, push the incoming operator.
7. If the incoming symbol has lower precedence than the symbol on the top of the stack, pop
the stack and print the top operator. Then test the incoming operator against the new top of
stack.
8. At the end of the expression, pop and print all operators on the stack. (No parentheses should
remain.
QUEUES:
A queue is an ordered collection of elements, where the elements can be inserted at one
end and deleted from another end. It works on the principle called First–In–First–Out (FIFO).
The information we retrieve from a queue comes in the same order that it was placed
on the queue. The examples of queues are checkout line at supermarket cash register, line of
cars waiting to proceed in some fixed direction at an intersection of streets.
Operations On Queues:
Insertion: The operation of adding new items on the queue occurs only at one end of the
queue called the rear end.
Deletion: The operation of removing items of the queue occurs at the other end called the
front end.
Queue_delete( )
If FRONT =0 then
Write(‗Queue under flow‘).
Return
K Q[FRONT]
If FRONT = REAR then
Begin
FRONT 0
REAR 0
End
Else
FRONT FRONT +1
Return K
UNIT – V
File is a collection of bytes that is stored on secondary storage devices like disk.
The primary purpose of a file is to keep record of data. Record is group of related fields, Field
is a group of characters they convey meaning.
Files are stored in auxiliary of secondary storage devices. The two common forms of
secondary storage are disk (hard disk, CD and DVD) and tape.
Each file ends with an end of file (EOF) at a specified byte number, recorded in file structure.
Streams:
Predefined Streams :
Stands
Standard Input Standard Output
For
Data (Often Text) going into a data (Often Text) going out from a
Data Flow
program program
FILE OPERATIONS:
There are 4 basic operations that can be performed on any files in C programming language.
They are,
1. Opening a file
2. Closing a file
3. Reading a file
4. Writing in a file
Let us see the syntax for each of the above operations in a table:
File operation/
Description
Syntax
file open
fopen function is used to open a file.
FILE *fp; fp=fopen(―filename‖,
Where, fp is file pointer to the data type ―FILE‖.
‖‗mode‖);
file close: fclose function closes the file that is being pointed by file
fclose(fp); pointer fp.
fgets is used to read a file line by line. where,
file read: buffer – buffer to put the data in.
fgets(buffer, size, fp); size – size of the buffer
fp – file pointer
file write:
fprintf(fp, ―some data‖); fprintf(fp,
fprintf writes the data into a file pointed by fp.
―text %d‖, variable_name);
Mode of operations
There are many modes in opening a file. Based on the mode of file, it can be opened for
reading or writing or appending the texts. They are listed below.
• r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist.
• w – Opens a file in write mode. It returns null if file could not be opened. If file exists,
data are overwritten.
• a – Opens a file in append mode. It returns null if file couldn‘t be opened.
• r+ – Opens a file for read and write mode and sets pointer to the first character in the
file.
• w+ – opens a file for read and write mode and sets pointer to the first character in the
file.
• a+ – Opens a file for read and write mode and sets pointer to the first character in the
file. But, it can‘t modify existing contents.
C programming language offers many inbuilt functions for handling files. They are given
below.
File
Description
handling functions
fopen () fopen () function creates a new file or opens an existing file.
fclose () fclose () function closes an opened file.
getw () getw () function reads an integer from file.
putw () putw () functions writes an integer to file.
getc (), fgetc () getc () and fgetc () functions read a character from file.
putc (), fputc () putc () and fputc () functions write a character to file.
gets () gets () function reads line from keyboard.
puts () puts () function writes line to o/p screen.
fgets () fgets () function reads string from a file, one line at a time.
fputs () fputs () function writes string to a file.
feof () feof () function finds end of file.
fgetchar () fgetchar () function reads a character from keyboard.
fgetc () fgetc () function reads a character from file.
fprintf () fprintf () function writes formatted data to a file.
fscanf () fscanf () function reads formatted data from a file.
fgetchar () fgetchar () function reads a character from keyboard.
fputchar () fputchar () function writes a character from keyboard.
Opening a file is performed using the library function in the "stdio.h" header file:
fopen():
Closing a File:
The file (both text and binary) should be closed after reading/writing.
fclose(fptr);
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that, fprint and
fscanf expects a pointer to the structure FILE.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
To write into a binary file, you need to use the function fwrite(). The functions takes four
arguments: Address of data to be written in disk, Size of data to be written in disk, number of
such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
fread(address_data,size_data,numbers_data,pointer_to_file);
If you have many records inside a file and need to access a record at a specific position, you
need to loop through all the records before it to get the record.
This will waste a lot of memory and operation time. An easier way to get to the required data
can be achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax:
fseek(FILE * stream, long int offset, int whence)
The first parameter stream is the pointer to the file. The second parameter is the position of
the record to be found, and the third parameter specifies the location where the offset starts.
Whence Meaning
SEKK_CUR Starts the offset from the current location of the cursor in the file.
Its prototype is
You can position a file's current location to the start of the file using rewind(). Its prototype
is
C provides function for error handling during I/O operations. Typical error situations include:
We have two status-inquiry library functions, feof () and ferror() that can help us detect I/O
error in the files.
EOF:
The feof function can be used to test for an end of file condition.
n = feof(fp);
The C programming language provides perror() and strerror() functions which can be used
to display the text message associated with errno.
• The perror() function displays the string you pass to it, followed by a colon, a space,
and then the textual representation of the current errno value.
• The strerror() function, which returns a pointer to the textual representation of the
current errno value.
Program Development:
The solid lines show inputs into each step of the development cycle. Compile and Linkage
Editor Operations are performed by the C for AIX product, which also lets you specify what
optional outputs are produced. Optional outputs are shown in the diagram by the broken lines.
Descriptions of the steps follow below:
Design and Code Involves designing a program to meet a specified requirement, and creating
the programming language text files that will comprise the program source.
Linkage Editor Links compiler output with external modules requested by the compiled
program. C programs can use routines from C libraries or any object or
archive file from the IBM XL family of languages. C programs can also
use modules produced by the current or previous compilations. As well as
linking the external modules, the linkage editor resolves addresses within
the object module.
Run and Test This stage can be both the final step in program development, or it can be
an intermediate point in the program design and implementation process.
A program's design commonly is further refined as a result of information
gathered during testing.
• A header file - contains the declaration of the class (without implementation details)
• An implementation file - contains implementations of the class members
Filenames:
Header files are usually in the format filename.h, and implementation files are usually in the
format filename.cpp. It is a good idea to use the same base filename for corresponding header
and implementation files. Example:
When classes are used in a program, the main program would usually be written in a separate
file.
The "compilation" of a program actually consitsts of two major stages.
1. Compile stage
o Syntax checked for correctness.
o Variables and function calls checked to insure that correct declarations were
made and that they match. (Note:& The compiler doesn't need to match function
definitions to their calls at this point).
o Translation into object code. Object code is just a translation of your code file
-- it is not an executable program, at this point. (Note: the word "object" in object
code does not refer to the definition of "object" that we use to define object-
oriented programming. These are different terms.)
2. Linking stage
o Links the object code into an executable program.
o May involve one or more object code files.
o The linking stage is the time when function calls are matched up with their
definitions, and the compiler checks to make sure it has one, and only one,
definition for every function that is called.
o The end result of linking is usually an executable program.
For a simple example like our Fraction example, it may be tempting to simply use the following
statement inside the main.cpp file:
#include "frac.cpp"
and then just compile the main.cpp file with a single command. This will work in this example,
because it's a linear sequence of #includes -- this essentially causes the whole thing to be put
together into one file as far as the compiler is concerned. This is not a good idea in the general
case. Sometimes the line-up of files is not so linear. The separate ideas of compiling and
linking allow these steps to be done separately and there are some good reasons and benefits:
• Changes to a file require only that file to be re-compiled (rather than everything), along
with the re-linking
• Often, libraries are distributed in pre-compiled format, so trying to #include the .cpp
file would not even be feasible. (A pre-compiled library would still give you the actual
.h file for the #include statements, to satisfy declare-before-use in your own code).
All of the programs that we have looked at to this point have been contained within a single
file. This is the exception rather than the rule. As programs become larger, it is important to
spread them across files of a reasonable size. In this lesson we will look at why this is important,
and how it can be done.
Compiling Files:
Up to this point, whenever you wanted to compile a program you compiled the file displayed
in an Emacs buffer. The Compile This File... option of Emacs' Compile menu (or equivalently,
M-x compile) is a handy feature when your entire program is contained with one file. It is, of
course, possible to compile a file completely independently of Emacs.
Download hello.c. It is a simple program that prints out ``Hello world'', and you can compile
and run it without ever displaying it in Emacs. To compile it, go to a Unix Shell window,
connect to the directory into which you downloaded the program, and enter the following
command:
This command will result in a new file being created. Use the ls command to list your directory.
What file is there that wasn't before?
Answer: You should see a file called ``hello'' in your directory. This is the executable. The
name of the executable came from the command that you just typed-it is the name that follows
the -o in the command.
Now that you have an executable you can run it in the familiar way. Simply type ``hello'' into
the UNIX Shell window.
To summarize, the steps involved in compiling, linking, and running a program are:
1. Compile the ``.c'' file containing the source code with a command such as
The -c in the command is important--it tells C to produce an object file called (in this
case) ``hello.o''. The -Wall part is optional but is strongly encouraged--it tells C to
produce all possible warning messages. A warning message will usually lead you to a
bug in your program. The -g tells the compiler to include information needed by the
debugger.
The -o hello in the command is important--it tells C what to name the executable. The
-lm part tells C to link in the math libraries. If your program doesn't use any of the
match functions from ``math.h'', you can leave this part out.
If your entire program is contained within a single file, you can do the compilation and
linking in one step by entering the command
This is exactly what Emacs does when it compiles a program for you. We have been careful to
this point to do the compilation in two separate steps so that you will be able to deal with
programs made up of more than one file.
A data structure is basically a group of data elements that are put together under one name,
and which defines a particular way of storing and organizing data in a computer so that it can
be used efficiently.
Data structures are used in almost every program or software system. Some common examples
of data structures are arrays, linked lists, queues, stacks, binary trees, and hash tables. Data
structures are widely applied in the following areas:
- Compiler design -Operating system
- Statistical analysis package - DBMS
When selecting a data structure to solve a problem, the following steps must be performed.
1. Analysis of the problem to determine the basic operations that must be supported. For
example, basic operation may include inserting/deleting/searching a data item from the data
structure.
2. Quantify the resource constraints for each operation.
UNIT-I
{
printf("%d", sizeof(struct test));
return 0;
}
b)#include <stdio.h>
struct test
{
unsigned int x;
long int y: 33;
unsigned int z;
};
int main()
{
struct test t;
unsigned int *ptr1 = &t.x;
unsigned int *ptr2 = &t.z;
printf("%d", ptr2 - ptr1);
return 0;
}
c)#include <stdio.h>
union test
{
unsigned int x: 3;
unsigned int y: 3;
int z;
};
int main()
{
union test t;
t.x = 5;
t.y = 4;
t.z = 1;
printf("t.x = %d, t.y = %d, t.z = %d",
t.x, t.y, t.z);
return 0;
}
27. Use bit fields in C to figure out a way whether a machine is little endian or big endian.
UNIT II
UNIT -III
1. Define sorting.
2. What is the importance of sorting?
3. List different sorting techniques.
4. Define searching.
5. Define linear search.
6. Define binary search.
7. Explain the working of selection sort.
8. Explain the working of Quick Sort sort.
9. Explain the working of insertion sort.
10. Which technique of searching an element in an array would you prefer to use and in
which situation?
11. What are the different types of sorting techniques? Which sorting technique has the
least worst case?
12. Explain the difference between Quick Sort sort and selection sort. Which one is
more efficient?
13. Sort the elements 77, 49, 25, 12, 9, 33, 56, 81 using insertion sort.
14. Sort the elements 77, 49, 25, 12, 9, 33, 56, 81 using selection sort.
15. Sort the elements 77, 49, 25, 12, 9, 33, 56, 81 using Quick Sort sort.
16. A certain sorting technique was applied to the following data set, 45, 1, 27, 36, 54, 90.
After two passes, the rearrangement of the data set is given as below: 1, 27, 45, 36,
54, 90. Identify the sorting algorithm that was applied.
17. A certain sorting technique was applied to the following data set, 81, 72, 63, 45, 27,
36. After two passes, the rearrangement of the dataset is given as: 27, 36, 80, 72, 63,
45. Identify the sorting algorithm that was applied.
18. A certain sorting technique was applied to the following data set, 45, 1, 63, 36, 54, 90.
After two passes, the rearrangement of the data set is given as below: 1, 45, 63, 36,
54, 90. Identify the sorting algorithm that was applied.
19. Discuss the advantages of insertion sort.
20. Write a recursive function to perform selection sort.
21. Compare the running time complexity of different sorting algorithms.
22. Describe insertion sort with a proper algorithm. What is the complexity of insertion
sort in the worst case?
23. How many key comparisons and assignments an insertion sort makes in its worst
case?
24. Quick Sort sort algorithm is inefficient because it continues execution even after an
array is sorted by performing unnecessary comparisons. Therefore, the number of
comparisons in the best and worst cases is the same. Modify the algorithm in such a
fashion that it will not make the next pass when the array is already sorted.
25. How many comparisons are required to find 73 in the following array using binary
search 12,25,32,37,41,48,58,60,66,73,74,79,83,91,95.
26. Write a program to implement linear search.
27. Differentiate between linear and binary search.
28. Write a program to implement Quick Sort sort.
29. Write a program to implement selection sort.
UNIT -IV
UNIT V
30. What functions are used for file positioning? State the SEEK_ Constants used in fseek
function and explain the meaning.
31. State the functions used for accessing files randomly? Explain with examples.
32. Mention the different file opening modes that can be used with fopen ( ).
33. Discuss about unformatted I/O with suitable examples.
34. How many ways are used to represent a tree?Discuss with examples.
35. Discuss representation of graph with examples
36. Write a program to read a text file and to print the count the no of tab characters in a
given file.
37. Write a program to read a text file and to count the no of uppercase letters in a given
file.
38. Write a 'C' program to append the contents of one file to another.
39. Write a program to generate prime numbers in a given range and append them to
primes data file and display the file.
40. Write a C program to read name and marks of n number of students from user and
store them in a file. If the file previously exits, add the information of n students.
41. Write a program to print file contents in reverse order
42. Write a program to copy one file contents into another file in reverse order.
43. Write a program to display contents of the file on screen.
44. Write a program to merge two files into single file.
45. Write a C program to read a text file and to count Number of characters, Number of
words and Number of sentences and write in an output file.
46. Write a C program to read the text file containing some paragraph. Use fseek() and
read the text after skipping n characters from the beginning of the file.
47. Write a C program to read the text file containing some paragraph. Print the first n
characters from the beginning of the file.
48. Explain the terms used in Trees.
49. Explain the terminology used in Graphs.
UNIT-I
1. Define a structure and explain declaration and initialization of a structure with examples.
4. What are nested structures. Explain various ways in which we can nest structure with
appropriate examples.
UNIT II
3. Analyze the function and find the output of following function for start pointing to
first node of following linked list?
1->2->3->4->5->6
void fun(struct node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
4. The following C function takes a single-linked list of integers as a parameter and
rearranges the elements of the list. The function is called with the list containing the
integers 1, 2, 3, 4, 5, 6, 7 in the given order. Analyze the code and find the contents of
the list after the function completes execution?
struct node
{
int value;
struct node *next;
};
void rearrange(struct node *list)
{
struct node *p, * q;
int temp;
if ((!list) || !list->next)
return;
p = list;
q = list->next;
while(q)
{
temp = p->value;
p->value = q->value;
q->value = temp;
p = q->next;
q = p ? p->next:0;
}
}
5. You are given pointers to first and last nodes of a singly linked list, Identify the
following operations which are dependent on the length of the linked list?
a. Delete the first element
b. Insert a new element as a first element
c. Delete the last element of the list
d. Add a new element at the end of the list
UNIT-III
3. Describe insertion sort with a proper algorithm. What is the complexity of insertion sort in
the worst case?
4. Write a program to implement Quick Sort sort.
5. Sort the elements 8, 22, 7, 9, 31, 19, 5, 13 using selection sort, Quick Sort sort, insertion sort
UNIT-IV
1. What is a Data Structure? Explain the concept of a linear list, queue and stack.
2. What is post fix and pre fix notation. Explain stack implementation for both with
appropriate example.
UNIT-V
1. Write a C program to read a text file and to count
a) number of characters
b) number of words and
c) number of sentences and write in an output file.
2. What are the file I/O functions in C. Give a brief note about the task performed by each
function with appropriate example.
4. Write a C program to replace every fifth character of the data file using fseek() command.
5. Write a program to read the following data to find the value of each item and display the
contents of the file.
UNIT-I
1. The member variable of structure are accessed by using
a) Union contain member of different data types which share the same storage
area in memory
7. Interrupt 0*21 is a
10. The number of bytes required for enumerated data type in memory are
a) AH b) AL c) BH d) AX
12. Observe the following program neatly and choose the appropriate printf() statement
}
a) printf(―\n Month :%s‖,m.month);
b) printf(―\n Month :%s‖,mmonth);
c) printf(―\n Month :%s‖,m.*month);
d) printf(―\n Month :%s‖,*m.month);
13. what will be the value of m displayed on axecution of the following programe?
#include<stdio.h>
struct bit
{
unsigned int m:3;
}
void main()
{
struct bit b={ 8};
printf(―\n m=%d‖,b.m);
}
a) m=0 b) m=8 c) m=3 d) none of the above
14. The size of structure in bytes occupied in the following program will be
#include<stdio.h>
struct bit
{
unsigned int m:4;
unsigned int x:4;
int k;
float bit f;
};
struct bit b;
void main()
{
printf(―size of structure in bytes =%d‖,sizeof(b));
}
a) 8 b) 10 c) 7 d) 4
UNIT II
1. Logical organization of data in computer memory is called [ ]
A. data style B. data manner C. data set D. all are wrong
2. A 2D array which contains majority of elements as null or zero [ ]
A. sparse matrix B. sparse matrix C. null matrix D all are correct
3. Address of the first element of an array is called [ ]
A. starting address B. base address C. both p &q are valid D. all are correct
4. Which of the following refers indexing formula [ ]
A. a[i]=M+(i-L)*w B.a[i]=M+(i+L)*w C.a[i]=M-(i+L)*w D.a[i]=M*(i-L)+w
5. Arrays are not static data structures [ ]
A. True B. false C. can‘t determine D. may be
6. A pointer array variable contains ------------- as its elements [ ]
A. integer values B. addresses of memory locations C. both p &q are valid D. none
7. What does link part of a tail node in a circular linked list hold? [ ]
A. address of head node B. address of header node C. address of it‘s previous node
D. none
8. What is the value present in the address part of a header node in linked list [ ]
A. address of head node B. address of header node
C. address of tail node D. all are wrong
9. Tail node in circular linked list always points [ ]
A. header node B. head node C.NULL value D. it‘s next node
10. How can we access the value present at nth- row ,pth- plane, mth- column of a multi -
dimensional array ―x‖ [ ]
A.x[n][p][m] B.x[n][m][p] C.x[p][n][m] D.x[m][n][p]
11. memory for elements in an array is not allocated in contiguous locations(addresseD. [ ]
A. true B. false C. not possible D. can‘t predict
12. Each node in a linked list must contain at least .... fields [ ]
A.3 B.2 C.4 D.5
14. A linear list in which the pointer points only to the successive node is........ [ ]
A. singly linked list B. double linked list C. circular linked list D. all
are correct
15. If address part of the head node contains non null value, it means [ ]
A. list has exactly 1 node
B. list has exactly 2 nodes address
C. list has at least 2 nodes
D. all are wrong
16. Let us suppose, header node address is:100,head node address is:200 and a new
node(address is 300) is inserted after the header node. Then data part of the header node
contains []
A.100 B.200 C.300 D.NULL
17. Llink part of the header node in a circular double linked list contains []
A. address of left most node B. address of right most node
C. address of head node D. both p&r
18. Which of the following is disadvantage in using ―linked lists‖? []
A .requires more memory B. dynamic data structure
C. elements are deleted and inserted easily D. none
19. Memory for elements in linked list are allocated in non-contiguous locations [ ]
A. true B. false C. can‘t determine D. may be
20. Which of the following data structures are convenient to perform insertion and deletion
operations []
A. arrays B. linked lists C. both A&B D. all are wrong
21. Which of the following is disadvantage of arrays
A. static storage B. insertions require shifting of elements [ ]
C. deletions require shifting of elements D. all are correct
22. To traverse an array means []
A. to process each element in an array B. to delete an element from an array
C. to insert an element into an array D. to combine two arrays into a single array
23. Finding the location of the element with a given value is: [ ]
A. Traversal B. Search C. Sort D. None of above
24. If the base address of a character array is 200 then what is the address of 3rd element in
that array [ ]
A.202 B.203 C.204 D. none
25. The memory address of first element in array is called? []
A. base address B. first address C. stating address
D. both a &c
26. the address of first node in a linked list is?
A. can‘t say B.100 C. 0 D. none
27. A doubly linked list has ........... pointers with each node. [ ]
A. 0 B. 1 C. 2 D. 3
28. A doubly linked list is also called as. ......... [ ]
A. linked list B. one way chain C. two way chain D. right link
29. In a linked list, insertion can be done as .......... [ ]
A. beginning B. end C. middle D. all of the above
30. To implement Sparse matrix dynamically, the following data structure is used [ ]
A. Trees B. Graphs C. Priority Queues D. Linked List
31. Header of a linked list is a special node at the [ ]
A. end of the linked list B. at the middle of the linked list
C. beginning of the linked list D. none of these
32. Which of the following operations is performed more effi ciently by a doubly linked list
than by a linear linked list? [ ]
A. Deleting nodes whose location is given
B. Searching an unsorted list for a given item
C. Inserting a node after the node with a given location
D. Traversing the list to process each node
33. Overflow condition in a linked list may occur when attempting to [ ]
A. create a node when free space pool is empty
B. traverse the nodes when free space pool is empty
C. create a node when linked list is empty
D. none of these
UNIT-III
1. The worst case complexity is when compared with the average case complexity of
a binary search algorithm.
3. Which of the following cases occurs when searching an array using linear search the value
to be searched is equal to the first element of the array?
(a) Worst case (b) Average case (c) Best case (d) Amortized case
4. A card game player arranges his cards and picks them one by one. With which sorting
technique can you compare this example?
(a) Quick Sort sort (b) Selection sort (c) Merge sort (d) Insertion sort
5. In which sorting, consecutive adjacent pairs of elements in the array are compared with
each other?
(a) Quick Sort sort (b) Selection sort (c) Insertion sort (d) Radix sort
6.Performance of the linear search algorithm can be improved by using abinary search
. algorithm
8. Sorting means .
C. Its performance depends on the position of the search element in the array
15. It is not a good idea to use binary search to find a value in a sorted linked list of values.
Why?
A. Binary search may not work for a linked list
B. Binary search using a linked list would usually be much slower than Linear search
C. It is not possible to sort a linked list, but sorted data is needed for binary search.
D. Linked list uses dynamic memory allocation. So the number of items are not known.
16. Which of the following case does not exist in complexity theory
A. Best case B. Worst case C. Average case D. Null case
D. When Item is the last element in the array or is not there at all
B. Merging
C. Inserting
D. Traversal
20. Finding the location of the element with a given value is:
A. Traversal B. Search C. Sort D. None of above
21. If the given input array is sorted or nearly sorted, which of the following algorithm gives
the best performance?
A. Insertion sort B. Selection sort C. Quick Sort sort
22. The number of swappings needed to sort the numbers 8, 22, 7, 9, 31, 19, 5, 13 in
ascending order using Quick Sort sort is
A. 11 B. 14 C. 13 D. 12
23. You have to sort a list L consisting of a sorted list followed by a few "random" elements.
Which of the following sorting methods would be especially suitable for such a task?
A. Quick Sort sort B. Selection sort C. Quick sort D. Insertion sort
UNIT-IV
1. If the sequence of operations - push(1), push(2), pop, push(1), push(2), pop, pop, pop,
push(2),pop are performed on a stack, the sequence of popped out values are:
a. 2 2 1 1 2
b. 2 2 1 2 2
c. 2 1 2 2 1
d. 2 1 2 2 2
2. Stacks cannot be used to
a. evaluate arithmetic expression in postfix from
b. implement recursion
c. convert given arithmetic expression in infix form to its equivalent postfix form.
d. allocate resources by OS
3. Stack is used for implementing
a. recursion
b. BFS
c. DFS
d both a & c
4. X is called self referential structure. What is X?
a, Linked list
b. Stack
c. Queues
d. Graph
5. The correct pop function is
a. S -> arr [(S -> top)--]
b. S -> arr [--(S -> top)]
c. S -> arr [(S -> top)]
d. None
6. The Ackermann's function
a. has quadratic time complexity
b. has exponential time complexity
c. cant be solved iteratively
d. has logarithmic time complexity
7. Stack A has enteries a, b, c (with a on top). Stack B is empty. An entry popped out of stack
B. An entery popped out of Stack B can only be printed. In this arrangement which of the
following permutations of a, b, c is not possible?
a. b a c
b. b c a
c. c a b
d. a b c
8. Which one of the following is an application of Queue Data Structure?
A. When a resource is shared among multiple consumers.
B. When data is transferred asynchronously (data not necessarily received at
same rate as sent) between two processes
C. Load Balancing
D. All of the above
9. How many stacks are needed to implement a queue. Consider the situation where no other
data structure like arrays, linked list is available to you.
A. 1
B. 2
C. 3
D. 4
10. In a queue, the initial values of front pointer f rare pointer r should be …….. and ………..
respectively
A. -1, -1
B. 0, -1
C. 0, 0
D. -1, 0
UNIT-V
of the file.
2. #include<stdio.h>
main()
FILE *ptr;
char i;
contents of zzz.c followed by an infinite loop
ptr=fopen("zzz.c","r");
while((i=fgetch(ptr))!=EOF)
printf("%c",i);
3. There were 10 records stored in ―somefile.dat‖ but the following program printed 11
names. What went wrong?
fread reads 10 records and prints the names successfully. It
void main() will return EOF only when fread tries to read another record
{ and fails reading EOF (and returning EOF). So it prints the last
record again. After this only the condition feof(fp) becomes
struct student false, hence comes out of the while loop.
{
char name[30], rollno[6];
}stud;
FILE *fp = fopen(―somefile.dat‖,‖r‖); while(!feof(fp))
{
fread(&stud, sizeof(stud), 1 , fp);
puts(stud.name);
4. #define assert(cond)
if(!(cond)) \
(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
FILE , LINE ), abort())
void main()
{
No output
int i = 10;
if(i==0)
assert(i < 100);
else
printf("This statement becomes else for if in assert macro");
}
5. What is the problem with the following code segment? fgets returns a pointer. So the correct
end of file check is
while ((fgets(receiving array,50,file_ptr)) != EOF) ; checking for != NULL.
6. If a file is opened in r+ mode then
a) reading is possible b)writing is possible c) it will be created if it does not exist
d)appending is possible
10. ftell()
a) is a function b) gives the current file position indicator c)can be used to find
the size of a file d) none of the above
11. The fseek() function
a) needs 2 arguments b)makes rewind function unnecessary c)takes 3 arguments d)none
of the above
12.rewind function takes number of arguments
a) 1 b) 2 c) 3 d)0
20. The value returned by fopen() function when the file is not opened
a) 0 b) garbage value c) NULL d) none of the above
22. The function that is not used for random access to files is
f) a)rewind b)ftell c)fseek d)fprintf
Unit 1
Unit 3
1) Write a c program to create an array of structures to store student information and sort them
using any of the sorting algorithms.
Unit 4
Unit 5
1) Write a c program to display the contents of a file using command line arguments.
2) Write a c program to create a structure and pass the structure data to files.
3) Write a c program to perform arithmetic operations using multi file approach.
None
6. How to break down a problem into modules and approach the solution
References
a. http://www.programiz.com/c-programming
b. https://www.tutorialspoint.com/cprogramming/
c. https://en.wikibooks.org/wiki/C_Programming