C Language

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 165

Computational Thinking for

Structured Design
Dr. UPPALAPATI SRILAKSHMI
Professor, Dept. of Computer Science and Engineering-Honors -- KLHYD
KL Deemed to be UNIVERSITY
2023 – 24 Odd Sem
Course Title: Computational Thinking for Structured Design
Course Code: 22SC1101
L-T-P-S Structure: 3-0-2-4
Credits: 5.5
Course Coordinator: Dr. U. Srilakshmi

Syllabus:

Module 3: Command line arguments, CRUD operations on Basic Data Structures:


Arrays, 2-D Arrays, Dynamic Memory Allocation Searching: Linear Search and
Binary Search Sorting: Bubble Sort.

Module 4: CRUD operations on Linear Data Structures: Stacks, Queues, Single


Linked List, Introduction to nonlinear data structures.
Text Books:

1. Brian W. Kernighan, Dennis M. Ritchie, “The C Programming Language: ANSI


C Version”, 2/e, Prentice-Hall/Pearson Education-2005.
2. E. Balagurusamy, “Programming in ANSI C” 4thed.,Tata McGraw-Hill
Education, 2008. 3. R. F. Gilberg, B. A. Forouzan, “Data Structures”, 2nd
Edition, Thomson India Edition-2005.
Web Links:

1. www.hackerrank.com
2. www.codechef.com
3. www.spoj.com
4. https://leetcode.com/
5. https://codeforces.com/
CO No Course Outcome (CO)
CO1 Develop and apply logical building blocks to solve real world problems

CO2 Apply computational thinking for designing solutions


CO3 Develop and apply the CRUD operations on arrays
CO4 Apply CRUD operations on Linear Data Structures
Apply the structured programming paradigm with logic building skills on
CO5
Basic and Linear Data Structures for solving real world problems

Skill the students in such a way that students will be able to develop logic
CO6
that help them to create programs as well as applications in C
Course Outcome 3

 Data types: char, pointer, command line arguments, Dynamic Memory Allocation

 Strings and String library

 ID Arrays - creation and insertion

 Bubble sort

 Linear Search

 Binary Search

 2-D Arrays - creation and insertion

 2-D Arrays, Matrix creation and insertion

 MatrixAlgebra
Course Outcome 4

 Structures

 Array of Structures

 Structure Pointer

 Linear Data Structures Stack using arrays

 Linear Data Structures, Queue usmg arrays

 Linear Data Structures Single Linked List - using structures

 Delete operation on linked List

 Introduction to non linear data structures


Dynamic Memory Allocation in C

The concept of dynamic memory allocation in c language enables the C

programmer to allocate memory at runtime. Dynamic memory allocation in c

language is possible by 4 functions of stdlib.h header file.

 malloc()

 calloc()

 realloc()

 free()
Dynamic Memory Allocation in C
Static memory allocation Dynamic memory allocation
Memory is allocated at compile Memory is allocated at run time.
time.
Memory can't be increased while Memory can be increased while
executing program. executing program.
Used in array. Used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc()


functions.
free() frees the dynamically allocated memory.
malloc() function in C
 The malloc() function allocates single block of requested memory.

 It doesn't initialize memory at execution time, so it has garbage value initially.

 It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)
