0% found this document useful (0 votes)
82 views

10 Programs

This document describes code for implementing various data structures and algorithms in C including: 1. A binary tree implementation using struct nodes with functions for insertion, search, and traversal. 2. Code for generating combinations of numbers from a set using recursion. 3. A file copy program that copies the contents of one file to another. 4. Implementation of a max heap data structure with functions for building and sorting an array using heap sort. 5. Matrix multiplication code that reads two matrices from a file and writes the product matrix to the file. 6. A variable argument print function mimicking printf. 7. Code to generate all permutations of a set recursively. 8

Uploaded by

Aakash Kansal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

10 Programs

This document describes code for implementing various data structures and algorithms in C including: 1. A binary tree implementation using struct nodes with functions for insertion, search, and traversal. 2. Code for generating combinations of numbers from a set using recursion. 3. A file copy program that copies the contents of one file to another. 4. Implementation of a max heap data structure with functions for building and sorting an array using heap sort. 5. Matrix multiplication code that reads two matrices from a file and writes the product matrix to the file. 6. A variable argument print function mimicking printf. 7. Code to generate all permutations of a set recursively. 8

Uploaded by

Aakash Kansal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

1.Binary tree .

c
/*This program implemenmts a binary tree using the struct data type to create a node. */
#include <stdio.h>
#include <stdlib.h>

/* Definition of a node of binary tree */


struct Node {
int data;
struct Node *left, *right;
};

/* Create a binary tree node */


struct Node* getNode() {
return (struct Node*)(malloc(sizeof(struct Node)));
}

/* Insert a node in binary tree */


struct Node* insert(struct Node* tn, int d)
{
if(tn == NULL) {
tn = getNode();
tn->data = d;
tn->left = tn->right = NULL;
}
else if(tn->data > d) /* Call insert() on left subtree */
tn->left = insert(tn->left, d);
else if(tn->data < d) /* Call insert() on left subtree */
tn->right = insert(tn->right, d);

/* Same element cannot be inserted twice so equality is not acted on */


return tn;
}

/* Print the elements of binary tree through "in order" traversal */


void inorder(struct Node* tn)
{
if(tn == NULL) /*Tree is finished - base case */
return;
/* Follow in order traversal */
inorder(tn->left);
printf("%d ", tn->data);
inorder(tn->right);
}

/* Search for element in the binary tree, and return 1 if true, 0 if false */
int search(struct Node* tn, int d)
{
if(tn == NULL)

/* Tree finished, element not found */

return 0;
else if(tn->data == d)

/* Element found */

return 1;
else if(tn->data < d) /* Search left subtree */
return search(tn->right, d);
else

/* Search right subtree */

return search(tn->left, d);


}

/* Main function to test the binary tree data structure. */

main() {
int ch, d, running = 1;
struct Node* tn = NULL;
while(running) {
/*Print menu of choices and accept choice */
printf("\n1: Insert new data\n");
printf("2: Search data\n");
printf("3: Print elements in order\n");
printf("4: Exit\n");
printf("Enter your choice:");
scanf("%d", &ch);
/* Execute options */
switch(ch)
{
case 1: /* Insert data into binary tree */
printf("Enter new data:");
scanf("%d", &d);
tn = insert(tn, d);
break;
case 2: /* Search for a data item in the binary tree */
printf("Enter data to search:");
scanf("%d", &d);
if(search(tn, d))
printf("\nData found\n");
else
printf("\nData not found\n");
break;
case 3: /* Traverse the binary tree in order and print the elements' data values */
inorder(tn);

printf("\n");
break;
case 4: /* Assign continuation flag to 0*/
running = 0;
}
}
}

2.combination
#include <stdio.h>
#include <stdlib.h>
int n, r, count;
void calccomb(int pos, int beg, int* arr);
void showcomb(int* arr);
main()
{
int *arr;
printf("Enter n:");
scanf("%d", &n);
printf("Enter r:");
scanf("%d", &r);
arr = (int*)malloc(r * sizeof(int));
calccomb(0, 1, arr);
printf("Number of combinations: %d\n", count);
}
void calccomb(int pos, int beg, int* arr)
{
int i;
if(pos == r){

showcomb(arr);
return;
}
for(i = beg; i <= n-r+pos+1; i++)
{
arr[pos] = i;
calccomb(pos+1, i+1, arr);
}
}
void showcomb(int* arr)
{
++count;
int i;
for(i = 0; i < r; i++)
printf("%d ", arr[i]);
printf("\n");
}

3.file copy
#include <stdio.h>
main()
{
FILE *fs,*fd;
char ch, fname1[80], fname2[80];
printf("Enter file to copy from with extension(within 80 characters)");
gets(fname1);
printf("Enter file to copy to with extension(within 80 characters)");
gets(fname2);
fs = fopen(fname1,"rb");

fd = fopen(fname2,"wb");

if(fs == NULL)
perror("Error in opening source file.");
else
{
do
{
ch = getc(fs);
fputc(ch, fd);
}
while (!feof(fs));
fclose(fs);
fclose(fd);
}
}

