Saturday, July 21, 2007
Matrix Multiplication - The C++ Way
/* Matrix Multiplication by PASSING OBJECT AS AN ARGUMENT */
class Matrix
{
int A[10][10];
int m,n;
public:
Matrix(int a,int b)
{
m = a;
n = b;
}
void readmatrix();
void printmatrix();
void addmatrix(Matrix b);
Matrix operator * (Matrix b);
};
void Matrix::readmatrix()
{
for(int i=0;i< m;i++)
{
for(j=0;j< n;j++)
cin>>A[i][j];
}
}
}
void Matrix::printmatrix()
{
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
{
cout< < A[i][j]<<" ";
}
cout< < endl;
}
}
void Matrix::addmatrix(Matrix b)
{
Matrix c(m,n);
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
{
c.A[i][j]=A[i][j]+b.A[i][j];
}
}
cout< < "The Addition Of The Two Matrices Is:"< < endl; c.printmatrix();
}
Matrix Matrix::operator*(Matrix b)
{
Matrix c(m,m);
for(int i=0;i< m;i++)
{
for(int k=0;k< m;k++)
{
c.A[i][k]=0;
for(int j=0;j< n;j++)
{
c.A[i][k] = A[i][j] * b.A[j][k] + c.A[i][k];
}
}
}
return c;
}
void main()
{
clrscr();
cout< < "Enter Order The Two Square Matrices: " ;
int a;
cin>>a;
Matrix x(a,a);
Matrix y(a,a);
cout< < endl< < "Enter Elements In First Matrix : ";
x.readmatrix();
cout< < endl< < "Enter Elements In The Second Matrix :";
y.readmatrix();
cout< < endl< < "The First Matrix:"< < endl;
x.printmatrix();
cout< < endl< < "The Second Matrix:"< < endl;
y.printmatrix();
x.addmatrix(y);
Matrix c(a,a);
c = x * y;
cout< < "The Multiplication Of The Two Matrices Are:"< < endl;
c.printmatrix();
getch();
}
/****** OUTPUT *******
Enter Order The Two Square Matrices: 3
Enter Elements In First Matrix : 1 0 0 0 1 0 0 0 1
Enter Elements In The Second Matrix :1 0 0 0 1 0 0 0 1
The First Matrix:
1 0 0
0 1 0
0 0 1
The Second Matrix:
1 0 0
0 1 0
0 0 1
The Addition Of The Two Matrices Is:
2 0 0
0 2 0
0 0 2
The Multiplication Of The Two Matrices Are:
1 0 0
0 1 0
0 0 1
*/
Operator Overloading,Inheritance
/* C++ Program For Implementation Of Constructors, Operator Overloading and Inheritance */
class index
{
protected:
int count;
public:
index()
{
count = 0;
}
index(int c)
{
count = c;
}
index operator ++()
{
count++;
}
void display()
{
cout< < endl< < "count = "< < count< < endl;
}
};
class index1 : public index
{
public:
void operator --()
{
count--;
}
};
void main()
{
clrscr();
index1 i;
i++;
i++;
i.display();
i--;
i.display();
getch();
}
Tuesday, July 10, 2007
Binary Tree Sort
Performance
The average number of comparisons for this method is O(nlog2n)
But in the worst case, the number of comparisons are reduced by O(n2), a case which arises when the sort tree is severely unbalanced .
/****** C Program For Implementation Of Binary Sort ***/
#define TRUE 1
#define FALSE 0
struct btreenode
{
struct btreenode *rightchild;
int data;
struct btreenode *leftchild;
};
insert(struct btreenode **sr,int num)
{
if(*sr==NULL)
{
*sr=malloc(sizeof(struct btreenode));
(*sr)- >leftchild=NULL;
(*sr)- >data=num;
(*sr)- >rightchild=NULL;
return;
}
else
{
if(num< (*sr)- >data)
insert(&((*sr)- >leftchild),num);
else
insert(&((*sr)- >rightchild),num);
}
return;
}
inorder(struct btreenode *sr)
{
if(sr!=NULL)
{
inorder(sr- >leftchild);
printf("%d ",sr- >data);
inorder(sr- >rightchild);
}
else
return;
}
postorder(struct btreenode *sr)
{
if(sr!=NULL)
{
postorder(sr- >rightchild);
printf("%d ",sr- >data);
postorder(sr- >leftchild);
}
else
return;
}
void main()
{
struct btreenode *bt;
int req,i=0,num,a[10],no;
bt=NULL;
clrscr();
while(i < 5)
{
printf("\nEnter value to be inserted: ");
scanf("%d",&a[i]);
insert(&bt,a[i]);
i++;
}
clrscr();
printf("\n\nSorted Binary tree in ascending order== > \n\n");
inorder(bt);
printf("\n\nSortred binary tree in descending order== >\n\n");
postorder(bt);
getch();
}
/************************** OUTPUT ***********************
Enter value to be inserted: 9
Enter value to be inserted: 8
Enter value to be inserted: 4
Enter value to be inserted: 5
Enter value to be inserted: 7
Sorted Binary tree in ascending order== >
4 5 7 8 9
Sortred binary tree in descending order== >
9 8 7 5 4 */
Saturday, July 7, 2007
Straight Selection Sort
ALGORITHM
1. Establish an array ‘a’ with ‘n’ elements
2. Repeat through step 6 for ‘n-1’ times
3. Repeat the position of the array already sorted
4. Repeat step 5 for the elements in unsorted position of the array
5. Record location of the largest element in the unsorted array
6. Exchange last element in the unsorted array with the largest element
PERFORMANCE OF THE ALGORITHM
During the first pass, in which the largest element is found, n-1 elements are compared. In general, for ith pass of the sort, n-I comparisons are required
So total number of comparisons
n-1 + n-2 + ……… + 1
Time Complexity = O(n2)
/**** C Program For Implementation Of Selection Sort ****/
#define MAX 10
char name[MAX][15];
void sort(int n)
{
int i,j,index;
char temp[15];
for(i=n;i >0;i--)
{
strcpy(temp,name[1]);
index=1;
for(j=1;j< =i;j++) { if(strcmp(name[j],temp) >0)
{
strcpy(temp,name[j]);
index=j;
}
}
strcpy(name[index],name[i]);
strcpy(name[i],temp);
}
}
void main()
{
int i,j,n;
clrscr();
A: printf("\n\nENTER HOW MANY NAMES: ");
scanf("%d",&n);
if(n >MAX)
{
printf("\n\t\tARRAY SIZE IS ONLY %d",MAX);
goto A;
}
else
{
printf("\n\t ENTER %d Names : \n",n);
for(i=1;i< =n;i++) { printf("\t\t"); scanf("%s",name[i]); } sort(n); printf("\n\n\t\t*********** SORTED LIST ************"); for(i=1;i< =n;i++) printf("\n \t\t\t\t%s",name[i]); } getch(); } /********** OUTPUT ************** ENTER HOW MANY NAMES: 12 ARRAY SIZE IS ONLY 10 ENTER HOW MANY NAMES: 4 ENTER 4 Names : Lionel Cyril Valerian Noronha *********** SORTED LIST ************ Cyril Lionel Noronha Valerian **************************************/
Thursday, July 5, 2007
Matrix Multiplication
#include<>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;
clrscr();
printf("Enter The Rows And Cloumns And Of The First Matrix:");
scanf("%d %d",&m,&n);
printf("\nEnter The Rows And Cloumns And Of The Second Matrix:");
scanf("%d %d",&p,&q);
printf("\nEnter Elements Of The First Matrix:\n");
for(i=0;i< m;i++)
{
for(j=0;j< n;j++)
scanf("%d",&a[i][j]);
}
printf("\nEnter Elements Of The Second Matrix:\n");
for(i=0;i< p;i++)
{
for(j=0;j< q;j++)
scanf("%d",&b[i][j]);
}
printf("The First Matrix Is:\n");
for(i=0;i< m;i++)
{
for(j=0;j< n;j++)
printf(" %d ",a[i][j]); //print the first matrix
printf("\n");
}
printf("The Second Matrix Is:\n");
for(i=0;i< p;i++) // print the second matrix
{
for(j=0;j< q;j++)
printf(" %d ",b[i][j]);
printf("\n");
}
if(n!=p)
{
printf("Aborting!!!!!!/nMultiplication Of The Above Matrices Not Possible.");
exit(0);
}
else
{
for(i=0;i< m;i++)
{
for(j=0;j< q;j++)
{
c[i][j] = 0;
for(k=0;k< n;k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
printf("\nMultiplication Of The Above Two Matrices Are:\n\n");
for(i=0;i< m;i++)
{
for(j=0;j< q;j++)
{
printf(" %d ",c[i][j]);
}
printf("\n");
}
}
getch();
}
Merge Sort
Divide the array into ‘n’ sub arrays of size 1 and merge adjacent pairs of sub arrays. Then we can have approximately n/2 sorted sub arrays of size 2. Repeat this process until there is 1 array containing n elements.
Algorithm
1. Establish a sub array ‘a’ with n elements
2. Let size < - 1 3. Repeat steps 4 through 6 until size >= n
4. Subdivide the sub array into sub arrays of size ‘size’
5. Merge adjacent pairs of sub arrays
6. Double the size
/*** C Program For Implementation Of Merge Sort ***/
#define MAX 20
void mergesort(int *,int);
void main()
{
int x[MAX],n,j,i;
char ans;
clrscr();
{
printf("\nEnter The Length Of The Array\t: ");
scanf("%d",&n);
for(i=0;i< n;i++)
{
printf("Enter Element %d\t: ",i+1);
scanf("%d",&x[i]);
}
mergesort(x,n);
printf("\n\t│ Sorted Array :\t\t\t│\n\t│");
for(i=0;i< n;i++)
printf("%d\t",x[i]);
}
printf("│");
getch();
}
void mergesort(int x[],int n)
{
int sub[MAX];
int i,j,k,list1,list2,u1,u2,size=1;
while(size< n)
{
list1=0;
k=0;
while((list1+size)< n)
{
list2=list1+size;
u1=list2-1;
u2=((list2+size-1)< n)?(list2+size-1):(n-1);
for(i=list1,j=list2;i< =u1 &&amp;amp; j< =u2;k++)
if(x[i]< =x[j])
sub[k]=x[i++];
else
sub[k]=x[j++];
for(;i< =u1;k++)
sub[k]=x[i++];
for(;j< =u2;k++)
sub[k]=x[j++];
list1=u2+1;
}
for(i=list1;k< n;i++)
sub[k++] = x[i];
for(i=0;i< n;i++)
x[i] =sub[i];
size *= 2;
}
}
/********* OUTPUT **********
Enter The Length Of The Array : 5
Enter Element 1 : 12
Enter Element 2 : 69
Enter Element 3 : 78
Enter Element 4 : 2
Enter Element 5 : 5
│ Sorted Array : │
│2 5 12 69 78 │
*/
Circular Queue
Algorithm for Insertion:-
Step-1: If "rear" of the queue is pointing to the last position then go to step-2 or else step-3
Step-2: make the "rear" value as 0
Step-3: increment the "rear" value by one
Step-4:
- if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then its a "queue overflow" state, so quit; else go to step-4.2
- insert the new value for the queue position pointed by the "rear"
Step-1: If the queue is empty then say "empty queue" and quit; else continue
Step-2: Delete the "front" element
Step-3: If the "front" is pointing to the last position of the queue then step-4 else step-5
Step-4: Make the "front" point to the first position in the queue and quit
Step-5: Increment the "front" position by one
/****** C Program For Impelmetation Of Circular Queue *******/
#define MAX 5
struct queue
{
int arr[MAX];
int rear,front;
};
int isempty(struct queue *p)
{
if(p->front ==p->rear)
return 1;
else
return 0;
}
void insertq(struct queue *p,int v)
{
int t;
t = (p->rear+1)%MAX;
if(t == p->front)
printf("\nQueue Overflow\n");
else
{
p->rear=t;
p->arr[p->rear]=v;
}
}
int removeq(struct queue *p)
{
if(isempty(p))
{
printf("\nQueue Underflow");
exit(0);
}
else
{
p->front=(p->front + 1)%MAX;
return(p->arr[p->front]);
}
}
void main()
{
struct queue q;
char ch;
int no;
clrscr();
q.rear=q.front =0;
insertq(&q,7);
insertq(&q,10);
insertq(&q,12);
insertq(&q,15);
insertq(&q,8);
printf("\n%d\n",removeq(&q));
printf("%d\n",removeq(&q));
printf("%d\n",removeq(&q));
printf("%d\n",removeq(&q));
removeq(&q);
getch();
}
/************** OUTPUT ****************
Queue Overflow
7
10
12
15
Queue Underflow */
Queue
/******** C Program For Impelmetation Of Queue ***********/
#define MAXSIZE 10
struct st
{
int front,rear;
int queue[MAXSIZE];
};
struct st s;
int empty(void);
int full(void);
void add(void);
void delete(void);
void display(void);
void main()
{
char ans;
int ch;
s.front = 0;
s.rear = 0;
do
{
clrscr();
printf("********Queue Program**********\n");
printf("1. ADD\n");
printf("2. DELETE\n");
printf("3. DISPLAY\n");
printf("4. QUIT\n");
printf("Enter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
add();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
break;
default:
printf("INVALID CHOICE!!!!!!!!!!!!!!!!\n");
break;
}
printf("\nWant To Go To The Main Menu[y/n]");
flushall();
ans = getch();
}
while(ans == 'y' ans == 'Y');
printf("\nPress Any Key To Continue\n");
getch();
}
int full(void)
{
if (s.rear == MAXSIZE)
return(1);
else
return(0);
}
int empty(void)
{
if (s.front == s.rear + 1)
return(1);
else
return(0);
}
void add(void)
{
char ch;
int x;
do
{
if(full() == 1)
{
printf("\n\nQueue Full\n");
break;
}
else
{
s.rear = s.rear + 1;
printf("\nEnter An Element to Be Added ");
scanf("%d",&x);
s.queue[s.rear] = x;
if(s.rear == 1) s.front ++;
}
printf("\nDo You Want to Add More Elements[y/n]:");
flushall();
ch = getch();
}
while(ch=='y' ch == 'Y');
}
void delete(void)
{
char ch;
do
{
if(empty() == 1)
{
printf("\n\nQueue Empty\n");
break;
}
else
{
printf("% d Has Been Deleted!",s.queue[s.front]);
s.front = s.front +1;
}
printf("\nWant to Delete More [y\n]");
flushall();
ch = getch();
}
while(ch=='y' ch == 'Y');
}
void display(void)
{
int i;
clrscr();
if(empty () == 1)
printf("\nQueue Empty!!");
else
{
printf("\nDisplaying Queue\n");
for(i = s.front;i
}
}
/************ OUTPUT ***************
**********Queue Program**********
1. ADD
2. DELETE
3. DISPLAY
4. QUIT
Enter Your Choice : 1
Enter An Element to Be Added 1
Do You Want to Add More Elements[y/n]:y
Enter An Element to Be Added 2
Do You Want to Add More Elements[y/n]:y
Enter An Element to Be Added 3
Do You Want to Add More Elements[y/n]:y
Enter An Element to Be Added 4
Do You Want to Add More Elements[y/n]:y
Enter An Element to Be Added 5
Do You Want to Add More Elements[y/n]:n
Want To Go To The Main Menu[y\n] y
**********Queue Program**********
1. ADD
2. DELETE
3. DISPLAY
4. QUIT
Enter Your Choice : 3
Displaying Queue
1
2
3
4
5
Want To Go To The Main Menu[y\n] y
**********Queue Program**********
1. ADD
2. DELETE
3. DISPLAY
4. QUIT
Enter Your Choice : 2
1 Has Been Deleted!!
Do You Want To Delete More?[y/n] n
Want to Go To Main Menue[y/n] y
**********Queue Program**********
1. ADD
2. DELETE
3. DISPLAY
4. QUIT
Enter Your Choice : 3
Displaying Queue
2
3
4
5
Want To Go To The Main Menu[y\n] y
**********Queue Program**********
1. ADD
2. DELETE
3. DISPLAY
4. QUIT
Enter Your Choice : 4 */
Stack
One way to think about this implementation is to think of functions as being stacked on top of each other; the last one added to the stack is the first one taken off. In this way, the data structure itself enforces the proper order of calls. Conceptually, a stack is simple: a data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack; the only element that can be removed is the element that was at the top of the stack.
Consequently, a stack is said to have "first in last out" behavior (or "last in, first out"). The first item added to a stack will be the last item removed from a stack. So what's the big deal? Where do stacks come into play? As you've already seen, stacks are a useful way to organize our thoughts about how functions are called. In fact, the "call stack" is the term used for the list of functions either executing or watiing for other functions to return. In a sense, stacks are part of the fundamental language of computer science. When you want to express an idea of the "first in last out" variety, it just makes sense to talk about it using the common terminology. Moreover, such operations show up an awful lot, from theoretical computer science tools such as a push-down automaton to AI, including implementations of depth-first search.
Stacks have some useful terminology associated with them:
- Push To add an element to the stack
- Pop To remove an element from the stock
- Peek To look at elements in the stack without removing them
- LIFO Refers to the last in, first out behavior of the stack
- FILO Equivalent to LIFO
- [Prologue] Save the parameters, Local Variables and return address.
- [Body] If the base criterion has been reached, then perform the final computation and go to step 3; otherwise, perfprm the partial computation and go to step 1(initialize a recursive call)
- [Epilogue] Restore the most recently saved parameters, local variables, and return address. Go to this return address.
#define MAXSIZE 10
struct st
{
int top;
int stack[MAXSIZE];
};
struct st s;
int empty(void);
int full(void);
void push(void);
void pop(void);
void display(void);
void main()
{
char ans;
int ch;
do
{
clrscr();
printf("********Stack Program**********\n");
printf("1.PUSH\n");
printf("2.POP\n");
printf("3.DISPLAY\n");
printf("4.QUIT\n");
printf("Enter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(1);
break;
default:
printf("INVALID CHOICE!!!!!!!!!!!!!!!!\n");
break;
}
printf("Want To Go To The Main Menu[y/n]");
flushall();
ans = getch();
}
while(ans == 'y' ans == 'Y');
printf("\nPress Any Key To Exit");
getch();
}
int full(void)
{
if (s.top == MAXSIZE)
return(1);
else
return(0);
}
int empty(void)
{
if (s.top == 0)
return(1);
else
return(0);
}
void push(void)
{
char ch;
int x;
do
{
if(full() == 1)
{
printf("\nStack Full\n");
break;
}
else
{
s.top = s.top + 1;
printf("\nEnter An Element To Be Pushed: ");
scanf("%d",&x);
s.stack[s.top] = x;
}
printf("\nDo You Want To Push More Elements[y/n]");
flushall();
ch = getch();
}
while(ch == 'y' ch == 'Y');
}
void pop(void)
{
char ch;
do
{
if(empty() == 1)
{
printf("\nStack Empty\n");
break;
}
else
{
printf("\n%d has been popped !",s.stack[s.top]);
s.top = s.top - 1;
}
printf("\nDo you Want To Pop Out More?[y/n]");
flushall();
ch = getch();
}
while(ch == 'Y' ch == 'y');
}
void display(void)
{
int i;
clrscr();
if(empty() == 1)
printf("\nStack Empty!!!");
else
{
printf("Displaying Stack............\n");
for(i = s.top; i>0;i--)
printf("%d",s.stack[i]);
}
}
/************** OUTPUT *************
********Stack Program**********
1. PUSH
2. POP
3. DISPLAY
4. QUIT
Enter Your Choice : 1
Enter An Element To Be Pushed : 1
Do YOu Want To Push More Elements [y\n] y
Enter An Element To Be Pushed : 2
Do YOu Want To Push More Elements [y\n] y
Enter An Element To Be Pushed : 3
Do YOu Want To Push More Elements [y\n] y
Enter An Element To Be Pushed : 4
Do YOu Want To Push More Elements [y\n] y
Enter An Element To Be Pushed : 5
Do YOu Want To Push More Elements [y\n] n
Want To Go Main Menu? [y\n] y
********Stack Program**********
1. PUSH
2. POP
3. DISPLAY
4. QUIT
Enter Your Choice : 3
Displaying Stack......
5
4
3
2
1
Want To Go Main Menu? [y\n] y
********Stack Program**********
1. PUSH
2. POP
3. DISPLAY
4. QUIT
Enter Your Choice : 2
5 Has Been Popped!
Do You Want To Pop More? [y\n] y
4 Has Been Popped!
Do You Want To Pop More? [y\n] n
Want To Go Main Menu? [y\n] y
********Stack Program**********
1. PUSH
2. POP
3. DISPLAY
4. QUIT
Enter Your Choice : 3
Displaying Stack.........
3
2
1
Want To Go Main Menu? [y\n] y
********Stack Program**********
1. PUSH
2. POP
3. DISPLAY
4. QUIT
Enter Your Choice : 4 */
File Handling - C Program
/************** File Handling *************/
void main()
{
FILE *file1;
char c;
int choice;
char op;
clrscr();
do
{
printf("\t\tMenu\n\t1. Enter The Information\n\t2. Display The Information\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Information \n");
file1=fopen("Handlin.doc","w");
while((c=getchar())!=EOF)
{
putc(c,file1);
}
fclose(file1);
break;
case 2:
printf("Information\n");
printf("Result :");
file1=fopen("Malcolm .doc","r");
while((c=getc(file1))!=EOF)
printf("%c",c);
fclose(file1);
break;
default:
exit(1);
}
printf("Enter Y To Continue:");
flushall();
scanf("%c",&op);
}
while((op=='y')(op=='Y'));
getch();
}
/********************* OUTPUT **********************
Menu
1. Enter The Information
2. Display The Information
1
Information
Today Is Sunday
^Z
Enter Y To Continue:y
Menu
1. Enter The Information
2. Display The Information
2
Information
Result :
Today Is Sunday
Enter Y To Continue:n
*/
Structures
int count;
struct employee
{
int idno,salary;
char name[10];
};
struct employee s[10];
void main()
{
int i,loc=0;
float top;
clrscr();
printf("Enter Number Of Employees : ");
scanf("%d",&count);
for(i=0;i
{
top=s[i].salary;
loc=i;
}
}
printf("\nThe Highest Salary Is : ");
printf("%s",s[loc].name);
getch();
}
/***************** OUTPUT ******************
Name : Lionel
ID no : 40
salary : 25000
Name : Cyril
ID no : 42
salary : 10000
Name : Bob
ID no : 46
salary : 15000
Name : Nigel
ID no : 45
salary : 12000
___________________________
Name ID no. Salary
---------------------------------------
Lionel 40 25000
Cyril 42 10000
Bob 46 15000
Nigel 45 12000
---------------------------------------
The Highest Salary Is : Lionel */