#include<stdio.h>
#include<stdlib.h>
int main() {
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc Enter elements of array: 3
Enter elements of array: 10
if(ptr==NULL) 10
{ 10
printf("Sorry! unable to allocate memory"); Sum=30

exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
calloc() function in C
 The calloc() function allocates multiple block of requested memory.

 It initially initialize all bytes to zero.

 It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)calloc(number, byte-size)
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc Enter elements of array: 3
Enter elements of array: 10
if(ptr==NULL) 10
{ 10
printf("Sorry! unable to allocate memory"); Sum=30

exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

ptr=realloc(ptr, new-size)

free() function in C

The memory occupied by malloc() or calloc() functions must be released by


calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

free(ptr)
Command Line Arguments
Command line arguments are the arguments which the user gives from the operating system’s command line during the
time of execution. Earlier, we used main() functions without arguments. These command line arguments are handled by
the main() function.
If you want to pass command line arguments then you will have to define the main() function with two arguments. The
first argument defines the number of command line arguments and the second argument is the list of command line
arguments.
Syntax
returnType_Function (*pointer_name) ( list_of_arguments)
In the above syntax, we have to specify the return type of the function such as int, void, double etc. Then, give the name to
the function pointer and then list the arguments.
Syntax
void ( *pointerToFunction ) ( int );
In the above syntax, pointerToFunction is the pointer to a function. It takes an integer argument and the return type is void.
int main(int argc, char *argv[] )
{
// body;
}
argc - It is known as argument count. It is int. It stores the number of

the command line arguments passed by a user from the terminal and

also stores the name of the program. The value of argc must not be

negative.

argv - It is a pointer array and it points to every argument which is

being passed to the program. Argv[0] denotes the name of the program.

Till argv[argc-1], every argument is a command line argument.


Command Line Arguments in C
C offers us a feature called "command line argument" using which we can enter values from the command line at the time of
execution. Command line argument is a parameter supplied to the program when it is invoked or run.
Use of Command Line arguments in C
 They are used when we need to control our program from outside instead of hard-coding it.
 They make installation of programs easier.
 Command line argument is an important concept in C programming. Command line arguments are passed to the main() method.
Syntax:
int main(int argc, char *argv[])
Here, argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds pointers of type
char which points to the arguments passed to the program.
Let's see a simple code example to check whether any command line arguments is provided to the code or not.
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc < 2)
printf("No argument supplied. The only argument here is %s", argv[0]);
return 0;
}
Example for Command Line Argument
If we want to print all the arguments in our program, we can do it as follows.
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n"); Output
for(i = 1; i < argc; i++)
{ argument list is empty.
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
Strings
A string is a sequence of character enclosed with in double quotes (“ ”) but
ends with \0. The compiler puts \0 at the end of string to specify the end of
the string.

To get a value of string variable we can use the two different types of
formats.

Using scanf() function as: scanf(“%s”, string variable);


Using gets() function as : gets(string variable);
Strings Handling Functions
C library supports a large number of string handling functions. Those
functions are stored under the header file string.h in the program.
Let us see about some of the string handling functions.
 strlen()
 strcat()
 strcmp()
 strcpy()
 strlwr()
 strrev()
 strupr()
strlen() function
strlen() is used to return the length of the string , that means counts the
number of characters present in a string.

Syntax

integer variable = strlen(string variable);


Example
#include<stdio.h> Output
#include<conio.h>
void main() Enter String:
{
Welcome
char str[20];
int strlength; Given String Length is: 7
printf(“Enter String:”);
gets(str);
strlength=strlen(str);
printf(“Given String Length is: %d”, strlength);
}
strcat() function
The strcat() is used to concatenate two strings. The second string will be
appended to the end of the first string. This process is called
concatenation.

Syntax

strcat(StringVariable1, StringVariable 2);


Example
#include<stdio.h>
Output
#include<conio.h> Enter First String:
void main()
Good
{
char str1[20],str2[20]; Enter Second String:
printf(“Enter First String:”);
Morning
scanf(“%s”,str1);
printf(“Enter Second String:”); Concatenation String is:
scanf(“%s”,str2);
GoodMorning
printf(“Concatenation String is:%s”, strcat(str1,str2));
}
strcmp() function
strcmp() function is used to compare two strings. strcmp() function does a
case sensitive comparison between two strings. The two strings are
compared character by character until there is a mismatch or end of one of
the strings is reached (whichever occurs first). If the two strings are
identical, strcmp( ) returns a value zero. If they‟re not, it returns the
numeric difference between the ASCII values of the first non-matching
pairs of characters.

Syntax

strcmp(StringVariable1, StringVariable 2);


Example
#include<stdio.h>
#include<conio.h>
Output
void main() Enter First String:
{
Good
char str1[20], str2[20];
int res; Enter Second String:
printf(“Enter First String:”);
Good
scanf(“%s”,str1);
printf(“Enter Second String:”); Concatenation String Result is:
scanf(“%s”,str2);
0
res = strcmp(str1,str2);
printf(“ Compare String Result is:%d”,res);
}
strcpy() function
strcpy() function is used to copy one string to another. strcpy() function
copy the contents of second string to first string.

Syntax

strcpy(StringVariable1, StringVariable 2);


Example
#include<stdio.h>
#include<conio.h> Output
void main() Enter First String:
{
char str1[20], str2[20]; Hello
int res; Enter Second String:
printf(“Enter First String:”);
scanf(“%s”,str1); Welcome
printf(“Enter Second String:”); First String is: welcome
scanf(“%s”,str2);
strcpy(str1,str2) Second String is: welcome
printf(“First String is:%s”,str1);
printf(“Second String is:%s”,str2);
}
strlwr() function
This function converts all characters in a given string from
uppercase to lowercase letter.

Syntax

strlwr(StringVariable);
Example
#include<stdio.h> Output
#include<conio.h> Enter String:
void main()
{ WELCOME
char str[20]; Lowercase String:
printf(“Enter String:”);
gets(str); welcome
printf(“Lowercase String : %s”, strlwr(str));
}
strrev() function
strrev() function is used to reverse characters in a given string.

Syntax

strrev(StringVariable);
Example
#include<stdio.h> Output
#include<conio.h>
Enter String:
void main()
WELCOME
{
char str[20]; Reverse String:
printf(“Enter String:”);
emoclew
gets(str);
printf(“Reverse String : %s”, strrev(str));
}
strupr() function
strupr() function is used to convert all characters in a given string from
lower case to uppercase letter.

Syntax

strupr(StringVariable);
Example
#include<stdio.h> Output
#include<conio.h>
void main() Enter String:
{
welcome
char str[20];
printf(“Enter String:”); Uppercase String:
gets(str);
WELCOME
printf(“Uppercase String : %s”, strupr(str));
}
Structures
Arrays are used for storing a group of SIMILAR data items. In order to
store a group of data items, we need structures. Structure is a constructed
data type for packing different types of data that are logically related. The
structure is analogous to the “record” of a database. Structures are used for
organizing complex data in a simple and meaningful way.
Example for structures
Student : regno, student_name, age, address
Book : bookid, bookname, author, price, edition, publisher, year
Employee : employeeid, employee_name, age, sex, dateofbirth, basicpay
Customer : custid, cust_name, cust_address, cust_phone
Structure Definition
The keyword “struct” is used for declaring a structure. In this example, book is the
name of the structure or the structure tag that is defined by the struct keyword. The
book structure has six fields and they are known as structure elements or structure
members. Remember each structure member may be of a different data type. The
structure tag name or the structure name can be used to declare variables of the
structure data type.
The syntax for structure definition is given below:
struct tagname Note:
{
Data_type member1; 1. To mark the completion of the template, semicolon is
Data_type member2; used at the end of the template.
................
2. Each structure member is declared in a separate line.
...............
};
Declaring Structure Variables
struct book
First, the structure format is defined. Then the {
variables can be declared of that structure type. int bookid;
char bookname[20];
A structure can be declared in the same way as the
variables are declared. There are two ways for char author[20];
declaring a structure variable. float price;
int year;
1) Declaration of structure variable at the time of int pages;
defining the structure (i.e structure definition and char publisher[25];
structure variable declaration are combined)
} b1,b2,b3;
The b1, b2, and b3 are structure variables of type
struct book.
2) Declaration of structure variable after defining the structure
struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};
struct book b1, b2, b3;
NOTE:
 Structure tag name is optional.
E.g.
struct
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
}b1, b2, b3;
Declaration of structure variable at a later time is not possible with this type of
declaration. It is a drawback in this method. So the second method can be
preferred.
 Structure members are not variables. They don‟t occupy memory until they
are associated with a structure variable.
Accessing Structure Members
There are many ways for storing values into structure variables. The members
of a
structure can be accessed using a “dot operator” or “period operator”.

E.g. b1.author -> b1 is a structure variable and author is a structure


member.

Syntax

STRUCTURE_Variable.STRUCTURE_Members
The different ways for storing values into structure variable is given below:

Method 1: Using Simple Assignment Statement


b1.pages = 786;
b1.price = 786.50;

Method 2: Using strcpy function


strcpy(b1.title, “Programming in C”);
strcpy(b1.author, “John”);

Method 3: Using scanf function