4.heap sort
/*
* This program contains methods to implement and use the heap
* data structure.
*/
#include <stdio.h>

/* The heap building and sorting methods*/


void max_heapify(int a[], int size, int index);
void build_max_heap(int a[], int size);
void heap_sort(int a[], int size);
main()

{}

/*
* This function transforms the subtree rooted at index to a max heap.
* It assumes the left and right subtrees of index are already max heaps
*/
void max_heapify(int a[], int size, int index)
{
if(index >= size) return;
int left, right, max;
index++;
left = index << 1;
right = (index << 1) + 1;
max = index;
if(left <= size && a[left - 1] > a[index - 1])
max = left;
if(right <= size && a[right - 1] > a[max - 1])
max = right;
if(max != index)
{
a[max - 1] = a[max - 1] ^ a[index - 1];
a[index - 1] = a[max - 1] ^ a[index - 1];
a[max ^ 1] = a[max - 1] ^ a[index - 1];
max_heapify(a, size, max - 1);
}
}

/*
* This function builds an unsorted array into a ax heap using the

* max_heapify procedure.
*/
void build_max_heap(int a[], int size)
{
int i;
for(i = size / 2; i >= 1; i--)
max_heapify(a, size, i - 1);
}

/*
* This function takes an unsorted array, contructs a heap from it
* using the build_max_heap() procedure,
* and sorts the array by heap sort method.
*/
void heap_sort(int a[], int size)
{
int length = size, i;
build_max_heap(a, size);
for(i = length; i >= 2; i--)
{
a[1] = a[1] ^ a[i];
a[i] = a[1] ^ a[i];
a[1] = a[1] ^ a[i];
size--;
max_heapify(a, 1, size);
}
}

5.mat.c
#include <stdio.h>
main()
{
FILE *fp;
int a[100][100], b[100][100], c[100][100];
int i, j, k, m, n, p;
printf("Enter the no. of rows and columns of matrix 1 :\n");
scanf("%d%d", &m, &n);
printf("Enter the no. of columns of matrix 2 :\n");
scanf("%d", &p);
fp=fopen("mat.txt", "r");
for(i=0; i<m; i++)
for(j=0; j<n; j++)
fscanf(fp, "%d", &a[i][j]);
for(i=0; i<n; i++)
for(j=0; j<p; j++)
fscanf(fp, "%d", &b[i][j]);
for(i=0; i<m; i++)
for(j=0; j<p; j++)
for(k=0; k<n; k++)
c[i][j] = c[i][j] + (a[i][k])*(b[k][j]);
fclose(fp);
fp = fopen("mat.txt", "a");
fprintf(fp, "\nThe multiplied matrix is :\n");
for(i=0; i<m; i++)
{
for(j=0; j<p; j++)

fprintf(fp, "%d\t", c[i][j]);


fprintf(fp, "\n");
}
fclose(fp);
}

6.variable argument print f


#include <stdio.h>
#include <stdarg.h>

void myprintf(const char* str, ...)


{
va_list vlist;
va_start(vlist, str);
char ch, c;
int item;
char *s;
unsigned uint;
while(ch = *(str++)) {
if(ch == '%') {
switch(*str) {
case 'd':
item = va_arg(vlist, int);
if(item < 0) {
putchar('-');
item = -item;
}
while(item > 0) {
putchar(item % 10 + 48);

item /= 10;
}
break;
case 'c':
c = va_arg(vlist, int);
putchar((char)c);
break;
case 's':
s = va_arg(vlist, char*);
while(*s) putchar(*(s++));
break;
case 'u':
uint = va_arg(vlist, unsigned int);
while(uint > 0) {
putchar(uint % 10 + 48);
uint /= 10;
}
break;
}
str++;
}
else putchar(ch);

}
va_end(vlist);
}
main()
{
myprintf("This is a test: %d %d %d %d %d\n", 11, 12, 13, 14, 15);

myprintf("%s", "This is also a test.\n");


myprintf("Testing character output: %c", 'a');
}

7.permutation
#include <stdio.h>
#include <stdlib.h>

int *arr1, n1, cnt;


void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void showperm(int* arr, int n)
{
int i;
if(n == 1)
{
cnt++;
for(i = 0; i < n1; i++)
printf("%d ", *(arr1 + i));
printf("\n");
return;
}
for(i = 0; i < n; i++)
{
swap(arr, arr+i);

showperm(arr+1, n - 1);
swap(arr, arr + i);
}
}
main()
{
int *arr, n, i;
cnt = 0;
printf("Enter n: ");
scanf("%d", &n);
n1 = n;
arr1 = arr = (int*)malloc(n * sizeof(int));
/*Assign the identity permutation to arr*/
for(i = 0; i < n; i++)
*(arr+i) = i + 1;
showperm(arr, n);
printf("Number of permutations: %d\n", cnt);
}

