CP II Sem Course File v-1
CP II Sem Course File v-1
Cheeryal (V), Keesara (M), Ranga Reddy District – 501 301 (T.S)
(AUTONOMOUS)
Computer Programming – II
COURSE FILE
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
1
S.No Contents Page No.
1 Cover Page 3
2 Syllabus copy 4
3 Vision of the Department 6
4 Mission of the Department 6
5 PEOs, POs and PSOs 7
6 Course objectives and outcomes 9
7 Brief notes on the importance of the course and how it fits into the 9
curriculum
8 Prerequisites if any 10
9 Instructional Learning Outcomes 10
Distribution List :
3)Sign : 3) Sign:
4) Date : 4) Date:
2) Sign : 1) Name :
4) Date : 3) Design :
4) Date :
2) Sign :
3) Date :
3
2. SYLLABUS
Computer Programming II
Code: 16CS1201 1st year Semester–2 L-3, C- 3
UNIT – I
Strings – Concepts, C Strings, String Input / Output functions, string manipulation functions,
arrays of strings, string / data conversion, C program examples.
Enumerated – The Type Definition (typedef), Enumerated types
Preprocessor commands, C program examples.
UNIT – II
Structure and Union Types – Structures –Declaration, initialization, accessing structures,
operations on structures, Complex structures, C program examples.
Structures in C - Structures and functions, passing structures through pointers, self
referential structures, unions, bit fields, C programming examples
UNIT – III
Sorting –selection sort, bubble sort, insertion sort and merge sort techniques (Using Arrays)
Searching - linear search, binary search, binary recursive search techniques (Using Arrays)
UNIT - IV
Linear list – singly linked list implementation, insertion, deletion and searching operations
on linear list
Stacks - Push and Pop Operations, Introduction to In-fix and Post-Fix Notation. (Arrays and
List impl.)
Queues - Enqueue and Dequeue operations. (Arrays and List impl.)
UNIT – V
File Input and Output – Concept of a file, streams, 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, C program examples.
Command line arguments, C program examples.
Program Development – Simple file, Multi-function, Multi-source files, Separate
Compilation of functions
4
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, Third Edition, B.S. Publications.
5
3. VISION OF THE DEPARTMENT
6
5. PEOs, POs & PSOs
PO 5: Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
7
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 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..
PROGRAM SPECIFIC OUTCOMES (PSOs)
PSO 1: To identify and define the computing requirements appropriate for its solution
under given constraints.
PSO 2: To follow the best practices, namely, SEI-CMM levels and 6-sigma which
varies from time to time for software development projects using open-ended
programming environments to produce software deliverables as per customer needs.
8
6. COURSE OBJECTIVES AND OUTCOMES
Course Objectives
Develop ability to
1. Understand the concepts of String Manipulation Functions using C language in
programming.
2. Introduce the structure, union, and enumerated types
3. Understand the classical approaches to sorting arrays: selection, bubble, insertion,
merge sorting; sequential and binary searching algorithms.
4. Introduce the basic concepts of lists, stacks and queues and their applications.
5. Understand the basic characteristics of text, binary files and C implementation of
file I/O using streams.
Course Outcomes
After completion of the course, student would be able to
CO1. Write and execute programs that read, write and manipulate strings using C
language program.
CO2. Use the type definition, enumerated types, define and use structures, unions in
programs using C language.
CO3. Write programs that sort data using selection, bubble, insertion techniques and
perform search mechanisms either by sequential or binary search techniques using C
language program.
CO4. Demonstrate the basic 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
9
8. PREREQUISITES IF ANY
i) Computer Programming - I.
ii) Mathematics of 10+2 helps in understanding the logic required.
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
*When the course outcome weightage is < 40%, it will be given as moderately correlated (1).
*When the course outcome weightage is > 40%, it will be given as strongly correlated (2).
POs 1 2 3 4 5 6 7 8 9 10 11 12 1 2
Computer Science
Computer Programming
CO1. Write and execute 1 2 1 1
programs that read, write
and manipulate strings
using C language program
CO2. Use the type 2 1 1 1
definition, enumerated
types, define and use
structures, unions in
10
programs using C
language
CO3. Write programs that 2 1 2 1 1
sort data using selection,
bubble, insertion
techniques and perform
search mechanisms either
by sequential or binary
search techniques using C
language program
CO4. Demonstrate the 2 1 2 1 1
basic operations of stacks
and queues using C
program.
CO5. Write programs that 2 2 1 2 1 1
read and write text, binary
files using the formatting
and character I/O functions
11
11. CLASS TIME TABLE
LUNCH
Wednesday ENG-II LAB III(LH II(LH- II(LH- H-
-221) 221) 221) 221)
M- CP-
SP(LH Libra
Thursday II(LH- II(LH-
-231)
CP-II LAB
231) 231) ry
M- M-
SP(LH Ment
Friday III(LH
-221)
II(LH- SP/ITWS LAB
-221) 221) oring
M- ENG(
SP(LH Libra
Saturday -222)
II(LH- LH- SP/ITWS LAB
222) 222) ry
Wednes
M-II M-II CP-II M-III SP SP Library
day
Thursd
SP M-III CP-II CM LAB Sports
ay
Mentori
Friday SP/ITWS LAB CP-II ENG WS
ng
Saturda
SP/ITWS LAB WS M-III M-II Library
y
12
Geethanjali College of Engineering & Technology
Department of Science & Humanities
Year/Sem/Sec: I-B. Tech-II Semester- Acad Year 2016-17, WEF:
CSE -C Section 27/12/2016
Version -
Class Incharge: Dr. J.Shankar 1 LH: 221
09.30- 10.20- 11.10- 12.00- 12.40- 2.20-
Time 1.30-2.20 3.10-4.00
10.20 11.10 12.00 12.40 1.30 3.10
Period 1 2 3 4 5 6 7
Monday SP/ITWS LAB SP M-II M-III Sports
Mentori
Tuesday CP-II LAB SP M-II WS
ng
LUNCH
Wednes
CP-II CP-II SP SP/ITWS LAB Library
day
Thursda
SP ENG M-III M-II ENG -II LAB
y
Mentori
Friday CM-LAB CP-II WS M-II
ng
Saturda
M-III ENG SP M-II CP-II CP-II Library
y
Wednes
SP/ITWS LAB M-III CP-II CP-II Sports
day
Thursda
CP-II CP-II SP M-II SP/ITWS LAB
y
Mentori
Friday M-III CP-II ENG M-II SP WS
ng
Saturda
CM LAB SP ENG WS Library
y
Period 1 2 3 4 5 6 7
H
Wednes Mentori
CM LAB WS M-II CP-II
day ng
Thursda
ITWS/SP M-III SP CP-II Library
y
Friday SP ENG WS CP-II M-II M-II Sports
Saturda
ENG SP M-III CP-II LAB Library
y
Wednes Mentori
CP-II CP-II SP SP/EWS LAB
day ng
Thursda
M-III CP-II M-II WS ENG SP Library
y
Mentori
Friday CP-II LAB SP M-III CP-II
ng
Saturda SP M-II M-II ENG-II LAB WS
14
y
LUNCH
Wedne Eng - II M-II (LH- ENGLISH II - LAB (L.H - R
(LH-236)
(LH-
236) 207 to R 210)
Library
sday 236)
Thurs CP (LH- AP (LH- WS (LH-
CP-II LAB
233) 233) 233)
Library
day
M-III M-II AP (LH-
Friday AP/EWS LAB
(LH-236) (LH-236) 236)
SPORTS
AP
Saturd M-III CP (LH- WS (LH-
(LH- CM LAB
ay (LH-236) 236) 235)
236)
Wednes
M-II M-II AP CP CP M-III Sports
day
Thursda Mentori
AP/EWS LAB CP WS AP
y ng
Friday CP CP M-II CP-II LAB Library
Saturda ENGLISH II - LAB (L.H - R 207
to R 210)
AP M-III M-II Library
y
15
09.30- 10.20- 11.10- 12.00- 12.40- 2.20-
Time 1.30-2.20 3.10-4.00
10.20 11.10 12.00 12.40 1.30 3.10
Period 1 2 3 4 5 6 7
ENGLISH II - LAB (L.H - R Mentori
Monday M-II CP-1I WS
206) ng
Tuesday AP M-II M-II M-III CP-1I CP-1I Library
LUNCH
Wednes
M-III ENG CP-1I M-II CP-II LAB
day
Thursda Mentori
ENG AP M-III AP/EWS LAB
y ng
Friday AP AP CP-1I CM LAB Library
Saturda
EWS/AP LAB M-II AP WS Sports
y
Wednes
day CP-1I AP M-III ENG CM LAB
Thursda Mentori
y M-II M-II AP CP-1I CP-1I WS ng
ENGLISH II - LAB (L.H - R 207
Friday to R 210) M-II ENG WS Sports
Saturda
y M-III AP M-II EWS/AP LAB Library
Mentori
Tuesday M-II M-II CP-II CP-II WS AP
ng
Wednes Mentori
AP/EWS LAB AP CP-II M-III
day ng
16
Thursda ENGLISH II - LAB (L.H - R
AP M-II CP-II Library
y 206)
Friday ENG AP M-III AP/EWS LAB Sports
Saturda
CP- II LAB ENG CP-II M-II Library
y
LUNCH
Wednesd
CSE B CSE A CSE A
ay
Thursda
CSE A CSE B CSE A (Lab)
y
Friday CSE B
Saturday Campus connect Prog.
Wednesd
CSE C CSE C CSE D CSE D
ay
Thursda
CSE D CSE D
y
Friday CSE D CSE C
Saturday CSE C CSE C
Wednesd
ECE C ECE C (CP Lab)
ay
Thursda
y
Friday ECE C
Saturday
ECE
Monday ECE D ( CP Lab)
D
ECE
Tuesday ECE E ECE E
D
17
Wednesd
ECE D ECE E
ay
Thursday ECE D ECE D ECE E
Friday
Saturday ECE E (CP Lab) ECE E
Hare
Krishna
09.30- 10.20- 11.10- 12.00- 12.40- 1.30- 2.20- 3.10-
Time
10.20 11.10 12.00 12.40 1.30 2.20 3.10 4.00
Period 1 2 3 4 5 6 7
Monday CSE E ECE A ECE A
Tuesday ECE A CSE E
LUNCH
Wednesday CSE E (CP Lab) CSE E
Thursday ECE A (CP Lab) ECE A
Friday CSE E
CSE
Saturday ECE A
E
Rad
ha
3.10
09.30- 10.20- 11.10- 12.00- 12.40- 1.30-
Time 2.20-3.10 -
10.20 11.10 12.00 12.40 1.30 2.20
4.00
Peri
1 2 3 4 5 6 7
od
Mon
EEE A EEE B
day
Tues
EEE A
day
LUNCH
Wed
nesd EEE B EEE B EEE A
ay
Thur
EEE B EEE A
sday
Frid
EEE B (CP Lab) EEE A EEE B
ay
Satu
EEE A (CP Lab)
rday
Rajaku
mari
3.10
09.30- 11.10- 12.00- 1.30- 2.20-
Time 10.20-11.10 12.40-1.30 -
10.20 12.00 12.40 2.20 3.10
4.00
Period 1 2 3 4 5 6 7
Monda
y
Tuesda
y
LUNCH
Wedne
ECE B ECE B
sday
Thursd
ECE B
ay
Friday ECE B ECE B ECE B (CP Lab)
Saturd
ay
18
13. LECTURE SCHEDULE WITH METHODOLOGY BEING USED / ADOPTED
Tot: 13
1 Introduction to Sorting Regular BB
III 1 Selection Sort Regular BB
1 Bubble Sort Regular BB
1 Insertion Sort Regular BB
1 Merge Sort Regular BB
1 Introduction to searching Regular BB
1 Linear Search
1 Binary Search Regular BB
1 Binary Search (Recursive) Regular BB
Tot: 8
19
1 Introduction to Lists Regular BB
5 Singly Linked List: Insertion, Deletion Regular BB
Searching
IV
1 Introduction to Stacks Regular BB
1 Stack Operations Regular BB
2 Stack notations : Infix, Postfix Regular BB
2 Infix, Postfix conversions Regular BB
20
14. DETAILED NOTES
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.
String Declaration
Whenever we declare a String then 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. Unsized Array : Array Length is not specified while initializing character array using
this approach
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
21
1. In this method we are directly assigning String to variable by writing text in double
quotes.
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
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];
22
printf("\nEnter the Name : ");
scanf("%s",name);
return(0);
}
2.getchar()
getchar() function is also one of the function which is used to accept the single character
Syntax
char ch = getchar();
Example
#include<stdio.h>
main()
{
char ch;
ch = getchar();
printf("Accepted Character : %c",ch);
}
3.gets()
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
gets(<variable-name> );
Example
#include<stdio.h>
void main()
{
char name[20];
printf("\nEnter the Name : ");
gets(name);
printf(“%s”,name);
}
23
String output functions:
C Language supports 3 output functions are there to read a string. They are
1.printf():
Syntax
printf (" Type your Message / Instruction " ) ;
and
void main()
{
char str[10];
printf("String is : %s ",str);
}
2.putchar():
putchar() is used to print one character at a time.to read more than one character write the
putchar() in loop.
Syntax
putchar (char variable name);
Example
#include< stdio.h>
void main()
{
charstring[]="This is an example string\n";
int i=0;
24
while(string[i]!='\0')
{
putchar(string[i]);
i++;
}
}
3.puts()
puts() is used to print multiple characters includeing white spaces at a time.
Syntax
puts(" Type your Message / Instruction ");
or
puts(string_Variable_name) ;
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
}
1.strlen()
strlen() function returns the length of the string. strlen() function returns integer value.
Syntax
25
variable=strlen(string or variable);
Example
char ch=”hello”
int n;
n=strlen(ch);
2.strcpy()
strcpy() function is used to copy one string to another. The Destination_String should be a
variable and Source_String can either be a string constant or a variable.
Syntax:
strcpy(Destination_String,Source_String);
3.strncpy()
strncpy() is used to copy only the left most n characters from source to destination. The
Destination_String should be a variable and Source_String can either be a string constant or a
variable.
Syntax:
strncpy(Destination_String, Source_String,no_of_characters);
4.strcat()
strcat() is used to concatenate two strings.
The Destination_String should be a variable and Source_String can either be a string constant
or a variable.
Syntax:
strcat(Destination_String, Source_String);
5.strncat()
strncat() is used to concatenate only the leftmost n characters from source with the destination
string.
The Destination_String should be a variable and Source_String can either be a string constant
or a variable.
Syntax:
strncat(Destination_String, Source_String,no_of_characters);
6.strcmp()
strcmp() function is use two compare two strings. strcmp() function does a case sensitive
26
comparison between two strings. The Destination_String and Source_String can either be a
string constant or a variable.
Syntax:
int strcmp(string1, string2);
This function returns integer value after comparison.
Value returned is 0 if two strings are equal.
If the first string is alphabetically greater than the second string then, it returns a positive
value.
If the first string is alphabetically less than the second string then, it returns a negative value
7.strncmp()
strncmp() is used to compare only left most „n‟ characters from the strings.
Syntax:
int strncmp(string1, string2,no_of_chars);
This function returns integer value after comparison.
Value returned is 0 if left most „n‟ characters of two strings are equal.
If the left most „n‟ characters of first string is alphabetically greater than the left most „n‟
characters of second string then, it returns a positive value.
If the left most „n‟ characters of first string is alphabetically less than the left most „n‟
characters of second string then, it returns a negative value
8. strcmpi()
strcmpi() function is use two compare two strings. strcmp() function does a case
insensitive comparison between two strings. The Destination_String and Source_String
can either be a string constant or a variable.
Syntax:
int strcmpi(string1, string2);
This function returns integer value after comparison.
9.strncmpi()
strncmpi() is used to compare only left most „n‟ characters from the strings. strncmpi()
function does a case insensitive comparison.
Syntax:
int strncmpi(string1, string2,no_of_chars);
This function returns integer value after comparison.
Topic:Arrays of strings
27
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.
Example:
char string_array[30][81];
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
28
printf("%s\t\t%s\n", tname[i], name[i]);
}
printf("------------------------------------------ \n");
}
5.fcvt(): Convert floating point numbers to an equivalent null terminated strings. It specifies
the equivalent number of characters after the decimal point.
/*program that converts string to its equivalent integer and floating point value*/
#include<stdio.h>
#include<stdlib.h>
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
C program examples.
29
1.C program to read line of text character by character.
#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
return0;
#include <stdio.h>
#include <ctype.h>
void main()
{
char sentence[100];
int count, ch, i;
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;
}
Typedef is a keyword that is used to give a new symbolic name for the existing name in a C
program. This is same like defining alias for the commands.
Syntax: typedef type identifier;
Where type refers to an existing data type and identifier refers to the new name given to the
data type .typedef cannot create a new type.
Example:
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:
32
Enum day {Monday,Tuesday,….Sunday};
Enum day week_st,week_end;
Week_st=Monday;
Week_end=Friday;
If(week_st==Tuesday)
Week_end=Saturday;
Preprocessor Syntax/Description
Syntax: #define
This macro defines constant value and can be any
Macro of the basic data types.
Syntax: #include<file_name>
Header file The source code of the file “file_name” is included
inclusion in the main program at the specified place.
33
UNIT-II
Structures and Union
TYPE DEFINITION (TYPEDEF)
Typedef enables us to rename existing built-in data types and use defined data types and
there by increases readability of program.
we can now declare variables of type integer using new type_name number x;
ENUMERATED TYPES
Enumerated data type offers us a way of creating our own data type.
enum-name variable-name
The values of the enum variable are integers, readability of the program is increased by using enum
instead of integers. Other common enumerated types are weekdays and months.
STRUCTURES
34
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;
};
Variables may also be declared as the structure is defined. This can be done as follows:
struct addr
{
char name[30];
char street[40];
int postalcode;
} addr_info, binfo, cinfo;
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;
INITIALIZATION
name=XYZ
street=Paradise
postalcode=500056
35
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;
};
Here the structure date is also a variable of structure student.
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
This program explains how to use structure within structure in C using normal variable.
“student_college_detail‟ structure is declared inside “student_detail” structure in this program. Both
structure variables are normal structure variables.
Please note that members of “student_college_detail” structure are accessed by 2 dot(.) operator
and members of “student_detail” structure are accessed by single dot(.) operator.
#include <stdio.h>
#include <string.h>
36
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);
return 0;
}
output
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];
};
37
struct student_detail
{
int id;
char name[20];
loat 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);
return 0;
}
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Osmania University
When the argument of a function is a structure, the entire structure is passed using call-by-value
method. Of course, this means that changes made to the contents of the structure inside the function
do not affect the structure used as the argument.
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];
---
---
};
38
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
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
{
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.
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
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.
That is
code.id
39
code.marks
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
}
The datatype is either int or unsigned int or signed int and the bit length is number of bits used.
sex 1 0 or 1
m_status 1 0 or 1
children 3 0 to 7(2(3)-1)
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 acessing bit fields is that a pointer cannot be used.It is possible to combine normal
structure elements with bit field elements.
For example:
40
struct personal
{
char name[20];
unsigned sex : 1;
unsigned age : 7;
....
....
}emp[100];
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.
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.
41
UNIT-III
Sorting –selection sort, bubble sort, insertion sort and merge sort techniques (Using Arrays)
Searching - linear search, binary search, binary recursive search techniques (Using Arrays)
Introduction To Sorting
Sorting is a technique to rearrange the elements of a list in ascending or descending order, which
can be numerical, lexicographical, or any user-defined order. Sorting is a process through which
the data is arranged in ascending or descending order. Sorting can be classified in two types;
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.
(i) SELECTION SORT :- Ex:- Selection sort algorithm, Heap Sort algorithm
(ii) INSERTION SORT :- Ex:- Insertion sort algorithm, Shell Sort algorithm
(iii) EXCHANGE SORT :- Ex:- Bubble Sort Algorithm, Quick sort algorithm
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 is 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 by imaginary wall. We find a smallest element from unsorted sub-list and swap it to the
beginning. And the wall moves one element ahead, as the sorted list is increases and unsorted list
is 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 need n-1 passes or iterations to
completely rearrange the data.
Algorithm: Selection_Sort ( A [ ] , N )
If A[ J ] < A [ POS ]
Set POS = J
End For
42
Step 5 : Swap A [ K ] with A [ POS ]
End For
Step 6 : Exit
Write a program to explain selection sort. Which type of technique does it belong.
/* program to sort elements of an array using selection sort*/
scanf("%d",&a[i]);
for(i=0;i<n;i++)
min=i;
min=j;
43
}
t=a[i];
a[i]=a[min];
a[min]=t;
OUTPUT
2. Bubble Sort:
Bubble sort method the list is divided into two sub-lists sorted and unsorted. The smallest element is
bubbled from unsorted sub-list. After moving the smallest element the imaginary wall moves one
element ahead. The In bubble sort was originally written to bubble up the highest element in the list.
But there is no difference whether highest / lowest element is bubbled. This method is easy to
understand but time consuming. In this type, two successive elements are compared and swapping is
done. Thus, step-by-step entire array elements are checked. Given a list of „n‟ elements the bubble
sort requires up to n-1 passes to sort the data.
44
Algorithm for Bubble Sort: Bubble_Sort ( A [ ] , N )
Step 3 : If ( A [ J ] <A[J–1])
End For
Step 4 : Exit
Example:
Ex:- A list of unsorted elements are: 10 47 12 54 19 23
(Bubble up for highest value shown here)
#include<stdio.h>
void main()
{
int i,n,temp,j,arr[25];
printf("Enter the number of elements in the Array: );
scanf("%d",&n);
printf("\nEnter the
elements:\n\n");
for(i=0 ; i<n ; i++)
{
printf(" Array[%d] = ",i);
scanf("%d",&arr[i]);
}
for(i=0 ; i<n ; i++)
{
for(j=0 ; j<n-i-1 ; j++)
{
if(arr[j]>arr[j+1]) //Swapping Condition is Checked
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("\nThe Sorted Array
is:\n\n"); for(i=0 ; i<n ; i++)
{
printf(" %4d",arr[i]); } }
Time Complexity of Bubble Sort :
The complexity of sorting algorithm is depends upon the number of comparisons that are made. Total
2
comparisons in Bubble sort is: n ( n – 1) / 2 ≈ n – n
2
Best case : O (n )
2
Average case : O (n )
2
Worst case : O (n )
3. Insertion Sort:
Both the selection and bubble sorts exchange elements. But insertion sort does not exchange
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]
. {Put A[j] into the sorted sequence A[1 . . j − 1]}
i←j−1
WHILE i > 0 and A[i] > key
DO A[i +1] ← A[i]
i←i−1
A[i + 1] ← key
Example: Following figure (from CLRS) shows the operation of INSERTION-SORT on the
array A= (5, 2, 4, 6, 1, 3). Each part shows what happens for a particular iteration with the value
of j 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.
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.
/*Program to sort elements of an array using insertion sort method*/
#include<stdio.h>
void main( )
{
int a[10],i,j,k,n;
scanf("%d",&n);
for (i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
k=a[i];
for(j= i-1; j>=0 && k<a[j]; j--)
a[j+1]=a[j];
a[j+1]=k;
for(i=0;i<n;i++)
printf("%d\n", a[i]);
OUTPUT:
4.Merge sort
The basic concept of merge sort is divides the list into two smaller sub-lists of approximately
equal size. Recursively repeat this procedure till only one element is left in the sub-list.After this,
various sorted sub-lists are merged to form sorted parent list. This process goes on recursively till the
original sorted list arrived.
Merge sort is based on the divide-and-conquer paradigm. Its worst-case running time has a
lower order of growth than insertion sort. Since we are dealing with sub-problems, we state each
sub-problem as sorting a sub-array A[p .. r]. Initially, p = 1 and r = n, but these values change as
we recurse through sub-problems.
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted. Otherwise,
split A[p .. r] into two sub-arrays A[p .. q] and A[q + 1 .. r], each containing about half
of the elements of A[p .. r]. That is, q is the halfway point of A[p .. r].
2. Conquer Step
Conquer by recursively sorting the two sub-arrays A[p .. q] and A[q + 1 .. r].
Combine the elements back in A[p .. r] by merging the two sorted sub-arrays A[p .. q]
and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we will define a
procedure MERGE (A, p, q, r).
Note that the recursion bottoms out when the sub-array has just one element, so that it is
trivially sorted.
To sort the entire sequence A[1 .. n], make the initial call to the procedure MERGE-SORT (A, 1, n).
MERGE-SORT (A, p, r)
#include<stdio.h>
void disp( );
msortdiv(int,int);
int a[50],n;
void main( )
int i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
disp( );
msortdiv(0,n-1);
disp( );
}
void disp( )
int i; for(i=0;i<n;i++)
printf("%d ",a[i]);
int t[50],i,j,k;
i=low; j=mid+1;
k=low;
if(a[i]>=a[j])
t[k++]=a[j++];
else t[k++]=a[i++];
while(i<=mid)
t[k++]=a[i++];
while(j<=high)
t[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=t[i];
int mid;
if(low!=high)
mid=((low+high)/2);
msortdiv(low,mid);
msortdiv(mid+1,high);
mergesort(low,mid,high);
OUTPUT:
Quick sort is based on partition. It is also known as partition exchange sorting. The basic concept of
It is also known as partition exchange sort. It was invented by CAR Hoare. It is based on partition.
The basic concept of quick sort process is pick one element from an array and rearranges the
remaining elements around it. This element divides the main list into two sub lists. This chosen
element is called pivot. Once pivot is chosen, then it shifts all the elements less than pivot to left of
value pivot and all the elements greater than pivot are shifted to the right side. This procedure of
choosing pivot and partition the list is applied recursively until sub-lists consisting of only one
element.
quicksort(q)
if length(q) ≤ 1
return q
1. It is complex method of sorting so, it is little hard to implement than other sorting methods.
1. Breaking into sub problems that are themselves smaller instances of the same type of problem.
Two types of sorting algorithms which are based on this divide and conquer algorithm :
1. Quick sort: Quick sort also uses few comparisons (somewhat more than the other two). Like
heap sort it can sort "in place" by moving data in an array.
2. Merge sort: Merge sort is good for data that's too big to have in memory at once, because its
pattern of storage access is very regular. It also uses even fewer comparisons than heap sort, and
is especially suited for data stored as linked lists.
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.
Take the next element in the list Go
to step 3
Step 5: If the flag is “element not found”
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>
void main( )
scanf("%d",&n);
scanf("%d",&a[i]);
scanf("%d",&k);
pos=linear(a,n,k);
if(pos != -1)
else
getchar( );
int i;
for(i=0;i<n;i++)
if(a[i]==k)
return(i);
return -1;
Output:-
Binary search is quicker than the linear search. However, it cannot be applied on unsorted data
structure. The binary search is based on the approach divide-and-conquer. The binary search starts
by testing the data in the middle element of the array. This determines target is whether in the first
half or second half. If target is in first half, we do not need to check the second half and if it is in
second half no need to check in first half. Similarly we repeat this process until we find target in the
list or not found from the list. Here we need 3 variables to identify first, last and middle elements.
To implement binary search method, the elements must be in sorted order. Search is performed as
follows:
Recursive Algorithm:
Binary_Search(a,key,lb,ub)
begin
Step 1: [initialization]
lb=0
ub=n-1;
Step 2: [search for the item]
Repeat through step 4 while lower bound(lb) is less than upper bound.
Step 3: [obtain the index of middle value]
mid = (lb+ub)/2
Step 4: [compare to search for item]
if(key < a[mid]) then
ub=mid-1
otherwise if( key > a[mid]) then
lb=mid+1;
otherwise if(key==a[mid]) Write “match found”
return (mid)
return Binary_Search(a,key,lb,ub)
#include<stdio.h>
void main( )
int
a[20],pos,n,k,i,lb,ub;
clrscr( );
printf("\nEnter the n
value:"); scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&k);
lb=0;
ub=n-
1;
pos=bsearch(a,k,lb,ub)
; if(pos!=-1)
else
getch( );
{
int mid;
while(ub>=lb)
mid=(lb+ub)/2;
if(k<a[mid])
ub=mid-1;
else if(k>a[mid])
lb=mid+1;
else if(k==a[mid])
return(mid);
return(bsearch(a,k,lb,ub));
return -1;
OUTPUT:
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;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&k);
pos=linear(a,n,k);
if(pos!=-1)
else
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
#include<stdio.h>
int bsearch(int [ ],int,int);
void main( )
int
a[20],pos,n,k,i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&k);
pos=bsearch(a,n,k);
if(pos!= -1)
else
getch( );
int lb=0,ub,mid;
lb=0;
while(ub>=lb)
{
mid=(lb+ub)/2;
if(k<a[mid])
ub=mid-1;
else if(k>a[mid])
lb=mid+1;
else if(k==a[mid])
return(mid);
return -1;
OUTPUT
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)
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.
(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.
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)
end;
(a)
(b)
(c)
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
(a)
(b)
(c)
(d)
Procedure:
Repeat Step 3 while the end of the list has not been reached and the node has not been
found.
Obtain the next node in the list and record its predecessor node.
If the end of the list has been reached then write node not found and return.
begin
write(‘ Underflow’);
return
while((temp x ) and
(link(temp) NULL))
begin
pred temp
temp link(temp)
end
return
avail x
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
(a)
(b)
The node which is 100th memory address will be added to free space
(ii) if x = 200
(c)
(a)
(b)
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.
Data Structure is a way of collecting and organising 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 is
of 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
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.
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 is function that call themselves are defined.
Stack uses a single pointer „top‟ to keep track of the information in the stack.
REPRESENTATION OF STACK:
Two standard methods of representing a stack are in terms of an array and a pointer
linked list which is a away 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 an 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]:
};
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
returnnull
endif
data← stack[top]
top← top -1
return data
end procedure
Implementation of this algorithm in C, is as follows −
Example
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
5 C + AB*C
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 * +
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
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^*
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.
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:
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.
Return
REAR REAR +1
FRONT 1
Return
The following is the algorithm for detecting an element from the queue.
Queue_delete( )
If FRONT =0 then
Return
K Q[FRONT]
Begin
FRONT 0
REAR 0
End
Else
FRONT FRONT +1
Return K
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;
Where, fp is file pointer to the data type “FILE”.
fp=fopen(“filename”, ”„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 writes the data into a file pointed by fp.
fprintf(fp, “text %d”,
variable_name);
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.
Opening a file is performed using the library function in the "stdio.h" header file:
fopen():
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.
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.
Commadline Arguments:
A command-line argument is the information that follows the program's name on the
command line of the operating system. Command-line arguments are used to pass
information to the program. For example, when you use a text editor, you probably specify
the name of the file you want to edit after the name of the word processing program. For
example, if you use a word processor called WP, then this line causes the file TEST to be
edited.
WP TEST
Here, TEST is a command-line argument. Your C programs may also utilize command-line
arguments. These are passed to a C program through two arguments to the main() function.
The parameters are called argc and argv. These parameters are optional and are not used
when no command-line arguments are being used.
The argc parameter holds the number of arguments on the command-line and is an integer. It
will always be at least 1 because the name of the program qualifies as the first argument. The
argv parameter is an array of string pointers. The most common method for declaring argv is
shown here.
char *argv[];
The empty brackets indicate that it is an array of undetermined length. All command-line
arguments are passed to main() as strings. To access an individual string, index argv. For
example, argv[0] points to the program's name and argv[1] points to the first argument. This
program displays all the command-line arguments that it is called with.
Ex:
#include<stdio.h>
Program Development:
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).
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.
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.
UNIT-I
2 MARKS
3 MARKS
10 MARKS
1. What are the String built in functions available? Write in detail about each one of them
with an Example?
2. The names of employees of an organization are stored in three arrays, namely, first name,
second name, and last name. Write a program to concatenate the three parts into one string to
be called name.
3. How can a list of strings be stored in a two - dimensional array? What library functions are
available to simplify string processing?
2 MARKS
1 Define a structure and state how the members of a structure are accessed with example?
Understand
6 Write the general format of sending a copy of a structure to the called function? Remember
3 MARKS
10 MARKS
1 What is the need of bit fields? Illustrate with an example the uses of bit fields in C
3 Explain with an example the process of Dynamic memory allocation using structures in C
UNIT -III
2 MARKS
3 MARKS
1. Write a C program that searches a value in a stored array using linear search.
2. Write a C-program for sorting integers in ascending order using insertion sort.
3. Write a program for recursive binary search to find the given element within array. For
What data binary search is not applicable?
4. Explain bubble sort with a c program?
5. Explain Selection Sort with a c program?
6. Explain Insertion Sort with a c program?
10 MARKS
1. Explain recursive algorithm for binary search with its timing analysis.
2. Demonstrate the insertion sort results for each insertion for the following initial
array of elements 25 6 15 12 8 34 9 18 2
3. Write a C program that searches a value in a stored array using non
recursive binary search.
4. Write a C program that searches a value in a stored array using recursive
linear search.
UNIT -IV
2 MARKS
3 MARKS
10 MARKS
UNIT-V
2 MARKS
3 MARKS
10 MARKS
2. (a) Write a program to generate prime numbers in a given range and append
them to primes data file and display the file.
(b) 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.
3. (a)Write a program that opens a file and deletes the blank spaces.
7. 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.
8. 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.
9. Write a C program to read the text file containing some paragraph. Print the first n
characters from the beginning of the file.
10. Write a program to print the output of the following format in an OUTPUT file.
Number Square Cube
2 4 8
3 9 27
UNIT-I
UNIT-II
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-III
2. Write a menu driven program where the program should get few numbers as input from the
user. Display the various sorting mechanisms, depending on user input the particular sorting
technique has to be used for sorting the elements. (use all the sorting techniques discussed).
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-1
1. What will be the output of the program
#include<stdio.h>
void main()
{
char nm*+=,‘A’,’N’,’S’,’I’,’O’,’C’,’\0’-;
int x=0;
while (nm[x] != ’\0’)
printf(“%c”, nm[x++]);
}
#include<stdio.h>
#include<string.h>
void main()
{
char x*+=”a1b2c3d4e5f6g7h8i9j0”;
int t=0;
for(t=0;x[t]!=0&&t<=strlen(x);t+2)
printf(“%c”,x*t+);
}
a) 1234567890 b)abcdefghij
c)a1b2c3d4e5f6g7h8i9j0 d) none of the above
#include<stdio.h>
void main()
{
char x*+=,‘s’,’a’,NULL-;
printf(“”/n %d”,sizeof(x));
#include<stdio.h>
#include<string.h>
void main()
{
char txt*+=”12345\0abcdef”;
printf(“%s”,txt);
}
#include<stdio.h>
#include<string.h>
void main()
{
char txt*+=”ABCDEF\0GHIJKL”;
printf(“%s%d”,txt,sizeof (txt));
}
a) ABCDEF 14 b)ABCDEFGHIJKL 14 c) ABCDEF 7 d)none of the above
7. Which of the following statement is true after execution of the following program?
int a[5]={2,3},*c;
c=a;
(*c)--;
8.What will be the resulting string after the execution of the following program?
#include<stdio.h>
#include<string.h>
main()
{
char *str1,*str2,*str3;
str1=”The capital of indiais”;
#include<stdio.h>
#include<string.h>
void main()
{
int a,*b=&a,**c=&b;
a=5;
**c=15;
*b=**c;
printf(“A=%d,B=-%d”,a,b);
}
a) A=15,B=15 b)A=15,B=5 c)A=15,B=16 D)none of the above
UNIT-II
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
#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
1. main()
{
main();
a) partition exchange sort b) partition sort c) greedy method d)divide and conquer
UNIT-IV
1. Linked lists uses __________ type of structures.
a) nested structures b) self referential structures c) simple structures d)unions
2. _________ cannot be used to represent Linked lists.
a) arrays b) structures c)unions d) all the above
3. Linked list uses __________ type of memory allocation
a) static b)random c)dynamic d)compile time
4. The functions used for memory allocation
a) malloc b)calloc c)a&b d) none of the above
5. calloc(m,n) is equivalent to
a) malloc(m*n,0) b)memset(0,m*n) c)ptr=malloc(m*n) d) malloc(m/n)
UNIT-V
b: fseek(ptr,0,SEEK_CUR);
FILE *ptr;
char i;
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?
void main()
{
struct student
{
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()
{
int i = 10;
if(i==0)
assert(i < 100);
else
printf("This statement becomes else for if in assert macro");
}
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
15. The contents of the file are lost if it is opened in _______ mode
c) a) a b)w c) w+ d)a+
16. The contents of the file are safe if it is opened in _________ mode
d) a) a b)r c) a+b d)all the above
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
g) a)rewind b)ftell c)fseek d)fprintf
Unit 1
1) Write a C Program which accepts data from the user and encrypt the data.
2) Write a c program to remove spaces from a given string
Unit 2
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.
7. 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
PERIODS
S.No Roll Number
Name of the Student
1 16R11A0597 A ABHAY
2 16R11A0598 AAKASH MUSALE
3 16R11A0599 ANJALI KAIN
4 16R11A05A0 AVUNURI SRAVAN
5 16R11A05A1 B.SWETHA
6 16R11A05A2 CHIRALA SWATHI REDDY
7 16R11A05A3 C R SRI HARI
8 16R11A05A4 CHEERNENI PRATHYUSHA
9 16R11A05A5 DAPPU BHAVANI
10 16R11A05A6 DHUMALA MEGHANA
11 16R11A05A8 JADDU ASHISH REDDY
12 16R11A05A9 K N V RAMANA
13 16R11A05B0 KANCHI BHARGAVI
14 16R11A05B1 KANDRA KONDA PREETHI
15 16R11A05B2 KANNATH MANOJ
16 16R11A05B3 KAPRABOINA GANESH
17 16R11A05B4 KARDANDU SAI KUMAR YADAV
18 16R11A05B5 KODURU MANIDEEP
19 16R11A05B6 KONDAPAKA TULASI
20 16R11A05B7 NEELI NAVEEN
21 16R11A05B8 NARRAMNENI RAHUL CHOWDARY
22 16R11A05B9 NUTIKATTU ADITYA SAI SUMANTH
23 16R11A05C0 PARANKUSHAM NIVEDITHA
24 16R11A05C1 PENTI MANISHA
25 16R11A05C2 PODUGU BAAVANA
26 16R11A05C3 POLAGOUNI SAI TEJA GOUD
27 16R11A05C4 POTHU SAHITHYA
28 16R11A05C5 PREREPA VUTHAM
29 16R11A05C6 PURANAM LAKSHMI PRAHARSHA
1 15R11A04D3 G MANIKANTA
2 15R11A04L9 M VISHAL