scanf(“%s \n”, b1.title);
scanf(“%d \n”, &b1.pages);
Example
#include<stdio.h>
#include<conio.h>
struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};
struct book b1, b2, b3;
main() {
struct book b1;
printf("Enter the Book Id: ");
scanf("%d", &b1.bookid);
printf("Enter the Book Name: ");
scanf("%s", b1.bookname);
printf("Enter the Author Name: ");
scanf("%s", b1.author);
printf("Enter the Price: ");
scanf("%f", &b1.price);
printf("Enter the Year: ");
scanf("%d", &b1.year);
printf("Enter the Total No. of Pages: ");
scanf("%d", &b1.pages);
printf("Enter the Publisher Name: ");
scanf("%s", b1.publisher);
printf("%d %s %d %f %d %d %s", b1.bookid, b1.bookname, b1.author, b1.price,
b1.year, b1.pages, b1.publisher); }
Output
Enter the Book Id: 786
Enter the Book Name: Programming
Enter the Author Name: John
Enter the Price: 123.50
Enter the Year: 2015
Enter the Total No. of Pages: 649
Enter the Publisher Name: Tata McGraw
786 Programming 2118 123.500000 2015 649 Tata
Structure Initialization
Like variables, structures can also be initialized at the compile time.
Example
main()
{
struct
{
int rollno;
int attendance;
}
s1={786, 98};
}
The above example assigns 786 to the rollno and 98 to the attendance.
Structure variable can be initialized outside the function also.
Example
main()
{
struct student
{
int rollno;
int attendance;
};
struct student s1={786, 98};
struct student s2={123, 97};
}
Note:
Individual structure members cannot be initialized within the template.
Initialization is possible only with the declaration of structure members.
Nested Structures or Structures within Structures
Structures can also be nested. i.e A structure can be defined inside another structure.
Example
struct employee
{
int empid;
char empname[20];
int basicpay;
int da;
int hra;
int cca;
} e1;
In the above structure, salary details can be grouped together and defined as
a separate structure.
Example
struct employee
{
int empid;
char empname[20];
struct
{
int basicpay;
int da;
int hra;
int cca;
} salary;
} e1;
The structure employee contains a member named salary which itself is
another
structure that contains four structure members. The members inside salary
structure can be referred as below:
e1.salary.basicpay
e1.salary.da;
e1.salary.hra;
e1.salary.cca;
However, the inner structure member cannot be accessed without the inner structure
variable.
Example
e1.basicpay
e1.da
e1.hra
e1.cca
are invalid statements
Moreover, when the inner structure variable is used, it must refer to its inner
structure member. If it doesn‟t refer to the inner structure member then it will be
considered as an error.
Array of Structures
A Structure variable can hold information of one particular record.
For example,
Single record of student or employee. Suppose, if multiple records are to be maintained, it
is impractical to create multiple structure variables. It is like the relationship between a
variable and an array.
Why do we go for an array?

Because we don’t want to declare multiple variables and it is practically impossible.


Assume that you want to store 1000 values. Do you declare 1000 variables like a1, a2,
a3…. Upto a1000? Is it easy to maintain such code ? Is it a good coding?
No. It is not.
Therefore, we go for Arrays. With a single name, with a single variable, we can store 1000
values. Similarly, to store 1000 records, we cannot declare 1000 structure variables. But we
need “Array of Structures”.
An array of structure is a group of structure elements under the same structure
variables.
struct student s1[1000];
The above code creates 1000 elements of structure type student. Each element will
be structure data type called student. The values can be stored into the array of
structures as follows:
s1[0].student_age = 19;
Example
#include<stdio.h>
#include<conio.h>
struct book
{
int bookid;
char bookname[20];
char author[20];
}; Struct b1[5];
main()
{
int i;
for (i=0;i<5;i++)
{
printf("Enter the Book Id: ");
scanf("%d", &b1[i].bookid);
printf("Enter the Book Name: ");
scanf("%s", b1[i].bookname);
printf("Enter the Author Name: ");
scanf("%s", b1[i].author);
}
for (i=0;i<5;i++)
{
printf("%d \t %s \t %s \n", b1[i].bookid, b1[i].bookname,
b1[i].author);
}
}
Output:
Enter the Book Id: 786
Enter the Book Name: Programming
Enter the Author Name: Dennis Ritchie
Enter the Book Id: 101
Enter the Book Name: Java Complete Reference
Enter the Author Name: Herbert Schildt
Enter the Book Id: 008
Enter the Book Name: Computer Graphics
Enter the Author Name: Hearn and Baker
786 Programming Dennis Ritchie
101 Java Complete Reference Herbert Schildt
008 Computer Graphics Hearn and Baker
Structure Pointer
The structure pointer points to the address of a memory block where the Structure is being stored. Like a pointer that tells
the address of another variable of any data type (int, char, float) in memory. And here, we use a structure pointer which
tells the address of a structure in memory by pointing pointer variable ptr to the structure variable.

Declare a Structure Pointer


The declaration of a structure pointer is similar to the declaration of the structure variable. So, we can declare the structure
pointer and variable inside and outside of the main() function. To declare a pointer variable in C, we use the asterisk (*)
symbol before the variable's name.
struct structure_name *ptr;
After defining the structure pointer, we need to initialize it, as the code is shown:

Initialization of the Structure Pointer


ptr = &structure_variable;
We can also initialize a Structure Pointer directly during the declaration of a pointer.
struct structure_name *ptr = &structure_variable;
Access Structure member using pointer
There are two ways to access the member of the structure using Structure
pointer.

 Using ( * ) asterisk or indirection operator and dot ( . ) operator.


 Using arrow ( -> ) operator or membership operator.

Program to access the structure member using structure pointer and the dot
operator.
// C Program to demonstrate Structure pointer
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
Output
};
Roll Number: 27
int main()
{
Name: Kamlesh Joshi
struct Student s1;
struct Student* ptr = &s1; Branch: Computer Science And Engineering
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi"); Batch: 2019
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;
printf("Roll Number: %d\n", (*ptr).roll_no);
printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);
return 0;
}
// C Program to demonstrate Structure pointer
// Displaying details of the student
#include <stdio.h>
#include <string.h> printf("\nStudent details are: \n");
// Creating Structure Student printf("Roll No: %d\n", ptr->roll_no);
struct Student {
int roll_no; printf("Name: %s\n", ptr->name);
char name[30];
printf("Branch: %s\n", ptr->branch);
char branch[40];
int batch; printf("Batch: %d\n", ptr->batch);
};
return 0;
// variable of structure with pointer defined }
struct Student s, *ptr;
Input
int main() Output
{ Enter the Roll Number of Student
ptr = &s; Student details are:
1001
// Taking inputs Roll No: 1001
Enter Name of Student
printf("Enter the Roll Number of Student\n");
aaa Name: aaa
scanf("%d", &ptr->roll_no);
Enter Branch of Student Branch: cse
printf("Enter Name of Student\n");
scanf("%s", &ptr->name); cse
Batch: 1
printf("Enter Branch of Student\n"); Enter batch of Student
scanf("%s", &ptr->branch);
1
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch);
C -A R R AY S

