Beruflich Dokumente
Kultur Dokumente
Arrays
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
Radiant Info School, kandy 2
example # 1
#include<iostreame.h.>
void main( )
{
int arr[10];
int x=0, sum=0;
while(x<=9)
{
arr[x]=(x+1)*2;
sum=sum+arr[x];
cout<<arr[x]<<endl;
x++;
}
cout<<”Total is”<<sum<<endl;
}
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.
#include<iostream.h>
void main( )
{
int pal[5]={‘m’,’a’,’d’,’a’,’m’};
int x,y;
bool opt=true;
for(x=0,y=4;x<=2,y>=2;x++,y--)
{ if (pal[x]!=pal[y])
{ cout<<”Not a palindrome “<<end; opt=fales;
break;}
}
if(opt = =1) cout<<”palindrome “<<endl;
}
The following indicates two main types of algorithms, which involve the concept of the
array. These two concepts are searching and sorting.
Radiant Info School, kandy 3
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 entire
array.
The following example # 3 gives the linear search for an unsorted array.
#include<iostream.h>
void main( )
{
int arr[5]={7, 21, 10, 34, 22};
int skey,x;
bool found=fales;
cout<<”Enter a value to search “; cin>>skey;
for(x=0;x<=4;x++){ {
if(skey==arr[x]){
found=true; break;
}
}
if(found==true) cout<<”Element found”<<endl;
else cout<,”element not found”<<endl;
}
Radiant Info School, kandy 4
#include<iostream.h>
void main( )
{
int arr[5]={7, 10, 21, 22, 34};
int skey,x;
bool found=false;
cout<<”Enter a value to search “;
cin>>skey;
for(x=0;x<=4;x++)
{
if(skey==arr[x])
{
found=true;
break;
}
else if(skey==arr[x])
break;
}
if(found==true) cout<<”Element found”<<endl;
else cout<,”element not found”<<endl;
}
void main( )
{
int arr[5]={7, 21, 10, 34, 22};
int skey,x;
bool found=false;
cout<<”Enter a value to search “;
cin>>skey;
for(x=0;x<=4;x++)
{
if(skey==arr[x])
{
found=true;
break;
}
}
if(found==true) cout<<”Element found”<<endl;
else cout<,”element not found”<<endl;
}
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 array
In order to over come the above problem the binary search algorithm can be used.
Radiant Info School, kandy 5
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 the
array. This process will continue until the element is found or until it is determined that
the element is not available in the array.
12 23 34 45 56
There after the new mid value will be calculated, this will result in the pointer to the
element 12.
12 23 34 45 56
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.
Radiant Info School, kandy 6
12 23 34 45 56
#include<iostream.h>
void main( )
{
int arr[5]={7, 10, 21, 22, 34};
int start=0,end=5,mid,skey;
bool found=false;
cout<<”Enter the search key “;
cin>>skey;
do{
mid=(start+end)/2;
if(skey==arr[mid])
{
found=true;
break;
}
else if(skey<arr[mid])
end=mid;
else if(skey>arr[mid])
start=mid;
}while(start<end&& found==false);
if(found==1)cout<<”Element found”<<endl;
else cout<<”Element not found”<<endl;
}
Sorting
Bubble sort
During the bubble sorting algorithm the elements in the same array is rearranged by
swapping the elements.
This is an interchange between two elements in the array; consider the following three
lines of code:
a b a b
Int temp = a;
a = b; 1
1 2 b = temp; 2 0
0 5 5
The following is the bubble sort algorithm for an array, which has five elements;
2 3 1 0 2 1 0 3 1 0 2 3
2 3 1 0 1 2 0 3 0 1 2 3
As given above when there is an array of five elements the actual required number of
comparisons is equal to 3 + 2 + 1 = 6
Radiant Info School, kandy 8
The following two coding illustrates the inefficient and the efficient method for sorting
using the bubble sort algorithm.
#include<iostream.h> #include<iostream.h>
void main( ) void main( )
{ {
int arr[5]={23,34,12,7,3}; int arr[5]={23,34,12,7,3};
int temp,x,y; int temp,x,y,count=1;
for(x=0;x<=4;x++) for(x=3;x>=0;x--)
{ {
for(y=0;y<=4;y++) for(y=0;y<=x;y++)
{ {
if(arr[y]>arr[y+1]) if(arr[y]>arr[y+1])
{ {
temp=arr[y]; temp=arr[y];
arr[y]=arr[y+1];
arr[y]=arr[y+1]; arr[y+1]=temp;
arr[y+1]=temp; }
} }
} }
} }
} cout<<”the sorted array is ”<<endl;
cout<<”the sorted array is ”<<endl; for(int z=0;z<=4;z++)
for(int z=0;z<=4;z++) {
{ cout<<arr[z]<<endl;
cout<<arr[z]<<endl; }
} }
}
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 table
indicates the concept of selection sort.
#include<iostream.h>
void main( )
{
int arr1[3]={255,47,93};
int arr2[3],x,y,z,min;
for(y=0;y<=2;y++)
{
min=arr1[0];
for(x=1;x<=2;x++)
{ if(arr1[x]<min)
{ min=arr1[x];
z=x;
}
} arr2[y]=arr1[z];
arr1[z]=999;
z=0;
}
for (int a=0;a<=2,a++) cout<<arr2[a]<<endl;
}
An array is a collection of elements, all of the same type. On the other hand a structure
enables 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;
};
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 contains
100 employee details.
Consider example
#include<iostream.h>
struct Employee{
char nm[10];
in temp_no;
}data;
void main( )
{
struct Employee data;
cout<<”enter a name and number ”<<endl;
cin>>data.nm;
cin>>data.emp_no;
cout<<data.nm<<endl;
cout<<data.emp_no<<endl;
}
A structure element is accessed using the dot operator. i.e.data.nm indicates the access of
the name section in data.
Radiant Info School, kandy 11
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<iostream.h>
cout<<d[x].emp_no<<endl
cout<<d[x].a.first_nm<<endl
cout<<d[x].a.surname<<endl
cout<<d[x].b.house_no<<endl
cout<<d[x].b.street<<endl
cout<<d[x].b.town<<endl
x++;
}
}
Radiant Info School, kandy 12
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.
#include<iostream.h>
void main( )
{
int *ptr;
int a= 20;
ptr= &a;
cout<<ptr<<endl; //0x0065DFD1 is the address of a
cout<<*ptr<<endl; //willdisplay value 20
cout<<a<<endl; //will display value 20
cout<<&a<<endl; //0x0065DFD1is the address of a
}
When considering passing parameters we could use the concept of passing 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<iostream.h>
void swop(double*a, double*b);
void main( )
{
double x=1,y=2;
swop(&x,&y);
cout<<”value of x is “<<endl; //the answer is 2
cout<<”value of y is “<<endl: //the answer is 1
}
void swop(double*a,double*b)
{
double temp;
temp=*a;
*a=*b;
*b=temp;
}
Radiant Info School, kandy 14
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.
#include<iostream.h>
void main( )
{
char *ch=”RIS”
cout<<”our institute is “<<ch>>endl;
}
Note :
When trying use the character input function then three character
pointer 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:
The following indicates a diagrammatical explaining for the concept of the linked list.
A1 B2 C3
20 34 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
Radiant Info School, kandy 15
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 a
pointer will be required to point to the 1st 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 1st of the linked
list.
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
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.
Radiant Info School, kandy 16
B2 C3
34 53
head
Step 4
Finally the address of the new node as the head of the linked list.
B2 C3
34 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 B2 C3
20
34 53
head
Radiant Info School, kandy 17
The following nodes indicates the insertion of nodes from the front of the linked list
#include<iostream.h>
struct Lnode{
int data;
Lnode*ptr;
};
void main( )
{
struct Lnode *L=new Lnode;
char opt;
Lnode *head;
L->ptr=NULL;
Cout<<”Enter a value”;
Cin>>L->data;
Head=L;
Do{
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.
Radiant Info School, kandy 18
C3
53
Step 2
Create a pointer named rear and point it to the created node
C3
53
rear
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.
C3 B2
53 34
rear
Step 4
Finally the address of the new node as the rear of the linked list.
Radiant Info School, kandy 19
C3 B2
53 34
rear
Step 5
Continue step 3 and step 4 when inserting the last node given. This will result in the
following linked list.
C3 B2 A1
53 34 20
rear
Radiant Info School, kandy 20
The following example illustrates the coding when insertion takes place from the end of
the linked list.
#include<iostream.h>
struct Lnode{
int data;
Lnode*ptr;
};
void main( )
{
struct Lnode *L=new Lnode;
char opt;
Lnode *rear;
L->ptr=NULL;
Cout<<”Enter a value”;
Cin>>L->data;
rear=L;
Do{
Lnode *L= new Lnode;
Cout<<”Enter a value”;
Cin>>L->data;
L->ptr=NULL;
rear=L;
cout<<”Do you want to continue”;
cin>>opt;
}while(opt= =’y’) ;
}
The concept of the linked list can be used for the purpose of deleting a particular node
from 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;
Radiant Info School, kandy 21
C3
53
Step 2
A1 B2 C3
20
34 53
head
temp
Step 3
Transfer the head node to the next node in the linked list.
Head = head->ptr;
20
34 53
temp
head
Step 4
B2 C3
34 53
head
Radiant Info School, kandy 22
Step 5
Continue this process until the user will terminate or the linked list become empty.
#include<iostream.h>
struct Lnode{
int data;
Lnode*ptr;
};
void main( )
{
struct Lnode *L=new Lnode;
char opt,opt2;
Lnode *head;
L->ptr=NULL;
Cout<<”Enter a value”;
Cin>>L->data;
Head=L;
Do{
Lnode *L= new Lnode;
Cout<<”Enter a value”;
Cin>>L->data;
L->ptr=head;
head=L;
cout<<”Do you want to continue”;
cin>>opt;
}while(opt= =’y’) ;
Lnode *cur=head;
While(cur!=NULL)
{
cout<<cur->data<<end;
cur=cur->ptr;
}
cout<<”do you want to delete”;
cin>>opt2;
while(pot2= =’y’);
{
Lnode *temp;
Temp= head;
if (temp=NULL)
{
cout<<”list empty”;
break;
}
Radiant Info School, kandy 23
head=head->ptr;
delete temp;
cout<<”do you want to delete”;
cin>>opt2;
}
Lnode *current=head;
While(current!= NULL)
{
cout<<current->data<<endl;
current=current->ptr;
}
}
The LHS indicates the source code, which creates, insert and delete nodes to and from a
linked list.
The RHS indicates the out come of the given program.
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
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, the
linked list can only perform a linear search.
Radiant Info School, kandy 24
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 two
pointers in a linked list node is termed as a double linked list.
Stacks
This is static,
Create stack.
int stack[5];
int top=-1;
push 10.
Radiant Info School, kandy 25
Top++;
Stack [top]=10;
top
10 0
Push 20,30,40,50
10 20 30 40 50 top
4
Push 60
Creates an overflow error.
Pop
10 20 30 40 top
3
Pop*4
top
-1
Pop
Creates an under flow error
The following codes illustrate the implementation of a stack using the concept of an
array.
The code indicates the insertion or push and pop operations in a stack.
Further the out come of the code is indicated below:
Radiant Info School, kandy 26
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 first
node 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.
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 incorrect
and 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- Empty
7-6/2 7-6/2 4 empty
Queues
Queues 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, while
deletion 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.
Radiant Info School, kandy 28
int queue[5];
int front= rear=-1;
attach 10.
Front++; rear++;
Queue [top]=10;
10 rear front
0 0
10 20 30 40 50 rear front
4 0
Attach 60
Creates an overflow error.
Detach
20 30 40 50 rear front
4 1
Detach*2
40 50 rear front
4 3
Attach 60
60 40 50 rear front
0 3
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
Radiant Info School, kandy 29
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.
#include<iostream.h>
void main( )
{
int queue[5]={0,0,0,0,0};
int front=-1,rear=-1,count=0;
char op1, op2;
cout<<”Enter an element”;
cin>>queue[++rear];
front=rear;
count++;
do{
if(rear= =4)
{
cout<<”overflow error”<<endl;
break;
}
cout<<”Enter an element”;
cin>>queue[++rear];count++;
cout<<”do you want to continue”;
cin>>op1;
}while(op1= = ‘y’);
for(int x=0;x<=4;x++)
{
cout<<queue[x]<<endl;
}
cout<<”do you want to delete”;
cin>>op2;
while(op2 = ‘y’)
{
if(front>rear)
{
cout<<”underflow error”;
break;
}
queue[front++];
count--;
cout<<’do you want to delete”;
cin>>op2;
}
}
Radiant Info School, kandy 30
The concept of queue can be also implemented using linked list. Since the concept of the
queue, 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.
Recursion
The above example illustrates how the factorial can be calculated non-recursively.
Factorial of 5
1*2*3*4*5=120
Radiant Info School, kandy 31
#include<iostream.h>
So each time factorial( ) is called separate copies are made of all the statements yet to be
executed, 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
Going up recursion
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
(sumsquares(2,7)+64)
((sumsquares(2,6)+49)+64)
(((sumsquares(2,5)+36)+49)+64)
((((sumsquares(2,4)+25)+36)+49)+64)
(((((sumsquares(2,3)+16)+25)+36)+49)+64)
((((((sumsquares(2,2)+9)+16)+25)+36)+49)+64)
((((((4+9))+ 16)+25)+36)+49)+64)
203
Radiant Info School, kandy 33
File handling
C language is also used when handling files. File handling any programming language
should 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. When
opening 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 Description
string
“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.
Radiant Info School, kandy 34
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h> Enter a character I
void main( ) Do you want to continue y
{ Enter a character n
FILE *fp; char key,opt=’y’ Do you want to continue y
fp=fopen(“junk.txt”,”w+”); Enter a character d
if(fp= = NULL) Do you want to continue y
{ Enter a character i
cout<<”end of file”<<endl; Do you want to continue y
exit(1); Enter a character a
} Do you want to continue n
do Press any key to continue
{
cout<<”enter a character”;
cin>>key
fputc(key,fp);
cout<<”do you want to
continue”;
cin>>opt;
}while(opt= = ‘y’);
fclose(fp)
.
Radiant Info School, kandy 35
The following example indicates how the content of on file will be copied to another.
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
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);
}