8.prng random no
#include <stdio.h>
int s[256], key[16], k[256], c1 = 0, c2 = 0;
int count[256];
void ksa();
int prng();
main()
{
printf("Enter 16 integers for key:");
for(int i = 0; i < 16; i++)

scanf("%d", &(a[i]));
for(int i = 0; i < 1000000; i++)
count[prng()]++;
printf("Counts of numbers:");
for(int i = 0; i < 256; i++)
printf("%d ", count[i]);
printf("\n");

}
void ksa()
{
int i, j;
/* Store identity permutaion in s */
for(i = 0; i < 256; i++)
s[i] = i;
j = 0;
for(i = 0; i < 256; i++){
j = (j + s[i] + k[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
int prng()
{
int temp;
c1 = (c1 + 1)%256;
c2 = (c2 + s[c1])%256;
temp = s[i];

s[i] = s[j];
s[j] = temp;
return s[(s[i] + s[j])%256];
}

9.queqe array
#define QSZ 20
#include <stdio.h>
struct Queue
{
int arr[QSZ];
int front, rear;
};
void init(struct Queue *q)
{
q->rear = q->front = -1;
}
int isEmpty(struct Queue *q)
{
return (q->front == -1);
}
int isFull(struct Queue *q)
{
return (q->front == QSZ - 1);
}
void push(struct Queue *q, int data)
{
int i;
if(isFull(q) == 1)

printf("Warning: Queue is full.");


else
{
for(i = q->front; i >= 0; i--)
q->arr[i + 1] = q->arr[i];
q->arr[0] = data;
q->rear = 0;
}
}
int pop(struct Queue *q)
{
if(isEmpty(q) == 1)
{
printf("Warning: Queue is empty");
}
else
{
return(q->arr[q->front--]);
}
}
void display(struct Queue *q)
{
int i;
if(q->front != -1)
for(i = q->rear; i <= q->front; i++)
printf("%d ", q->arr[i]);
printf("\n");
}

10.rc4
/*************** Start *****************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LOOP1 256*256
#define LOOP2 2
/*Function not used anywhere*/
unsigned int myrand(){
unsigned int j;
j=(unsigned int) (256.0*rand()/(RAND_MAX+1.0));
return j;
}
main(){
char str[80];
int s[256], i, j, temp, t, z, k[256], key[16], ml = 0, cnt = 0, r;
/* Use system as seed for library defined random function */
srand(time(NULL));
/* Run KSA and PRGA for LOOP1 random keys and check LOOP2TH pseudo random byte each time */
while(ml < LOOP1){

/* Generate random 16 byte key using rand() */


for(i = 0; i < 16; i++){
j = (int) (256.0*rand()/(RAND_MAX+1.0));
/* rand()/(RAND_MAX+1.0) falls between [0, 1). It is multiplied by

* 256 and fractional part omitted to get integer between 0 to 255 */


key[i] = j;
}

/* KEY SCHEDULING ALGORITHM*/


/* Replicate key 16 times to generate 256 bytes and store in k */
for (i = 0; i < 256; i++) k[i] = key[i%16];
/*Store identity permutation in s */
for (i = 0; i < 256; i++) s[i] = i;

/* Scramble s using k to generate random permutation - mug this section */


j = 0;
for (i = 0; i < 256; i++){
j = (j + s[i] + k[i])%256;
temp = s[i]; s[i] = s[j]; s[j] = temp;
}

/* Pseudo Random Number Generator - mug code*/


i = 0; j = 0; r = 0;
/* Generate upto LOOP2 th byte only */
while (r < LOOP2){
i = (i+1)%256; j = (j + s[i])%256;
temp = s[i]; s[i] = s[j]; s[j] = temp;
/* Generate (r + 1)th pseudo random byte tand store in z */
z = s[(s[i]+s[j])%256];
r++;
}
/*z now contains LOOP2TH pseudorandom byte for current key*/

if (z == 0) cnt++; /* Counting no. of 0s at LOOP2th byte - Replace 0 if


you want to check bias for some other value */
ml++;
}
/*Divide count of number of 0s at LOOP2TH byte by total number of keys checked
to estimate probability of getting 0 at LOOP2TH byte. If truly random it should
be 1/255, but it isn't */
printf("%.8lf\n", ((double) cnt)/((double) ml));
gets(str);
}

/*************** End *****************/

11.stack array
#define STKSZ 20
#include <stdio.h>
struct Stack
{
int arr[STKSZ];
int top;
};
typedef struct Stack stack;
void init(stack *s)
{
s->top = -1;
}
int isFull( stack *s)
{
if( s->top == STKSZ - 1)

return 1;
else
return 0;
}
int isEmpty ( stack *s)
{
if( s->top == -1)
return 1;
else
return 0;
}
void push(stack *s, int data)
{
if(isFull(s) == 1)
printf("Warning: Stack is full.");
else
{
(s->top)++;
s->arr[s->top] = data;
}
}
int pop(stack *s)
{
int temp;
if(isEmpty(s) == 1)
printf("Warning: Stack is empty.");
else
{
temp = s->arr[s->top];

(s->top)--;
return temp;
}
}
int top(stack *s)
{
if(isEmpty(s) ==1)
printf("warning: stack is empty.");
else
{
return s->arr[s->top];
}
}
void display(stack *s)
{
int i;
for(i = 0; i <= s->top; i++)
{
printf("%d ", s->arr[i]);
}
}

You might also like