1/20
ARRAY S
 An array is a collection of elements of the same type that are referenced by a
common name.

 Compared to the basic data type (int, float) it is an


aggregate or derived data type.

 All the elements of an array occupy a set of contiguous memory locations.

 Why need to use array type?

 Consider the following issue:

 "We have a list of 1000 students' marks of an integer type. If


using the basic data type (int), we will declare something like
the following…"

 int studMark0, studMark1, ...studMark999


 Can you imagine how long we have to write the
declaration part by using normal variable
declaration?

int main(void)
{
int studMark1, studMark2, studMark3, studMark4, …, …,
studMark998, stuMark999, studMark1000;


return 0;
}
 By using an array, we just declare like this,

 int studMark[1000];
 This will reserve 1000 contiguous memory locations for
storing the students’ marks.
 Graphically, this can be depicted as in the following figure.
 This absolutely has simplified our declaration of the variables.

 We can use index or subscript to identify each element or location in


the memory.

 Hence, if we have an index of j, studMark[j] would refer to the jth


element in the array of studMark.

 For example, studMark[0] will refer to the first element of the array.

 Thus by changing the value of j, we could refer to any element in the


array.

 So, array has simplified our declaration and of


course, manipulation of the data.
 A single or one dimensional array declaration
has the following form,

⚫ array_element_data_type array_name[array_
size];

 Here, array_element_data_type defines the base type of the array,


which is the type of each element in the array.
 array_name is any valid C identifier name that obeys the same
rule for the identifier naming.
 array_size defines how many elements the array
will hold.
 For example, to declare an array of 30 characters, that
construct a people name, we could declare,
⚫ char cName[30];
 Which can be depicted as follows,

 In this statement, the array character can store up to


30 characters with the first character occupying
location cName[0] and the last character occupying
cName[29].

 Note that the index runs from 0 to


29. In C , an index always starts from 0 and ends
with array's (size-1).

 So, take note the difference between the array size and
subscript/index terms.
 Examples of the one-dimensional array declarations,
 int xNum[20], yNum[50];
 float fPrice[10], fYield;
 char chLetter[70];
 The first example declares two arrays named xNum and yNum of type int.
Array xNum can store up to 20 integer numbers while yNum can store up to 50
numbers.

 The second line declares the array fPrice of type float. It


can store up to 10 floating-point values.

 fYield is basic variable which shows array type can be declared together with
basic type provided the type is similar.

 The third line declares the array chLetter of type char. It can store a string
up to 69 characters.

 Why 69 instead of 70? Remember, a string has a null terminating character (\0) at
the end, so we must reserve for it.
A R R AY I N I T I A L I Z AT I O N
 An array may be initialized at the time of declaration.

 Initialization of an array may take the following form,


 type array_name[size] = {a_list_of_value};
 For example:
 int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
 float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
 char '\ chVowel[6] = {'a', 'e', 'i', 'o', 'u',
0'};
 The first line declares an integer array idNum and it immediately assigns the values 1, 2,
3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively.

 The second line assigns the values 5.6 to


fFloatNum[0], 5.7 to fFloatNum[1], and so on.

 Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1], and
