progrmming in c
TRANSCRIPT
-
8/7/2019 progrmming in c
1/35
Radiant Info School, kandy
Arrays
1. An array is a sequence of memory locations of which are stored in adjacentlocations in the memory.
2. All the elements in the array which are of the same type. I.e. the array should be
either an integer, character, Boolean etc.3. The concept of an array can be categorized in to the following types.
One dimensional array
Two dimensional array
Three dimensional array
One dimensional array
A One dimensional array is a collection of elements, which are stored in adjacentmemory locations.
The data in an One dimensional array can be stored as a row or as a column.The following indicates how to declare a one dimensional array.
int arr[5]; // declare in an integer array of five elements.
This will create the following array;
0 1 2 3 4
index
The following example indicates the use of an array to display the sum of the first ten
even numbers. Refer example # 1
1
-
8/7/2019 progrmming in c
2/35
Radiant Info School, kandy
example # 1
The One dimensional array can be used for many types of algorithms. Example # 2
indicates the concept of the palindrome. (Palindrome is a concept where a word will be
the same if given in reveres order. E.g. MADAM, RADAR, DEED are palindromes)
In the given example for loop is used with two variables, where the variable x is used
to move from the start till the end of the array, while the variable y is used to move from
the end till the start of the array.
The following indicates two main types of algorithms, which involve the concept of the
array. These two concepts are searching and sorting.
#include
void main( )
{
int arr[10];int x=0, sum=0;
while(x
-
8/7/2019 progrmming in c
3/35
Radiant Info School, kandy
Searching and sorting
Searching
The concept of the searching can be performed either for an unsorted array or
even a sorted array.
This algorithm is termed as a linear searching algorithm.
When performed to an unsorted array the code becomes slightly inefficient, since
when searching for an element in an unsorted array we should search the entirearray.
The following example # 3 gives the linear search for an unsorted array.
3
#include
void main( )
{
int arr[5]={7, 21, 10, 34, 22};
int skey,x;
bool found=fales;
coutskey;
for(x=0;x
-
8/7/2019 progrmming in c
4/35
Radiant Info School, kandy
The other example i.e. example # 5 indicates the linear search for a sorted array.The problem in the linear search algorithm is that the maximum number of comparisons
when searching for any element it is available in the array or even not available is that the
comparison will be equal to the number of element in the arrayIn order to over come the above problem the binary search algorithm can be used.
#include
void main( )
{
int arr[5]={7, 10, 21, 22, 34};
int skey,x;
bool found=false;
coutskey;
for(x=0;x
-
8/7/2019 progrmming in c
5/35
Radiant Info School, kandy
As the name implies the binary search algorithm divides the entire array into two and
then searching will be either done to the initial part of the array or the later part of thearray. This process will continue until the element is found or until it is determined that
the element is not available in the array.
Consider the following illustration:
12 23 34 45 56
1
There after the new mid value will be calculated, this will result in the pointer to theelement 12.
12 23 34 45 56
2
Finally the new mid value will be pointing to the value, which holds 23, and as a result
the element will be found. Further searching for any element which is available or not
available in the array can be determined using only half the comparison of array.
5
If the search key is equal to 23,
the search will commence from
the mid value.Since the mid value is greater
then the search key the latter part
of the array will be omitted.
-
8/7/2019 progrmming in c
6/35
Radiant Info School, kandy
12 23 34 45 56
3
Sorting
A one dimensional array can be rearranged either in ascending order or in
descending order.
There are many sorting algorithms available;
The following indicates one of the main sorting algorithms.
6
#include
void main( )
{
int arr[5]={7, 10, 21, 22, 34};
int start=0,end=5,mid,skey;
bool found=false;
coutskey;
do{
mid=(start+end)/2;
if(skey==arr[mid])
{
found=true;
break;
}
else if(skeyarr[mid])
start=mid;
}while(start
-
8/7/2019 progrmming in c
7/35
Radiant Info School, kandy
Bubble sort
During the bubble sorting algorithm the elements in the same array is rearranged byswapping the elements.
What is meant by swapping?
This is an interchange between two elements in the array; consider the following three
lines of code:
a b a b
10
25
25
10
Int temp = a;a = b;b = temp;
The following is the bubble sort algorithm for an array, which has five elements;
1
1
1
1
1
1
1 112 3
0
0
0
0
0
0
0
00
2
2
2
2
2
2
2 2
3
3
3
3
3 3
3 3
Pass three indicatesone comparison andwill result in the
largest threeelements in thecorrect location ofthe arrayPass two indicates
two comparisonsand will result in thelargest two elementsin the correctlocation of the array
Pass one indicatesthree comparisonsand will result in thelargest element inthe final location ofthe array
As given above when there is an array of five elements the actual required number ofcomparisons is equal to 3 + 2 + 1 = 6
7
-
8/7/2019 progrmming in c
8/35
Radiant Info School, kandy
The following two coding illustrates the inefficient and the efficient method for sorting
using the bubble sort algorithm.
The above bubble sorting algorithm mainly focus on sorting a single array, the concept of
the selection sort algorithm can be done using two arrays.
Since two arrays are use the concept of swapping will not be needed. The following tableindicates the concept of selection sort.
Arr1 Arr 2 Arr1 Arr2 Arr1 Arr2 Arr1 Arr2
255 - 255 47 255 47 999 47
47 - 999 - 999 93 999 93
93 - 93 - 999 - 999 255
8
#include
void main( ){
int arr[5]={23,34,12,7,3};
int temp,x,y;
for(x=0;x
-
8/7/2019 progrmming in c
9/35
Radiant Info School, kandy
The following example indicates the selection sorting coding.
Structures and structure array
An array is a collection of elements, all of the same type. On the other hand a structureenables you to collect variables of different types under one name.
This enables to handle complicated collection of data as a single unit.
The following code fragments indicates how a structure can be implicated.
Struct Employee
{
char name[20];
int num;
};
Consider the following example
Emp_no Emp_name Emp_ add Designation
100 John London Manager
200 Roger Paris Clerk
300 Allen New york Accountant
#include
void main( ){
int arr1[3]={255,47,93};
int arr2[3],x,y,z,min;
for(y=0;y
-
8/7/2019 progrmming in c
10/35
Radiant Info School, kandy
When a collection of such structure elements are required, a structure array can be used in
the above example, the second example indicates a structure array which contains100 employee details.
Consider example
A structure element is accessed using the dot operator. i.e.data.nm indicates the access ofthe name section in data.
Representing the above
structure in C language
Struct employee
{int Emp_no;
char Emp_name[10];
char Emp_Add[20];
char Designation[20];
};
Representing the above
structure which can hold up to
100 such records in C language.
Struct Employee
{
int Emp_no;
char Emp_name[10];
char Emp_Add[20];
char Designation[20];
}data[100];
#include
struct Employee{
char nm[10];
in temp_no;}data;
void main( )
{
struct Employee data;
coutdata.emp_no;
cout
-
8/7/2019 progrmming in c
11/35
Radiant Info School, kandy
Consider examples which indicates the concept of the structure array as the name
indicates the structure array will contain a structure inside each array element
#include
struct Emp{int Emp_no;
struct name
{
char first_nm[10];
char surname[20];
}a;
struct address
{
int house_no
char street[10];
char town[20];}b;
}d[3];
void main( )
{
int x =0;
while(x=1)
{
coutd[x].b.house_no;
cin>>d[x].b.street;
cin>>d[x].b.town;
cout
-
8/7/2019 progrmming in c
12/35
Radiant Info School, kandy
As given in 2nd example a structure in structure concept is used. As a result a hierarchy of
structure can be formed. As specified in the example the address structure consists of thehouse number, street and the town of an employee. There fore when accessing the inner
structure two dot operators are used, eg-d[x].b.street.
Pointers
A pointer can be defined as a memory location, which will contain the address of another
memory location.
This will enable to access the memory locations value with out the use of the variable
name.
The pointer can be defined as follows:
int *ptr;// declaring an integer pointer.
An integer pointer can only store the address of an integer variable.
int a; //declaring an integer variable.
a= 20; //assigning value 20 in a.
ptr= &a; //storing the address of a in the pointer named ptr.
12
-
8/7/2019 progrmming in c
13/35
Radiant Info School, kandy
The following example indicates the use of the pointers.
When considering passing parameters we could use the concept ofpassing by value,which was discussed initially under the heading name functions.
Parameters can also be passed by the use of pointers this known as passing by reference.
Next example indicates the concept of passing by reference.
#include
void main( )
{
int *ptr;int a= 20;
ptr= &a;
cout
-
8/7/2019 progrmming in c
14/35
Radiant Info School, kandy
The concept of pointer can also be used when declaring and using Boolean, character,
integer, double..etc. In this example indicates the use of character pointer which will act
as a string.
Note :
When trying use the character input function then three characterpointer will produce a run time error.
Linked list
A linked list consist of a collection of similar nodes which are connected with each other
using mainly the concept of pointers.The linked list node is indicated as below:
Data area Pointer area
The following indicates a diagrammatical explaining for the concept of the linked list.
A1
20 34
B2C3
53
As indicated above there are three nodes connected to the linked list. These three nodes
are connected via the concept of pointers. That is the address of the next node is sorted in
#include
void main( )
{
char *ch=RIS
cout
-
8/7/2019 progrmming in c
15/35
Radiant Info School, kandy
the pointer area of the current node which enables to maintain the connection between
the two nodes.
The final nodes in the list will be grounded. That is since there is on other node connected
to the list after node value 53, and then the pointer area will contain a NULL value which
further indicates that there is no connection to another node.
Depending on the operations performed on linked list it will require several pointers. That
is if the linked list is used to perform an insertion from the beginning of the linked list apointer will be required to point to the 1 st node of the linked list. Else if the insertion will
be done from the rear of the linked list then we would require a pointer to point to the last
node of list linked list.
Further if the node needs to insert from the middle when we would require two pointers
one pointing to the previous node and the other pointing to the next node.
The following example indicates the insertion of a new node from the 1
st
of the linkedlist.
Step 1
Create node and insert the value in to the data area of the node. Further ground the
pointer area of the node.
C3
53
Step 2
Create a pointer named head and point it to the created node
C3
53
head
Step 3
Create a new node and connect the new node to the current node. When connecting the
two nodes store the address of the existing node in the pointer area of the new node.
15
-
8/7/2019 progrmming in c
16/35
Radiant Info School, kandy
34
B2 C3
53
head
Step 4
Finally the address of the new node as the head of the linked list.
34
B2 C3
53
head
Step 5
Continue step 3 and step 4 when inserting the last node given. This will result in the
following linked list.
A1
2034
B2 C3
53
head
16
-
8/7/2019 progrmming in c
17/35
Radiant Info School, kandy
The following nodes indicates the insertion of nodes from the front of the linked list
The following example indicates the insertion of a new node from the rear of the linked
list
Step 1
Create a node and insert the value into data area of the node. Further ground the pointer
area of the node.
17
#include
struct Lnode{
int data;
Lnode*ptr;
};
void main( )
{
struct Lnode *L=new Lnode;
char opt;
Lnode *head;
L->ptr=NULL;
CoutL->data;
Head=L;
Do{
Lnode *L= new Lnode;
CoutL->data;
L->ptr=head;
head=L;
coutopt;
}while(opt= =y;)
Lnode *cur=head;
While(cur!=NULL)
{
cout
-
8/7/2019 progrmming in c
18/35
Radiant Info School, kandy
C3
53
Step 2
Create a pointer named rear and point it to the created nodeC3
53
rear
Step 3
Create a new node and connect the new node to the current node. When connecting thetwo nodes store the address of the existing node in the pointer area of the new node.
34
B2C3
53
rear
Step 4
Finally the address of the new node as the rear of the linked list.
18
-
8/7/2019 progrmming in c
19/35
Radiant Info School, kandy
34
B2C3
53
rear
Step 5
Continue step 3 and step 4 when inserting the last node given. This will result in thefollowing linked list.
A1
2034
B2C3
53
rear
19
-
8/7/2019 progrmming in c
20/35
Radiant Info School, kandy
The following example illustrates the coding when insertion takes place from the end of
the linked list.
The concept of the linked list can be used for the purpose of deleting a particular nodefrom the front of the list or from the rear of the list
The following illustration indicates the deletion of a node from the front of the linked list.
Step 1
Create a temp node.
Lnode *temp;
#include
struct Lnode{int data;
Lnode*ptr;
};
void main( )
{
struct Lnode *L=new Lnode;
char opt;
Lnode *rear;
L->ptr=NULL;
CoutL->data;
rear=L;
Do{
Lnode *L= new Lnode;
CoutL->data;
L->ptr=NULL;
rear=L;
coutopt;
}while(opt= =y) ;
}
20
-
8/7/2019 progrmming in c
21/35
Radiant Info School, kandy
C3
53
Step 2
Assign the head of the linked list to the temp.
Temp = head;
A1
2034
B2 C3
53
head
A1
2034
B2 C3
53
head
A1
2034
B2 C3
53
head
A1
2034
B2 C3
53
head
A1
2034
B2 C3
53
head
A1
2034
B2 C3
53
head
temp
Step 3
Transfer the head node to the next node in the linked list.
Head = head->ptr;
2034 53
2034 53
2034 53
2034 53
2034 53
2034 53
head
temp
Step 4
Delete the temp node.
Delete the temp;
B2 C3
34 5334 5334 5334 5334 5334 53
head
21
-
8/7/2019 progrmming in c
22/35
Radiant Info School, kandy
Step 5
Continue this process until the user will terminate or the linked list become empty.
22
#include
struct Lnode{
int data;
Lnode*ptr;
};
void main( )
{
struct Lnode *L=new Lnode;
char opt,opt2;
Lnode *head;L->ptr=NULL;
CoutL->data;
Head=L;
Do{
Lnode *L= new Lnode;
CoutL->data;
L->ptr=head;
head=L;
coutopt;
}while(opt= =y) ;
Lnode *cur=head;
While(cur!=NULL)
{
cout
-
8/7/2019 progrmming in c
23/35
Radiant Info School, kandy
The LHS indicates the source code, which creates, insert and delete nodes to and from alinked list.
The RHS indicates the out come of the given program.
The concept of a linked list can also be used for the purpose of searching for an element
in the linked list. The searching operation can only be done if the linked list is either in
ascending or in descending order. Since traversal can only be done in one direction, thelinked list can only perform a linear search.
Enter a value 40
Enter a value 30
Do you want to continue y
Enter a value 20
Do you want to continue n
20
30
40
Do you want to delete y
Do you want to delete y
Do you want to delete n
40
Press any key to continue
23
head=head->ptr;delete temp;
coutopt2;
}
Lnode *current=head;
While(current!= NULL)
{
cout
-
8/7/2019 progrmming in c
24/35
Radiant Info School, kandy
But if the linked list node had two pointers in a single node one pointing to the previous
node and the other pointing to the next node then it will be possible to perform a
searching algorithm for even an unsorted linked list the concept of maintaining twopointers in a linked list node is termed as a double linked list.
The following diagram illustrates a doubly linked list
100 341 121
Stacks and queues
Stacks
Stacks can be implemented using two methods.
Array based implementation
Linked list based implementation
Stacks can use the concept of (last in first out) LIFO, that is when inserting an element
into the stack it will be inserted from the rear or the top of the stack.
Due to this reason a stack only needs one identifier to identify the location of the top
element.Stack option
Push- insertion of an element to the stack Pop deletion of an element from the stack
Top display of the 1st element of the stack.
Count- displays the number of element of the stack.
Odd- display true if number of elements in the stack is odd and falseotherwise
Array based implementation
This is static,
Create stack.
int stack[5];
int top=-1;
push 10.
24
-
8/7/2019 progrmming in c
25/35
Radiant Info School, kandy
Top++;
Stack [top]=10;
10top0
Push 20,30,40,50
10 20 30 40 50 top4
Push 60
Creates an overflow error.
Pop10 20 30 40 top
3
Pop*4top-1
Pop
Creates an under flow error
The following codes illustrate the implementation of a stack using the concept of anarray.
The code indicates the insertion or push and pop operations in a stack.Further the out come of the code is indicated below:
25
-
8/7/2019 progrmming in c
26/35
Radiant Info School, kandy 26
#include
void main( )
[
int stack[5]={0,0,0,0,0};
int top=-1,count=0;
char op1,op2;
coutstack[++top];
count++;
do{
if(count==5);
{ cout
-
8/7/2019 progrmming in c
27/35
Radiant Info School, kandy
Further the concept of a stack can also be implemented using a linked list. Similar to the
array concept the linked list will also require only one pointer in order to point to the firstnode of the linked list. This pointer is top.
This concept is the same as a linked list where the insertion to the linked list is done from
the front of the linked list.Further deletion from the linked list will also be performed from the front.
Practical implications of stacks
Stacks are used by the ALU when performing various arithmetic operations such as
7+3x(5-2). There can be two answers for the above that is value 30, which is incorrectand value 16 which is the correct. Therefore the stack uses the concept of a prefix, postfix
statements which performs the relevant calculations with the help of a stack to generate
correct outcome.
The mathematical equation method is given below:7-6/2
Expression Infix Prefix Stack
7 7 7 Empty
7- 7- 7 -
7-6 7-6 76 -
7-6 7-6 76 -
7-6/ 7-6/ 76 -/
7-6/2 7-6/2 762 -/
7-6/2 7-6/2 762/ -
7-6/2 7-6/2 73 -
7-6/2 7-6/2 73- Empty7-6/2 7-6/2 4 empty
A stack is also used when performing a recursive function. A recursive function is a
function that will call itself.
QueuesQueues also can be implemented using two methods.Array based implementation
Linked list based implementation
Queues use the concept of FIFO. Therefore insertion is done from the front, whiledeletion is done from the rear.
Due to this reason a queues need two identifier to identify the front and rear.
Queue operations:
Attach- insertion of an element to the queue.
Detach- deletion of an element from the queue.
Front-display of te first element if the queue.
27
-
8/7/2019 progrmming in c
28/35
Radiant Info School, kandy
Count- display the number of elements of the queue.
Array based implementation
Array based implementation are staticCreate queue.
int queue[5];
int front= rear=-1;
attach 10.
Front++; rear++;
Queue [top]=10;
10 rear0
front0
Attach 20, 30, 40, 50
10 front0
20 30 40 50 rear4
Attach 60
Creates an overflow error.
Detach
20 30 40 50 rear4
front1
Detach*2
40 50 rear4
front3
Attach 60
40 50front3
60 rear0
When performing operations for the queue data structure problems that arise in the stack
such as overflow and underflow errors will still be available for a queue implementation
28
-
8/7/2019 progrmming in c
29/35
Radiant Info School, kandy
using an array. Further queues have an unique problem, that when attachment and
detachment is done to and from a queue since the concept of FIFO is used an overflow
error might still occur through the array has not be full as yet.
The following codes indicates the implementation of a queue using arrays
29
#include
void main( )
{
int queue[5]={0,0,0,0,0};
int front=-1,rear=-1,count=0;
char op1, op2;
coutqueue[++rear];
front=rear;
count++;
do{if(rear= =4)
{
cout
-
8/7/2019 progrmming in c
30/35
Radiant Info School, kandy
The concept of queue can be also implemented using linked list. Since the concept of thequeue, insertion is done from the front while the deletion or detachment is done from the
rear therefore we would require two pointers to identify the front and the rear of the
queue.
Practical implications of queues:
In a networking or even in a stand alone environment a single printer may be
shared. Therefore several print jobs may be sending to the printer, this is stored
and executed using a printer queue.The keyboard buffer also maintains a queue. Therefore when characters are
entered to the queue they are stored in a sequence of input.
The concept of recursion was mentioned earlier under the heading of functions.
Further we discussed that recursion uses the concept of stacks. Therefore Idelayed this concept until we have a clear idea of stacks. Now it is time to learn
recursion.
Recursion
Recursion is a key recurring concept
The process which allows the functions to all themselves is called recursion.Recursive definitions are circular definitions, i.e. when some thing is defined recursively
it defines it in terms of itself.Consider the following example
Non recursive factorial code
int factorial(int n){
int i, f;
f =1;
for(i=2;i
-
8/7/2019 progrmming in c
31/35
Radiant Info School, kandy
Following is the recursive function for factorial.
So each time factorial( ) is called separate copies are made of all the statements yet to beexecuted, finally the complier find a value of number (1), for which it knows the value of
factorial( ). So at last it can begin to execute (in reverse order).
Drawbacks
Consumes huge amount of computer memoryConsume huge amount of time
There are different recursive solutions
Two of them are
Going up recursion
Going down recursion
Going up recursion
int sumSquares(int m, int n){
if(m
-
8/7/2019 progrmming in c
32/35
Radiant Info School, kandy
return m*m;
}
}
sumSquares(2,8)
(4+ sumSquares(3,8))(4+(9+ sumSquares(4,8)))
(4+(9+(16+ sumSquares(5,8))))
(4+(9+(16+(25+ sumSquares(6,8)))))
(4+(9+(16+(25+(36+ sumSquares(7,8))))))
(4+(9+(16+(25+(36+(49+ sumSquares(8,8)))))))
(4+(9+(16+(25+(36+(49+64))))))
203
Going down recursion
int sumSquares(int m,int n){
if(m
-
8/7/2019 progrmming in c
33/35
Radiant Info School, kandy
File handling
C language is also used when handling files. File handling any programming languageshould perform the following file handling operations.
Opening file Creating a file if it dose not exist
Reading from a file
Writing to file
Closing for a file
The following example indicates file creation, opening and writing functions. Whenopening the file we should indicate under what mode we need to open the file. Following
indicates different types of modes in C language. There are several other types which I
felt will not be needed at this level.
Example
Mode
string
Description
r Read only
w Write only. Creates a new file or if an file exists it will overwrite the
file
a Append. Writes only either at the end of a file or creates a new file if
the existing file dose not exists.
r+ Update. Reads or writes to an existing file
w+ Update. Creates new file for read/write or over writes an existing file
a+ Updates. Appends at the end of the file, or creates a new file.
The LHS indicates program where output window is given on the RHS. The outcome of
the given out put will be India.
33
-
8/7/2019 progrmming in c
34/35
Radiant Info School, kandy
#include
#include
#include
void main( )
{
FILE *fp; char key,opt=y
fp=fopen(junk.txt,w+);
if(fp= = NULL)
{
cout
-
8/7/2019 progrmming in c
35/35
Radiant Info School, kandy
The following example indicates how the content of on file will be copied to another.#include
#include
#include
void main( )
{
FILE *in,*out;
int key;
if (in=fopen(junk.txt,r))= = NULL)
{
puts(unable to open file);
exit(1);
}
out = fopen(copy.txt,w);
while(!feof(in))
{
key=fgetc(in);
if (!feof(in))
{
fputc(key,out);
}
}
fclose(in);
fclose(out);
}
35