Anda di halaman 1dari 35

# Radiant Info School, kandy 1

Arrays

## 1. An array is a sequence of memory locations of which are stored in adjacent

locations 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

## A One dimensional array is a collection of elements, which are stored in adjacent

memory 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

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.

## 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 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;
}

#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;
}
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;
}

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.

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

## 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.

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.

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;
}

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.

Bubble sort

During the bubble sorting algorithm the elements in the same array is rearranged by
swapping 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
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

## Pass three indicates

one comparison and
2 1 3 0 1 0 2 3 will result in the
largest three
elements in the
correct location of
2 1 0 3 Pass two indicates the array
two comparisons
and will result in the
Pass one indicates largest two elements
three comparisons in the correct
and will result in the location of the array
largest element in
the final location of
the array

As given above when there is an array of five elements the actual required number of
comparisons is equal to 3 + 2 + 1 = 6

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.

## 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

## The following example indicates the selection sorting coding.

#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;
}

## Structures and structure array

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;
};

## Emp_no Emp_name Emp_ add Designation

100 John London Manager
200 Roger Paris Clerk
300 Allen New york Accountant

## Representing the above

structure in C language Representing the above
structure which can hold up to
Struct employee 100 such records in C language.
{ Struct Employee
int Emp_no; {
char Emp_name[10]; int Emp_no;
}; char Designation[20];
}data[100];

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.

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>

## #include<iostream.h> struct Emp{

struct Student{ int Emp_no;
char name[20]; struct name
double mark; {
}; char first_nm[10];
void main( ) char surname[20];
{ }a;
int x=0;count=0; {
char opt=’y’; int house_no
do{ char street[10];
cout<<”’enter name”; char town[20];
cin>>dt[x].name; }b;
cout<<”enter mark”; }d[3];
cin>>dt[x].mark;
cout<<”do you want to void main( )
continue”; {
cin>>opt; int x =0;
count++; while(x=1)
x++; {
}while(opt= =’y’); cout<<”enter the” <<x+1<<”st
cout<<”student pass”<<endl; record”<<endl;
for(int y=0;y<=count;y++) cin>>d[x].emp_no;
{ cin>>d[x].a.first_nm;
if (dt[y].mark>=40) cin>>d[x].a.surname;
{ cin>>d[x].b.house_no;
cin>>d[x].b.street;
cout<<dt[y].name<<endl; cin>>d[x].b.town;

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++;
}
}

## 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 the
house 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.

## 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.

## The following example indicates the use of the pointers.

#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;
}

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.

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 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

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

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

## Create a pointer named head and point it to the created node

C3

53

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.

B2 C3

34 53

Step 4

B2 C3

34 53

Step 5
Continue step 3 and step 4 when inserting the last node given. This will result in the
A1 B2 C3
20
34 53

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;
L->ptr=NULL;
Cout<<”Enter a value”;
Cin>>L->data;
Do{

## Lnode *L= new Lnode;

Cout<<”Enter a value”;
Cin>>L->data;
cout<<”Do you want to continue”;
cin>>opt;
}while(opt= =’y’;)
While(cur!=NULL)
{
cout<<cur->data<<end;
cur=cur->ptr;
}
}

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.

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.

C3 B2

53 34

rear

Step 5

Continue step 3 and step 4 when inserting the last node given. This will result in the

C3 B2 A1

53 34 20

rear

The following example illustrates the coding when insertion takes place from the end of

#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;

C3
53

Step 2

A1 B2 C3
20
34 53
temp

Step 3

Transfer the head node to the next node in the linked list.

20
34 53
temp

Step 4

## Delete the temp node.

Delete the temp;

B2 C3

34 53

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;
L->ptr=NULL;
Cout<<”Enter a value”;
Cin>>L->data;

Do{
Lnode *L= new Lnode;
Cout<<”Enter a value”;
Cin>>L->data;
cout<<”Do you want to continue”;
cin>>opt;
}while(opt= =’y’) ;
While(cur!=NULL)
{
cout<<cur->data<<end;
cur=cur->ptr;
}
cout<<”do you want to delete”;
cin>>opt2;
while(pot2= =’y’);
{
Lnode *temp;
if (temp=NULL)
{
cout<<”list empty”;
break;
}

delete temp;
cout<<”do you want to delete”;
cin>>opt2;
}
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
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.

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

## Stacks can be implemented using two methods.

• Array 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 false
otherwise

## Array based implementation

This is static,
Create stack.
int stack[5];
int top=-1;

push 10.

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:

## #include<iostream.h> Enter an element 10

void main( ) Enter an element 20
Do you want to continue y
[ Enter an element 30
int stack[5]={0,0,0,0,0}; Do you want to continue y
int top=-1,count=0; Enter an element 40
char op1,op2; Do you want to continue y
cout<<”Enter an element”; Enter an element 50
cin>>stack[++top]; Do you want to continue y
count++; Overflow error
do{ 10
if(count==5); 20
{ 30
cout<<”Overflow 40
error”<<endl; 50
break; Do you want to delete y
} Do you want to delete y
cout<<”Enter an elelment”; Do you want to delete y
cin>>stack[++top]; Do you want to delete y
count++; Do you want to delete y
cout<<do you want to continue”; Do you want to delete y
cin>>op1; Underflow error
{while(op1==’y’); Press any key to continue
for(int x=0;x<=4;x++)
{
cout<<stack[x]<<endl;
}
cout<<”do you want to delete”;
cin>>op2;
while(op2==’y’)
{
if(count==0)
{
cout<<”underflow error”
break;
}
cout<<stack[top--]<<endl;
count--;
cout<<”do you want to delete”;
cin>> op2;
}
}

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.

## 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 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

## A stack is also used when performing a recursive function. A recursive function is a

function that will call itself.

Queues
Queues also can be implemented using two methods.
Array 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.

## Array based implementation are static

Create queue.

int queue[5];
int front= rear=-1;

attach 10.
Front++; rear++;
Queue [top]=10;

10 rear front
0 0

## Attach 20, 30, 40, 50

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

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

#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;
}
}

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.

## 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 I
delayed 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

## int factorial(int n){

int i, f;
f =1;
for(i=2;i<=n;i++)
f = f*i;
return f;
}

The above example illustrates how the factorial can be calculated non-recursively.
Factorial of 5

1*2*3*4*5=120

## Following is the recursive function for factorial.

#include<iostream.h>

## int factorial(int n){

if(n= =1){
return 1;
}else{
return n*factorial(n-1);
}
}
void main( )
{
int f=4;
cout<<factorial(f)<<endl;
}

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

## Consumes huge amount of computer memory

Consume huge amount of time

## Two of them are

Going –up recursion
Going –down recursion

Going up recursion

## int sumSquares(int m, int n){

if(m<n){
return m*m+sumSquares(m+1,n);
}else
{

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

## int sumSquares(int m,int n){

if(m<n){
return sumSquares(m,n-1)+n*n;
}else{
return n*n;
}
}

(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

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
• 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
“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.

#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)
.

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);
}