so on. Note again, for characters we must use the single apostrophe/quote (') to enclose
them.
 Also, the last character in chVowel is NULL character ('\0').
 Initialization of an array of type char for holding strings
may take the following form,
⚫ char array_name[size] = "string_lateral_constant";

 For example, the array chVowel in the previous example


could have been written more compactly as follows,
⚫ char chVowel[6] = "aeiou";

 When the value assigned to a character array is a string (which must be


enclosed in double quotes), the compiler automatically supplies the NULL
character but we still have to reserve one extra place for the NULL.
 For unsized array (variable sized), we can declare as
follow,
⚫ char chName[ ] = "Mr. Dracula";

 C compiler automatically creates an array which is big enough to hold all the
initializer.
R E T R I E V I N G A R R AY E L E M E N T S
 If you want to retrieve specific element then then you have to
specify not only the array or variable name but also the index
number of interest.

 For example:
 int Arr[]={1,3,5,6,8};

 printf(“%d\t%d\n”,Arr[1],Arr[2]);

 Output: 3 5
A R R AY E X A M P L E
 Take 10 integer input from user and store then in an
array and find the sum of all numbers stored in array.

#include<stdio.h>
int main(){
int i,sum=0,arr[10]; for(i=0;i<10;i++)
scanf(“%d”,&arr[i]);
for(i=0;i<10;i++)
sum+=arr[i];
printf(“Sum of input integers is %d\n”,sum);
return 0;
}
Summarize the response of a survey.
Input: Response of the survey, can be in the range between 0 and 10.
Assume the population size to be 40.
Output: Frequency of each response.
 #include<stdio.h>
 #define S I Z E 40
 #define A N S 11

 int main(void) {
 int response[SIZE];
 int freq[ANS] = {0};
 int i;
 for(i=0; i< SIZE; i++){
 scanf(“%d”,&response[i]);
 ++freq[response[i]];
 }

 for(i=0;i<ANS;i++)
 printf("Frequency of %d is %d\n",i,freq[i]);
 }
ASSIGNMENT
 Read from user ages of all students in class and save them in an
array which can store floating point and find average, minimum
and maximum age.
 A six faced die is rolled 600 times. Find the
frequency of the occurrence of each face?
 int rand(void): returns a pseudo-random
number in the range of 0 to R A N D _ M A X .
 R A N D _ M A X : is a constant whose default value may vary
between implementations but it is granted to be at least 32767.
 Issue: If we generate a sequence of random number with rand()
function, it will create the same sequence again and again every
time program runs.
 The srand() function sets the starting point for producing a series
of pseudo-random integers. If srand() is not called, the rand() seed
is set as if srand(1) were called at program start.
 The pseudo-random number generator should only be seeded once,
before any calls to rand(), and the start of the program.
 Standard practice is to use the result of a call
to srand(time(0)) as the seed. However, time()
returns a time_t value which vary everytime and hence the
pseudo-random number vary for every program call.
#include<stdio.h>

int main(){
int i,j,arr[7]={0};
srand(time(0));
for (i=0;i<600;i++){ j=rand()%6; j=j+1;
arr[j]++;
}
for(i=1;i<=6;i++)
printf("%d came out for %d times\n",i,arr[i]);
return 0;
}
[sourav@gaya]$ ./a.out 1 came
out for 113 times 2 came out for
114 times 3 came out for 102
times 4 came out for 86 times 5
came out for 99 times 6 came
out for 86 times
ASSIGNMENT

 Store marks obtained by students in an array. Find if there is more


than one student who scored same marks. Assume minimum
marks obtained is 30 and maximum marks obtained is 85.
#include<stdio.h>

int main(){
int i,j,x,arr[10];

printf("Enter 10 integer number\n"); for(i=0;i<10;i++){


scanf("%d",&arr[i]);
}

for(i=0;i<9;i++){
x=arr[i]; for(j=i+1;j<10;j++){
if(x==arr[j])
printf("%d number appeared more than once\n",x);
}
}
return 0;
}
[sourav@gaya]$ ./a.out Enter 10 integer
number 1
2
3
4
5
6
2
4
8
9
2 number appeared more than once
4 number appeared more than once
T WO D I M E N S I O N A L / 2 D A R R AY S

 A two dimensional array has two subscripts/indexes.


 The first subscript refers to the row, and the second, to the
column.
 Its declaration has the following form,

⚫ data_type array_name[1st dimension size][2nd dimension size];

 For examples,

⚫ int xInteger[3][4];
⚫ float matrixNum[20][25];

 The first line declares xInteger as an integer array with 3 rows and 4 columns.
 Second line declares a matrixNum as a floating-point array with 20 rows and 25
columns.
D O U B L E S C R I P T E D ARRAY WITH 3 ROWS A N D 4
COLUMNS
 #include <stdio.h>
 int main() {
⚫ int abc[5][4] ={ {0,1,2,3}, {4,5,6,7}, {8,9,10,11},
{12,13,14,15}, {16,17,18,19} };
⚫ for (int i=0; i<=4; i++) {
 printf("%d ",abc[i]);
⚫ }
⚫ return 0;
 }
 Output: 1600101376 1600101392 1600101408
1600101424 1600101440
L I ST O F S T U D E N T S A N D T H E I R S U B J E C T
MARKS

Marks
Students 10 23 31 11
20 43 21 21
12 22 30 13
30 31 26 41
13 03 41 15

Find the average mark scored by each student?


#include<stdio.h> #define ROW 5
#define C O L 4

int main(void)
{
int i, j;
double total;
int marks[ROW][COL]= { 10, 23, 31, 11, 20, 43, 21, 21,12,
22, 30, 13, 30, 31, 26, 41,13, 03, 41, 15 };
for(i = 0; i < ROW ; i++)
{
total = 0.0;
for (j=0; j<COL; j++)
total+=marks[i][j];
printf("Average of student %d is %f \n", i, total/4.0);
}
}
I N I T I A L I Z AT I O N O F 2D A R R AY

 int disp[2][4] = { {10, 11, 12, 13}, {14, 15, 16, 17} };

 OR

 int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};

 1st one is recommended.


T H I N G S THAT YO U M U S T C O N S I D E R W H I L E I N I T I A L I Z I N G
A 2D A R R AY

 We already know, when we initialize a normal array (or you can say one
dimensional array) during declaration, we need not to specify the size of it.
However that’s not the case with 2D array, you must always specify the second
dimension even if you are specifying elements during the declaration.

 /* Valid declaration*/
 int abc[2][2] = {1, 2, 3 ,4 }
 /* Valid declaration*/
 int abc[][2] = {1, 2, 3 ,4 }
 /* Invalid declaration – you must specify second dimension*/
 int abc[][] = {1, 2, 3 ,4 }
 /* Invalid because of the same reason mentioned above*/
 int abc[2][] = {1, 2, 3 ,4 }
 For array storing string

⚫ char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole", "Kidman",


"Arnold", "Jodie"};

 Here, we can initialize the array with 6 strings, each with maximum 9
characters long.
 If depicted in rows and columns it will look something like the following and
can be considered as contiguous arrangement in the memory.
ASSIGNMENTS
 Print Transpose of a Matrix

 Add Two Matrix Using Multi-dimensional Arrays

 Multiply to Matrix Using Multi-dimensional Arrays


#include <stdio.h>

void main()
{
static int array[10][10]; int i, j, m, n;
printf("Enter the order of the matrix \n ");
scanf("%d %d", &m, &n);

printf("Enter the coefiicients of the matrix \n "); for (i = 0; i < m;


++i){
for (j = 0; j < n; ++j){ scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n ");
for (i = 0; i < m; ++i){
for (j = 0; j < n; ++j){ printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n ");
for (j = 0; j < n; ++j){
for (i = 0; i < m; ++i){ printf(" %d", array[i][j]);
}
printf("\n");
}
}
#include <stdio.h>
int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter number of columns (between 1 and 100): "); scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j) {
printf("Enter element a%d%d: ",i+1,j+1); scanf("%d",&a[i][j]);
}
}
printf("Enter elements of 2nd matrix:\n"); for(i=0; i<r; +
+i)
for(j=0; j<c; ++j) {
printf("Enter element a%d%d: ",i+1, j+1); scanf("%d", &b[i]
[j]);
}
// Adding Two matrices for(i=0;i<r;++i)
for(j=0;j<c;++j) { sum[i][j]=a[i][j]+b[i][j];
}
// Displaying the result
printf("\nSum of two matrix is: \n\n"); for(i=0;i<r;++i)
for(j=0;j<c;++j) {
printf("%d ",sum[i][j]);
if(j==c-1) { printf("\n\n"); }
}
return 0;
}
 #include <stdio.h>
 int main() {
⚫ int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
⚫ printf("Enter rows and column for first matrix: ");
⚫ scanf("%d %d", &r1, &c1);
⚫ printf("Enter rows and column for second matrix: ");
⚫ scanf("%d %d",&r2, &c2);
⚫ while (c1 != r2) {
 printf("Error! Not compatible for multiplication\n");
⚫ }
⚫ printf("\nEnter elements of matrix 1:\n");
⚫ for(i=0; i<r1; ++i)
 for(j=0; j<c1; ++j) {
 printf("Enter elements a%d%d: ",i+1, j+1);

 scanf("%d", &a[i][j]);

 }

⚫ printf("\nEnter elements of matrix 2:\n");


⚫ for(i=0; i<r2; ++i)
 for(j=0; j<c2; ++j) {
 printf("Enter elements b%d%d: ",i+1, j+1); scanf("%d",&b[i][j]);

 }
⚫ // Initializing all elements of result matrix to 0
⚫ for(i=0; i<r1; ++i)
 for(j=0; j<c2; ++j) {
 result[i][j] = 0;

 }

⚫ // Multiplying matrices a and b and // storing result in result matrix


for(i=0; i<r1; ++i)
 for(j=0; j<c2; ++j)
 for(k=0; k<c1; ++k) {

⚫ result[i][j]+=a[i][k]*b[k][j];
 }
⚫ // Displaying the result
⚫ printf("\nOutput Matrix:\n");
⚫ for(i=0; i<r1; ++i)
 for(j=0; j<c2; ++j) {
 printf("%d ", result[i][j]);

 if(j == c2-1) printf("\n\n");

 }

⚫ return 0;
 }
3 D : A 3D A RRAY I S A N ARRAY O F 2D
A RRAYS .
 #include<stdio.h>
 int main(){
 int
i,j,k,x[][2][3]={{{1,2,3},{4,5,6}},{{7,8,9},{10,11,12}}};
 for(i=0;i<2;i++)
 for(j=0;j<2;j++)
 for(k=0;k<3;k++){

printf("x[%d,%d,%d]=%d\n",i,j,k,x[i][j][k]);
 }
 return 0;
 }
Searching

Searching is a process of finding out a particular


element in a list of ‘n’ elements
Methods of Searching
• Linear Search (Sequential Search)
• Binary Search
Linear Search(Sequential Search)
In a linear search, we start at the top of the list, and compare the
element there with the key

If we have a match, the search terminates and the index number


is returned
Linear Search

Comparison = 05
Linear Search

No of Comparisons = 11
Binary Search

• A binary search is a divide and conquer


algorithm
In a binary search, we look for the key in the middle of the list
If we get a match, the search is over
If the key is greater than the thing in the middle of the list, we
search the top half
If the key is smaller, we search the bottom half
Binary Search

Beg = 0
End = 6
0 1 2 3 4 5 6 Mid = 0+6/2
6 13 14 25 33 43 51
Search Element = 25
If(key==a[mid]
Binary Search

Beg = 0
End = 6
0 1 2 3 4 5 6 Mid = 0+6/2
6 13 14 25 33 43 51
Search Element = 13

If 13 < a[mid] then search in the left side.

Beg = 0
End = mid – 1
Mid = 0+2/2
Binary Search

Beg = 0
End = 6
0 1 2 3 4 5 6 Mid = 0+6/2
6 13 14 25 33 43 51

If key > a[mid]


Beg = mid+1
End = 6
Mid = 4+6/2
Difference between linear and binary search
• Linear Search • Binary Search
1. Data can be in any order. 1. Data should be in a sorted order.
2. Multidimensional array also can be used. 2. Only single dimensional array is used.
3.TimeComplexity:- 3. Time Complexity:- O(log n 2)
O( n) 4. Efficient for large inputs also.
4. Not an efficient method to be used if
there is a large list.
Application of Searching
Sorting (Bubble Sort)
5 4 4 4 4
4 5 3 3 3
3 3 5 2 2
2 2 2 5 1
1 1 1 1 5

1
2
3
4
5
Stack & Queue

Stack Queue
* Basic principles * Basic principles
* Operation of stack * Operation of queue
* Stack using Array * Queue using Array
* Stack using Linked List * Queue using Linked List
* Applications of stack * Applications of queue
Stack
A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of
plates, etc.
Stack Representation

• Can be implemented by means of Array, Structure, Pointers and Linked List.


• Stack can either be a fixed size or dynamic.
push

pop

create
STACK
isempty

isfull
STACK: Last-In-First-Out (LIFO)
• void push (stack *s, int element);
/* Insert an element in the stack */
• int pop (stack *s);
/* Remove and return the top element */
• void create (stack *s);
/* Create a new stack */
• int isempty (stack *s);
/* Check if stack is empty */
• int isfull (stack *s);
/* Check if stack is full */

Assumption: stack contains integer elements!


Stack using Array
Push using Stack

PUSH

top
top
Pop using Stack

POP

top
top
Stack using Linked List

Push using Linked List

top

PUSH OPERATION
Pop using Linked List

POP OPERATION

top
Basic Idea
• In the array implementation, we would:
• Declare an array of fixed size (which determines the maximum size of the stack).
• Keep a variable which always points to the “top” of the stack.
• Contains the array index of the “top” element.
• In the linked list implementation, we would:
• Maintain the stack as a linked list.
• A pointer variable top points to the start of the list.
• The first element of the linked list is considered as the stack top.
Declaration

#define MAXSIZE 100 struct lifo


{
struct lifo int value;
{ struct lifo *next;
int st[MAXSIZE]; };
int top; typedef struct lifo
}; stack;
typedef struct lifo
stack; stack *top;
stack s;

ARRAY LINKED LIST


Stack Creation

void create (stack *s) void create (stack **top)


{ {
s->top = -1; *top = NULL;
/* s->top points to /* top points to NULL,
last element indicating empty
pushed in; stack */
initially -1 */ }
}

ARRAY LINKED LIST


Pushing an element into stack

void push (stack *s, int element) void push (stack **top, int element)
{ {
if (s->top == (MAXSIZE-1)) stack *new;
{ new = (stack *)malloc (sizeof(stack));
printf (“\n Stack overflow”); if (new == NULL)
exit(-1); {
} printf (“\n Stack is full”);
else exit(-1);
{ }
s->top++; new->value = element;
s->st[s->top] = element; new->next = *top;
} *top = new;
} }

ARRAY LINKED LIST


Popping an element from stack

int pop (stack **top)


{
int pop (stack *s) int t;
{ stack *p;
if (s->top == -1) if (*top == NULL)
{ {
printf (“\n Stack underflow”); printf (“\n Stack is empty”);
exit(-1);
exit(-1); }
} else
else {
{ t = (*top)->value;
p = *top;
return (s->st[s->top--]); *top = (*top)->next;
} free (p);
} return t;
}
}

ARRAY LINKED LIST


Checking for stack empty

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST


Checking for Stack Full

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST


Example: A Stack using an Array
#include <stdio.h>
#define MAXSIZE 100
struct lifo
{
int st[MAXSIZE];
int top;
};
typedef struct lifo stack;
main() {
stack A, B;
create(&A);
create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100);
push(&B,5);
printf (“%d %d”, pop(&A), pop(&B));
push (&A, pop(&B));
if (isempty(&B))
printf (“\n B is empty”);
return;
}
Example: A Stack using Linked List
#include <stdio.h>
struct lifo
{
int value;
struct lifo *next;
};
typedef struct lifo stack;
main() {
stack *A, *B;
create(&A);
create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100);
push(&B,5);
printf (“%d %d”, pop(&A), pop(&B));
push (&A, pop(&B));
if (isempty(B))
printf (“\n B is empty”);
return;
}
Applications of Stacks
• Direct applications:
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Chain of method calls in the Java Virtual Machine
• Validate XML

• Indirect applications:
• Auxiliary data structure for algorithms
• Component of other data structures
Queue
• Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open
at both its ends. One end is always used to insert data (enqueue) and the other is used to remove
data (dequeue).
Queue Representation

• As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and
Structures.
Queue

In real life, a Queue is a line or sequence of people or vehicles or any objects awaiting their turn to be attended to or to proceed. Let’s consider the below real-time examples.

A queue of people waiting for their turn to come to take money from the ATM machine,

A queue of vehicles waiting for the traffic signal to turn green,

A queue of people waiting to buy tickets in a railway station or movie theater.

etc.
enqueue

dequeue

create
QUEUE
isempty

size
QUEUE: First-In-First-Out (LIFO)
void enqueue (queue *q, int element);
/* Insert an element in the queue */
int dequeue (queue *q);
/* Remove an element from the queue */
queue *create();
/* Create a new queue */
int isempty (queue *q);
/* Check if queue is empty */
int size (queue *q);
/* Return the no. of elements in queue */

Assumption: queue contains integer elements!


Queue using Linked List
• Basic idea:
• Create a linked list to which items would be added to one end and deleted from the other
end.
• Two pointers will be maintained:
• One pointing to the beginning of the list (point from where elements will be deleted).
• Another pointing to the end of the list (point where new elements will be inserted).
Rear

Front DELETION INSERTION


Queue: Linked List Structure

ENQUEUE

front rear
Queue: Linked List Structure

DEQUEUE

front rear
Example :Queue using Linked List
struct qnode
{
int val;
struct qnode *next;
};

struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;

void enqueue (QUEUE *q,int element)


{
struct qnode *q1;
q1=(struct qnode *)malloc(sizeof(struct qnode));
q1->val= element;
q1->next=q->qfront;
q->qfront=q1;
}
Example :Queue using Linked List
int size (queue *q)
{
queue *q1;
int count=0;
q1=q;
while(q1!=NULL) int dequeue (queue *q)
{ {
q1=q1->next; int val;
count++; queue *q1,*prev;
} q1=q;
return count; while(q1->next!=NULL)
} {
prev=q1;
q1=q1->next;
}
val=q1->val;
int peek (queue *q) prev->next=NULL;
{ free(q1);
queue *q1; return (val);
q1=q; }
while(q1->next!=NULL)
q1=q1->next;
return (q1->val);
}
Problem With Array Implementation

• The size of the queue depends on the number and order of enqueue and dequeue.
• It may be situation where memory is available but enqueue is not possible.

ENQUEUE DEQUEUE
Effective queuing storage area of array gets reduced.
0 N

frontfront rear rear

Use of circular array indexing


Applications of Queues
• Direct applications:-
• Waiting lists
• Access to shared resources (e.g., printer)
• Multiprogramming

• Indirect applications:-
• Auxiliary data structure for algorithms
• Component of other data structures
Single Linked List
 In array, elements are stored in consecutive memory locations.

 To occupy the adjacent space, block of memory that is required for the array
should be allocated before hand.

 Once memory is allocated, it cannot be extended any more. So that array is


called the static data structure.

 Wastage of memory is more in arrays.

 Array has fixed size

 But, Linked list is a dynamic data structure, it is able to grow in size as


needed.
What is Linked List?
 A linked list is a linear collection of homogeneous data elements,
called nodes, where linear order is maintained by means of links or
pointers.

 Each node has two parts:


 The first part contains the data (information of the element) and
 The second part contains the address of the next node (link /next pointer field) in the list.

 Data part of the link can be an integer,


a character, a String or an object of any kind.
node

link

data

Start Null

A B C D
Linked Lists
 Linked list

– Linear collection of self-referential structures, called nodes, connected by pointer links.

– Accessed via a pointer to the first node of the list.

– Subsequent nodes are accessed via the link-pointer member stored in each node.

– Link pointer in the last node is set to null to mark the end of list.

– Data stored dynamically – each node is created as necessary.

– Length of a list can increase or decrease.

– Becomes full only when the system has insufficient memory to satisfy dynamic storage allocation
requests.
Types of linked lists
– Singly linked list
• Begins with a pointer to the first node
• Terminates with a null pointer
• Only traversed in one direction

– Circular, singly linked list


• Pointer in the last node points back to the first node

– Doubly linked list


• Two “start pointers”- first element and last element
• Each node has a forward pointer and a backward pointer
• Allows traversals both forwards and backwards

– Circular, doubly linked list


• Forward pointer of the last node points to the first node and backward pointer of the first node
points to the last node
Dynamic Memory Allocation

 Dynamic memory allocation


– Obtain and release memory during execution
• malloc
– Takes number of bytes to allocate
• Use sizeof to determine the size of an object
– Returns pointer of type void *
• A void * pointer may be assigned to any pointer
• If no memory available, returns NULL
– newPtr = malloc( sizeof( struct node ) );
• free
– Deallocates memory allocated by malloc
– Takes a pointer as an argument
– free (newPtr);
Self-Referential Structures
• Self-referential structures
– Structure that contains a pointer to a structure of the same type
– Can be linked together to form useful data structures such as lists, queues, stacks and trees
– Terminated with a NULL pointer (0)

• Two self-referential structure objects linked together

15 10

Data member and NULL pointer (points to


pointer nothing)
Singly linked list operations

Insertion:
• Insertion of a node at the front
• Insertion of a node at any position in the list
• Insertion of a node at the end

Deletion:
• Deletion at front
• Deletion at any position
• Deletion at end

Display:
• Displaying/Traversing the elements of a list
Singly linked lists
Node Structure

struct node
2000
{
int data; new
struct node *link;
}*new, *ptr, *header, *ptr1;
data link

10 NULL
Creating a node

new = malloc (sizeof(struct node));


2000
new -> data = 10;
new -> link = NULL;
Inserting a node at the beginning
Create a node that is to be inserted
2500
new
data link Algorithm:
1. Create a new node.
10 NULL 2. if (header = = NULL)
2500 3. header = new;
4. else
5. {
If the list is empty 6. new -> link = header;
7. header = new;
NULL 8. }
header header

If the list is not empty

1200
2500 header
new
5 1300 5 1330 4 1400 8 NULL
10 NULL 1200 1300 1330 1400
2500
header Inserting a node at the end
1500

10 1800 20 1200 30 1400 40 NULL

1400
1500 1800 1200

ptr 50 NULL

2000

Algorithm:
new
1. new=malloc(sizeof(struct node));
2. ptr = header; 2000
3. while(ptr -> link!= NULL)
4. ptr = ptr -> link;
5. ptr -> link = new;
Inserting a node at the given position
header ptr
1800
1500 1500 Insert position : 3

2000

10 1800 20 1200 30 1400 40 NULL


1400
1500 1800 1200

1200
50
new NULL Algorithm:
1. new=malloc(sizeof(struct node));
2000
2000 2. ptr = header;
3. for(i=1;i < pos-1;i++)
4. ptr = ptr -> link;
5. new -> link = ptr -> link;
6. ptr -> link = new;
Deleting a node at the beginning
header ptr

18001500 1500

10 1800 20 1200 30 1400 40 NULL


1400
1500 1800 1200

Algorithm:
1. if (header = = NULL)
2. print “List is Empty”;
3. else
4. {
5. ptr = header;
6. header = header -> link;
7. free(ptr);
8. }
header
Deleting a node at the end
ptr1 ptr1 ptr1
1500

NULL
10 1800 20 1200 30 40 NULL
1400
1400
1500 1800 1200

ptr

1500 1800 1400

1200 Algorithm:
1. ptr = header;
2. while(ptr -> link != NULL)
3. ptr1=ptr;
4. ptr = ptr -> link;
5. ptr1 -> link = NULL;
6. free(ptr);
Deleting a node at the given position
ptr1
header ptr
1800 1200
1500 1500 Insert position : 3

1400
10 1800 20 1200 30 1400 40 NULL
1400
1500 1800 1200

Algorithm:
1. ptr = header ;
2. for(i=1;i<pos-1;i++)
3. ptr = ptr -> link;
4. ptr1 = ptr -> link;
5. ptr -> link = ptr1-> link;
6. free(ptr1);
Traversing an elements of a list
header ptr
1500
1500

10 1800 20 1200 30 1400 40 NULL

1500 1800 1200 1400

Algorithm:
1. if(header = = NULL)
2. print “List is empty”;
3. else
4. for (ptr = header ; ptr != NULL ; ptr = ptr -> link)
5. print “ptr->data”;
/*Program to implement single linked list*/
#include<stdio.h> #include<malloc.h> #include<stdlib.h>
void traverse(); void deletion(); void insertion();
int choice,i,pos,item;
struct node {
int data;
struct node *link;
}*header,*ptr,*ptr1,*new;
void main() {
header=NULL;
ptr=header;
printf("****Menu****\n");
printf("\n 1.Insertion\n 2.Deletion\n 3.Traverse\n 4.Search\n 5.Exit\n");
while(1) {
printf("\nenter ur choice");
scanf("%d",&choice);
switch(choice) {
case 1: insertion(); break;
case 2: deletion(); break;
case 3: traverse(); break;
default: printf("\nwrong choice\n");
}/*end of switch*/
}/*end of while*/
}/*end of main*/
void insertion() {
new=malloc(sizeof(struct node));
printf("\n enter the item to be inserted\n");
scanf("%d",&item);
new->data=item;
if(header = = NULL)
{
new->link=NULL;
header=new;
}/*end of if*/
else
{
printf("\nEnter the place to insert the item\n");
printf("1.Start\n 2.Middle\n 3.End\n");
scanf("%d",&choice);
if(choice = = 1)
{
new->link=header;
header=new;
}
if(choice = = 2)
{
ptr=header;
printf("Enter the position to place an item: ");
scanf("%d",&pos);
for(i=1;i<pos-1;i++)
ptr=ptr->link;
new->link=ptr->link;
ptr->link=new;
}
if(choice = = 3)
{
ptr=header;
while(ptr->link!=NULL)
ptr=ptr->link;
new->link=NULL;
ptr->link=new;
}
}/*end of else*/
}/*end of insertion*/
void deletion()
{
ptr=header;
if(header = = NULL)
{
printf("\nThe list is empty");
}
else
{
printf("\n1.Start \n2.Middle \n3.End");
printf("\nEnter the place to delete the element from list");
scanf("%d",&choice);
if(choice = = 1)
{
printf("\nThe deleted item from the list is -> %d",ptr->data);
header=header->link;
}
if(choice = = 2)
{
printf("\nEnter the position to delete the element from the list");
scanf("%d",&pos);
for(i=0;i<pos-1;i++)
{
ptr1=ptr;
ptr=ptr->link;
}
printf("\nThe deleted element is ->%d",ptr->data);
ptr1->link=ptr->link;
}
if(choice = = 3)
{
while(ptr->link!=NULL) {
ptr1=ptr;
ptr=ptr->link;
}//while
printf("\nThe deleted element from the list is ->%d", ptr->data);
ptr1->link=NULL;
}
}/*end of else*/
}/*end of deletion*/
void traverse()
{
if(header = = NULL)
printf("List is empty\n");
else
{
printf("\nThe elements in the list are");
for(ptr=header;ptr!=NULL;ptr=ptr->link)
printf("\n\tNode at %d is %d",++i,ptr->data);
}
}/*end of traverse*/

You might also like