SlideShare uma empresa Scribd logo
1 de 113
Baixar para ler offline
DATA STRUCTURES
************acess element using
pointer*****************
#include<stdio.h>
int main()
{
int data[5], i;
printf("Enter elements: ");
for(i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: n");
for(i = 0; i < 5; ++i)
printf("%dn", *(data + i));
return 0;
}
*****************addmaloc*****************
#include<stdio.h>
#include<stdlib.h>
int main()
{
//1
int i,j;
int count;
int *arr;
int sum = 0;
int product=1;
//2
arr = (int *)malloc(count* sizeof(int));
printf("Enter the total number of elements you want to
enter : ");
scanf("%d",&count);
printf("adresses of allocatedmeroryn");
for(i = 0;i<count;++i)
printf("%ut",arr+i);
//4
for(i = 0;i<count;i++){
//5
printf("nEnterelement %d : ",(i+1));
scanf("%d",arr+i);
//6
sum += *(arr+i);
product *= *(arr+i);
}
//7
printf("sum is %d n",sum);
printf("product is %d n",product);
//8
free(arr);
return 0;
}
******************addmaloc size**************
#include<stdio.h>
#include<stdlib.h>
int main()
{
//1
int i,j,s1,s2;
int count;
int *arr;
int sum = 0;
int product=1;
//2
arr = (int *)malloc(count* sizeof(int));
printf("Enter the total number of elements you want to
enter : ");
scanf("%d",&count);
printf("adresses of allocatedmeroryn");
for(i = 0;i<count;++i)
printf("%ut",arr+i);
s1=sizeof(int);
s2=count * s1;
printf("size of int=%d , size of one data =%dn",s1,s2);
printf("Size of integer type array having total %d * %d = %d
bytesn",s2/s1,s1,s2);
for(i = 0;i<count;i++)
{
//5
printf("nEnterelement %d : ",(i+1));
scanf("%d",arr+i);
//6
sum += *(arr+i);
product *= *(arr+i);
}
//7
printf("sum is %d n",sum);
printf("product is %d n",product);
//8
free(arr);
return 0;
}
**************reallocatingthe memory to
0***************
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int *ptr = (int*) malloc(10);
/* we are calling realloc with size = 0 */
realloc(ptr, 0);
return 0;
}
*****************limittest using malloc***********
/*C program to input and print text
using Dynamic Memory Allocation.*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
char *text;
printf("Enterlimit of the text: ");
scanf("%d",&n);
/*allocatememory dynamically*/
text=(char*)malloc(n*sizeof(char));
printf("Entertext: ");
scanf(" "); /*clear input buffer*/
gets(text);
printf("Inputtedtext is: %sn",text);
/*Free Memory*/
free(text);
return 0;
}
****************malloc**********
#include<stdio.h>
main()
{
float *list, sortnum, j, average = 0, sum = 0;
printf("Enter the number of data pointsto average: ");
scanf("%f",&sortnum);
list = (float *)malloc(sortnum * sizeof(int));
for (j = 0; j < sortnum; j++)
scanf("%f", list + j);
printf("You entered the following:n");
for (j = 0; j < sortnum; j++)
printf("%fn", *(list + j));
free(list);
return 0;
}
******************calloc********************
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, num;
float *data;
printf("Entertotal number of elements(1 to 100): ");
scanf("%d", &num);
// Allocatesthe memory for 'num' elements.
data = (float*) calloc(num, sizeof(float));
if(data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
printf("n");
// Stores the number entered by the user.
for(i = 0; i < num; ++i)
{
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}
// Loop to store largest number at address data
for(i = 1; i < num; ++i)
{
// Change < to > if you want to find the smallest number
if(*data < *(data + i))
*data = *(data + i);
}
printf("Largest element = %.2f", *data);
return 0;
}
*******************array additionand multiplication
using pointers*************
#include<stdio.h>
main()
{
int arr[5];
int sum,product, i;
int s1=sizeof(arr);
int s2=sizeof(int);
printf("Size of int=%d bytesn",s2);
printf("Size of one data=%d bytesn",sizeof(arr[0]));
printf("Size of integer type array having %d elements =
%d bytesn",s1/s2, s1);
/*read array elements*/
printf("nenter elements:n");
for(i=0;i<5;i++)
{
printf("enter arr[%d]",i);
scanf("%d",&arr[i]);
}
/*calculate sum and product*/
sum=0;
product=1;
for(i=0;i<5;i++)
{
sum=sum+arr[i];
product=product*arr[i];
}
printf("nsum of array is: %d",sum);
printf("nproduct of array is: %d",product);
}
*****************binaryfile using fwrite with
pointer***************
#include<stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:program.bin","wb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointerreturns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
***************code to read a file***********
#include<stdio.h>
#include<stdlib.h> // For exit() function
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! openingfile");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^n]", c);
printf("Datafrom the file:n%s", c);
fclose(fptr);
return 0;
}
****************reverse in a file**********
/*
* C Program to Reverse the Contents of a File and Print it
*/
#include<stdio.h>
#include<errno.h>
long count_characters(FILE *);
int main()
{
int i;
long cnt;
char ch, ch1;
FILE *fp1, *fp2;
if (fp1 = fopen("file1.txt", "r"))
{
printf("The FILE hasbeen opened...n");
fp2 = fopen("file123.txt", "w");
cnt = count_characters(fp1); // to count the total
number of characters inside the source file
fseek(fp1, -1L, 2); // makes the pointerfp1 to point
at the last character of the file
printf("Number of characters to be copied %dn",
ftell(fp1));
while (cnt)
{
ch = fgetc(fp1);
fputc(ch, fp2);
fseek(fp1, -2L, 1); // shifts the pointerto the
previouscharacter
cnt--;
}
printf("n**File copied successfully in reverse
order**n");
}
else
{
perror("Error occuredn");
}
fclose(fp1);
fclose(fp2);
}
// count the total number of characters in the file that *f
pointsto
long count_characters(FILE *f)
{
fseek(f, -1L, 2);
long last_pos= ftell(f); // returns the positionof the last
element of the file
last_pos++;
return last_pos;
}
******************struct student in file*******
#include<stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);
printf("Enter height: ");
scanf("%d", &stud1[i].height);
}
fwrite(stud1, sizeof(stud1), 1, fptr);
fclose(fptr);
fptr = fopen("file.txt", "rb");
fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %snHeight: %d", stud2[i].name,
stud2[i].height);
}
fclose(fptr);
}
**************write student data into file*********
#include<stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
return 0;
}
for(i = 0; i < num; ++i)
{
printf("Forstudent%dnEnter name: ", i+1);
scanf("%s", name);
printf("Entermarks: ");
scanf("%d", &marks);
fprintf(fptr,"nName: %s nMarks=%d n", name, marks);
}
fclose(fptr);
return 0;
}
***************concatenatefiles***************
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fs1, *fs2, *ft,*fs3;
char ch, file1[20], file2[20], file3[20],ch1;
int charcount,wordcount,linecount;
printf("Enter name of first filen");
gets(file1);
printf("Enter name of second filen");
gets(file2);
printf("Enter name of file which will store contents of the
two filesn");
gets(file3);
fs1 = fopen(file1, "r");
fs2 = fopen(file2, "r");
if(fs1 == NULL || fs2 == NULL)
{
perror("Error ");
printf("Press any key to exit...n");
exit(EXIT_FAILURE);
}
ft = fopen(file3, "w"); // Opening in write mode
if(ft == NULL)
{
perror("Error ");
printf("Press any key to exit...n");
exit(EXIT_FAILURE);
}
while((ch = fgetc(fs1)) != EOF)
fputc(ch,ft);
while((ch = fgetc(fs2)) != EOF)
fputc(ch,ft);
printf("The two files were merged into %s file
successfully.n", file3);
{
ft=fopen(file3,"r");
fs3=fopen("file3.txt","w");
if (ft)
{
while ((ch1=getc(ft)) != EOF)
{
// Increment character count if NOT new line or
space
if (ch1 != ' ' && ch1 != 'n') { ++charcount; }
// Increment word count if new line or space
character
if (ch1 == ' ' || ch1 == 'n') { ++wordcount; }
// Increment line count if new line character
if (ch1 == 'n') { ++linecount;}
}
if (charcount > 0)
{
++linecount;
++wordcount;
}
}
else
{
printf("Failedto open the filen");
}
fprintf(fs3,"Lines : %d n", linecount);
fprintf(fs3,"Words : %d n", wordcount);
fprintf(fs3,"Characters : %d n", charcount);
getchar();
fclose(fs1);
fclose(fs2);
fclose(ft);
fclose(fs3);
}
return 0;
}
**************to count word and character**********
#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char filename1[100],filename2[100];
char ch;
int linecount,wordcount, charcount;
// Initialize countervariables
linecount = 0;
wordcount = 0;
charcount = 0;
// Prompt user to enter filename
printf("Entera filename :n");
gets(filename1);
printf("enter file name2:n");
gets(filename2);
// Open file in read-only mode
fp1 = fopen(filename1,"r");
fp2=fopen(filename2,"w");
// If file opened successfully, then write the string to file
if ( fp1 )
{
//Repeat until End Of File character is reached.
while ((ch=getc(fp1)) != EOF) {
// Increment character count if NOT new line or
space
if (ch != ' ' && ch != 'n') { ++charcount;}
// Increment word count if new line or space
character
if (ch == ' ' || ch == 'n') { ++wordcount; }
// Increment line count if new line character
if (ch == 'n') { ++linecount;}
}
if (charcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("Failedto open the filen");
}
fprintf(fp2,"Lines : %d n", linecount);
fprintf(fp2,"Words : %d n", wordcount);
fprintf(fp2,"Characters : %d n", charcount);
getchar();
return(0);
}
***********concatenatetwo files************
#include<stdio.h>
int main()
{
FILE *fp1,*fp2,*fp3;
int i,j,temp,count1,count,size,size2;
char str[100]={"This is a pattern matching"};
char substr[20]={"pattern"};
char
ch[100],ch1[100],filename1[100],filename2[100],filename3[1
00];
printf("Entera filename :n");
gets(filename1);
printf("enter file name2:n");
gets(filename2);
printf("enter file name2:n");
gets(filename3);
// Open file in read-only mode
fp1 = fopen(filename1,"r");
fp2=fopen(filename2,"r");
fp3=fopen(filename3,"w");
if(fp1&&fp2)
{
while((ch[i]= fgetc(fp1)) != EOF)
fseek(fp1, 0, 2); /* file pointerat the end of file */
size = ftell(fp1); /* take a positionof file pointerun size
variable*/
while((ch1[i] = fgetc(fp2)) != EOF)
fseek(fp2, 0, 2); /* file pointer at the end of file */
size2 = ftell(fp2); /* take a position of file pointerun size
variable*/
for (i = 0; i < size;)
{
j = 0;
count = 0;
while ((ch[i] == ch1[j]))
{
count++;
i++;
j++;
}
if (count == size2)
{
count1++;
count = 0;
}
else
i++;
}
fprintf(fp3," %d times in %s",count1, str);
}
}
return 0;
}
***************employ record using files********
/*
* C Program to Update Detailsof Employee using Files
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct emp
{
int empid;
char *name;
};
int count = 0;
void add_rec(char*a);
void display(char*a);
void update_rec(char*a);
void main(intargc, char *argv[])
{
int choice;
while (1)
{
printf("MENU:n");
printf("1.Add a recordn");
printf("2.Displaythe filen");
printf("3.Update the recordn");
printf("Enter your choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:
add_rec(argv[1]);
break;
case 2:
display(argv[1]);
break;
case 3:
update_rec(argv[1]);
break;
case 4:
exit(0);
default:
printf("Wrong choice!!!nEnterthe correct
choicen");
}
}
}
void add_rec(char*a)
{
FILE *fp;
fp = fopen(a, "a+");
struct emp *temp = (struct emp *)malloc(sizeof(struct
emp));
temp->name = (char *)malloc(50*sizeof(char));
if (fp == NULL)
printf("Error!!!");
else
{
printf("Enter the employee idn");
scanf("%d", &temp->empid);
fwrite(&temp->empid, sizeof(int), 1, fp);
printf("enter the employee namen");
scanf(" %[^n]s", temp->name);
fwrite(temp->name, 50, 1, fp);
count++;
}
fclose(fp);
free(temp);
free(temp->name);
}
void display(char*a)
{
FILE *fp;
char ch;
int rec = count;
fp = fopen(a, "r");
struct emp *temp = (struct emp *)malloc(sizeof(struct
emp));
temp->name = (char *)malloc(50*sizeof(char));
if (fp == NULL)
printf("Error!!");
else
{
while (rec)
{
fread(&temp->empid, sizeof(int), 1, fp);
printf("%d", temp->empid);
fread(temp->name, 50, 1, fp);
printf(" %sn", temp->name);
rec--;
}
}
fclose(fp);
free(temp);
free(temp->name);
}
void update_rec(char*a)
{
FILE *fp;
char ch, name[5];
int rec, id, c;
fp = fopen(a, "r+");
struct emp *temp = (struct emp *)malloc(sizeof(struct
emp));
temp->name = (char *)malloc(50*sizeof(char));
printf("Enter the employee id to update:n");
scanf("%d", &id);
fseek(fp, 0, 0);
rec = count;
while (rec)
{
fread(&temp->empid, sizeof(int), 1, fp);
printf("%d", temp->empid);
if (id == temp->empid)
{
printf("Enterthe employee name to be updated");
scanf(" %[^n]s", name);
c = fwrite(name, 50, 1, fp);
break;
}
fread(temp->name, 50, 1, fp);
rec--;
}
if (c == 1)
printf("Record updatedn");
else
printf("Update not successfuln");
fclose(fp);
free(temp);
free(temp->name);
}
*****************delete a displayedtree*********
#include<stdio.h>
int array[100], n;
main()
{
int choice, num;
n = 0;/*Represents number of nodes in the heap*/
while(1)
{
printf("1.Insert the element n");
printf("2.Delete the element n");
printf("3.Display all elements n");
printf("4.Quit n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the element to be inserted to the list : ");
scanf("%d", &num);
insert(num, n);
n = n + 1;
break;
case 2:
printf("Enter the elements to be deleted from the list:
");
scanf("%d", &num);
delete(num);
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalidchoice n");
}/*End of switch */
}/*End of while */
}/*End of main()*/
display()
{
int i;
if (n == 0)
{
printf("Heap is empty n");
return;
}
for (i = 0; i < n; i++)
printf("%d ", array[i]);
printf("n");
}/*End of display()*/
insert(int num, int location)
{
int parentnode;
while (location> 0)
{
parentnode =(location - 1)/2;
if (num <= array[parentnode])
{
array[location]= num;
return;
}
array[location]= array[parentnode];
location = parentnode;
}/*End of while*/
array[0] = num; /*assign number to the root node */
}/*End of insert()*/
delete(int num)
{
int left, right, i, temp, parentnode;
for (i = 0; i < num; i++) {
if (num == array[i])
break;
}
if (num != array[i])
{
printf("%d not found in heap listn", num);
return;
}
array[i] = array[n - 1];
n = n - 1;
parentnode=(i - 1) / 2; /*find parentnode of node i */
if (array[i] > array[parentnode])
{
insert(array[i], i);
return;
}
left = 2 * i + 1; /*left child of i*/
right = 2 * i + 2; /* right childof i*/
while (right < n)
{
if (array[i] >= array[left] && array[i] >= array[right])
return;
if (array[right] <= array[left])
{
temp = array[i];
array[i] = array[left];
array[left] = temp;
i = left;
}
else
{
temp = array[i];
array[i] = array[right];
array[right] = temp;
i = right;
}
left = 2 * i + 1;
right = 2 * i + 2;
}/*End of while*/
if (left == n - 1 && array[i]) {
temp = array[i];
array[i] = array[left];
array[left] = temp;
}
}
**********************float multiplicationusing
malloc************
#include<stdio.h>
#include<stdlib.h>
main()
{
//1
int i,j,s1,s2;
float count;
float *arr;
int sum = 0;
int product=1;
//2
arr = (float *)malloc(count* sizeof(float));
{
printf("Enter the total number of elements you want to
enter : ");
scanf("%d",&count);
printf("adresses of allocatedmeroryn");
for(i = 0;i<count;++i)
printf("%ut",arr+i);
}
s1=sizeof(float);
s2=count * s1;
printf("nsize of float=%f n",s1);
printf("Size of integer type array having total %f * %f = %f
bytesn",s2/s1,s1,s2);
for(i = 0;i<count;i++)
{
//5
printf("nEnterelement %d : ",(i+1));
scanf("%f",arr+i);
//6
sum += *(arr+i);
product *= *(arr+i);
}
//7
printf("sum is %.2f n",sum);
printf("product is %.2f n",product);
//8
free(arr);
return 0;
}
*****************displaythe count of line word ans
characters***********
#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char filename1[100],filename2[100];
char ch;
int linecount,wordcount, charcount;
// Initialize countervariables
linecount = 0;
wordcount = 0;
charcount = 0;
// Prompt user to enter filename
printf("Entera filename :n");
gets(filename1);
printf("enter file name2:n");
gets(filename2);
// Open file in read-only mode
fp1 = fopen(filename1,"r");
fp2=fopen(filename2,"w");
// If file opened successfully, then write the string to file
if ( fp1 )
{
//Repeat until End Of File character is reached.
while ((ch=getc(fp1)) != EOF) {
// Increment character count if NOT new line or
space
if (ch != ' ' && ch != 'n') { ++charcount;}
// Increment word count if new line or space
character
if (ch == ' ' || ch == 'n') { ++wordcount; }
// Increment line count if new line character
if (ch == 'n') { ++linecount;}
}
if (charcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("Failedto open the filen");
}
fprintf(fp2,"Lines : %d n", linecount);
fprintf(fp2,"Words : %d n", wordcount);
fprintf(fp2,"Characters : %d n", charcount);
getchar();
return(0);
}
***********file length calculation*********
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
int size = 0;
fp = fopen("words2.txt", "r");
if (fp == NULL)
printf("nFile unableto open ");
else
printf("nFile opened ");
fseek(fp, 0, 2); /* file pointer at the end of file */
size = ftell(fp); /* take a positionof file pointer un size
variable*/
printf("The size of given file is : %dn", size);
fclose(fp);
}
**************write a sentence into a file********
#include<stdio.h>
#include<stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;
fptr = fopen("program1.txt", "w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:n");
gets(sentence);
fprintf(fptr,"%s", sentence);
fclose(fptr);
return 0;
}
*************file*********
#include<stdio.h>
int main()
{
FILE *fptr;
int i,num,marks;
char name[50];
fptr=(fopen("file1.txt","wb"));
if (fptr==NULL)
{
printf("error");
return 1;
}
for(i=0;i<num;i++)
{
printf("for student %d n enter name:",i+1);
scanf("%s",name);
printf("enter marks:");
scanf("%d",&marks);
fprintf(fptr,"n name:%s n marks=%d n",name
,marks);
}
fclose(fptr);
return 0;
}
****************
****************fseek example**********
#include<stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointerreturns NULL.
exit(1);
}
// Moves the cursor to the end of the file
fseek(fptr, sizeof(struct threeNum), SEEK_END);
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %dtn2: %dtn3: %d", num.n1, num.n2,
num.n3);
}
fclose(fptr);
return 0;
}
********************doublylinkedlist***************
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *prev;
struct node *next;
};
struct node *head = NULL;
struct node *last = NULL;
struct node *current = NULL;
//Create Linked List
void insert(int data) {
// Allocate memory for new node;
struct node *link = (struct node*) malloc(sizeof(struct
node));
link->data= data;
link->prev = NULL;
link->next = NULL;
// If head is empty, create new list
if(head==NULL) {
head = link;
return;
}
current = head;
// move to the end of the list
while(current->next!=NULL)
current = current->next;
// Insert link at the end of the list
current->next = link;
last = link;
link->prev = current;
}
//display the list
void printList() {
struct node *ptr = head;
printf("n[head]<=>");
//start from the beginning
while(ptr->next != NULL) {
printf(" %d <=>",ptr->data);
ptr = ptr->next;
}
printf(" %d <=>",ptr->data);
printf(" [head]n");
}
int main() {
insert(10);
insert(20);
insert(30);
insert(1);
insert(40);
insert(56);
printList();
return 0;
}
**************mallocmemory*****************
#include<stdio.h>
#include<stdlib.h>
struct course
{
int marks;
char subject[30];
};
int main()
{
struct course *ptr;
int i, noOfRecords;
printf("Enter number of records: ");
scanf("%d", &noOfRecords);
// Allocatesthe memory for noOfRecords structures with
pointerptr pointingto the base address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct
course));
for(i = 0; i < noOfRecords; ++i)
{
printf("Enter name of the subject and marks
respectively:n");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}
printf("DisplayingInformation:n");
for(i = 0; i < noOfRecords ; ++i)
printf("%st%dn", (ptr+i)->subject, (ptr+i)->marks);
return 0;
}
*************mallocexample***************
#include<stdio.h>
#include<stdlib.h>
struct course
{
int marks;
char subject[30];
};
int main()
{
struct course *ptr;
int i, noOfRecords;
printf("Enter number of records: ");
scanf("%d", &noOfRecords);
// Allocatesthe memory for noOfRecords structures with
pointerptr pointingto the base address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct
course));
for(i = 0; i < noOfRecords; ++i)
{
printf("Enter name of the subject and marks
respectively:n");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}
printf("DisplayingInformation:n");
for(i = 0; i < noOfRecords ; ++i)
printf("%st%dn", (ptr+i)->subject, (ptr+i)->marks);
return 0;
}
***************doublylinkedlist
1*********************
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
struct Node *prev;
}node;
void insert(node *pointer, int data)
{
/* Iterate through the list till we encounterthe last
node.*/
while(pointer->next!=NULL)
{
pointer= pointer -> next;
}
/* Allocate memory for the new node and put data in
it.*/
pointer->next = (node *)malloc(sizeof(node));
(pointer->next)->prev = pointer;
pointer = pointer->next;
pointer->data = data;
pointer->next = NULL;
}
int find(node*pointer, int key)
{
pointer = pointer -> next; //First node is dummy node.
/* Iterate through the entire linked list and search for
the key. */
while(pointer!=NULL)
{
if(pointer->data== key) //key is found.
{
return 1;
}
pointer= pointer -> next;//Search in the next node.
}
/*Key is not found */
return 0;
}
void delete(node *pointer, int data)
{
/* Go to the node for which the node next to it has to be
deleted */
while(pointer->next!=NULL && (pointer->next)->data !=
data)
{
pointer= pointer -> next;
}
if(pointer->next==NULL)
{
printf("Element %d is not present in the
listn",data);
return;
}
/* Now pointerpointsto a node and the node next to it
has to be removed */
node *temp;
temp = pointer -> next;
/*temp pointsto the node which has to be removed*/
pointer->next = temp->next;
temp->prev = pointer;
/*We removed the node which is next to the pointer
(which is also temp) */
free(temp);
/* Beacuse we deleted the node, we no longer require
the memory used for it .
free() will deallocatethe memory.
*/
return;
}
void print(node *pointer)
{
if(pointer==NULL)
{
return;
}
printf("%d ",pointer->data);
print(pointer->next);
}
int main()
{
/* start alwayspoints to the first node of the linked list.
temp is used to point to the last node of the linked
list.*/
node *start,*temp;
start = (node *)malloc(sizeof(node));
temp = start;
temp -> next = NULL;
temp -> prev = NULL;
/* Here in this code, we take the first node as a dummy
node.
The first nozdoes not contain data, but it used because
to avoid handlingspecialcases
in insert and delete functions.
*/
printf("1. Insertn");
printf("2. Deleten");
printf("3. Printn");
printf("4. Findn");
while(1)
{
int query;
scanf("%d",&query);
if(query==1)
{
int data;
scanf("%d",&data);
insert(start,data);
}
else if(query==2)
{
int data;
scanf("%d",&data);
delete(start,data);
}
else if(query==3)
{
printf("The list is ");
print(start->next);
printf("n");
}
else if(query==4)
{
int da ta;
scanf("%d",&data);
int status = find(start,data);
if(status)
{
printf("ElementFoundn");
}
else
{
printf("ElementNot Foundn");
}
}
}
}
****************binarytree using linkedlist************
/*
* C Program to Implement Binary Tree using Linked List
*/
#include<stdio.h>
#include<malloc.h>
struct node {
struct node * left;
char data;
struct node * right;
};
struct node *constructTree( int );
void inorder(struct node *);
char array[ ] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', '0', '0', 'H' };
int leftcount[ ] = { 1, 3, 5, -1, 9, -1, -1, -1, -1, -1 };
int rightcount[ ] = { 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 };
int main() {
struct node *root;
root = constructTree( 0 );
printf("In-order Traversal: n");
inorder(root);
}
struct node * constructTree( int index) {
struct node *temp = NULL;
if (index!= -1) {
temp = (struct node *)malloc( sizeof ( struct node ) );
temp->left = constructTree( leftcount[index]);
temp->data = array[index];
temp->right = constructTree( rightcount[index] );
}
return temp;
}
void inorder( struct node *root ) {
if (root != NULL) {
inorder(root->left);
printf("%ct", root->data);
inorder(root->right);
}
}
*************post to prefix************
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define MAX 20
char str[MAX], stack[MAX];
int top = -1;
char pop()
{
return stack[top--];
}
void push(char ch)
{
stack[++top] = ch;
}
void postfix_to_prefix(char expression[])
{
int count, length;
length = strlen(expression);
printf("nPrefix Expression:t");
for(count = length - 1; count >= 0; count--)
{
printf("%c", expression[count]);
}
}
int main()
{
char postfix_expression[35];
printf("nEnterPostfix Expression:t");
scanf("%s", postfix_expression);
postfix_to_prefix(postfix_expression);
printf("n");
return 0;
}
*******************bubblesort**************
#include<stdio.h>
#define MAX 10
int list[MAX] = {1,8,4,6,0,3,5,2,7,9};
void display() {
int i;
printf("[");
// navigate through all items
for(i = 0; i < MAX; i++) {
printf("%d ",list[i]);
}
printf("]n");
}
void bubbleSort() {
int temp;
int i,j;
bool swapped = false;
// loop through all numbers
for(i = 0; i < MAX-1; i++) {
swapped = false;
// loopthrough numbers falling ahead
for(j = 0; j < MAX-1-i; j++) {
printf(" Items compared: [ %d, %d ] ", list[j],list[j+1]);
// check if next number is lesser than current no
// swap the numbers.
// (Bubble up the highest number)
if(list[j] > list[j+1]) {
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
swapped = true;
printf(" => swapped [%d, %d]n",list[j],list[j+1]);
} else {
printf(" => not swappedn");
}
}
// if no number was swapped that means
// array is sorted now, break the loop.
if(!swapped) {
break;
}
printf("Iteration%d#: ",(i+1));
display();
}
}
int main() {
printf("Input Array: ");
display();
printf("n");
bubbleSort();
printf("nOutput Array: ");
display();
}
***********shell sort********************
#include<stdio.h>
#include<stdbool.h>
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
void display() {
int i;
printf("[");
// navigate through all items
for(i = 0;i < MAX;i++) {
printf("%d ",intArray[i]);
}
printf("]n");
}
void shellSort() {
int inner, outer;
int valueToInsert;
int interval = 1;
int elements = MAX;
int i = 0;
while(interval<= elements/3) {
interval= interval*3 +1;
}
while(interval> 0) {
printf("iteration%d#:",i);
display();
for(outer = interval;outer < elements; outer++) {
valueToInsert= intArray[outer];
inner = outer;
while(inner> interval -1 && intArray[inner - interval]
>= valueToInsert) {
intArray[inner] = intArray[inner - interval];
inner -=interval;
printf(" item moved :%dn",intArray[inner]);
}
intArray[inner]= valueToInsert;
printf(" item inserted :%d, at position
:%dn",valueToInsert,inner);
}
interval= (interval -1) /3;
i++;
}
}
int main() {
printf("Input Array: ");
display();
shellSort();
printf("Output Array: ");
display();
return 1;
}
*******************selectionsort***************
#include<stdio.h>
#include<stdbool.h>
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
/*void printline(intcount) {
int i;
for(i = 0;i < count-1;i++) {
printf("=");
}
printf("=n");
}*/
void display() {
int i;
printf("[");
// navigate through all items
for(i = 0;i < MAX;i++) {
printf("%d ", intArray[i]);
}
printf("]n");
}
void selectionSort() {
int indexMin,i,j;
// loop through all numbers
for(i = 0; i < MAX-1; i++) {
// set current element as minimum
indexMin= i;
// check the element to be minimum
for(j = i+1;j < MAX;j++) {
if(intArray[j] < intArray[indexMin]) {
indexMin= j;
}
}
if(indexMin!= i) {
printf("Items swapped: [ %d, %d ]n" , intArray[i],
intArray[indexMin]);
// swap the numbers
int temp = intArray[indexMin];
intArray[indexMin]= intArray[i];
intArray[i] = temp;
}
printf("Iteration%d#:",(i+1));
display();
}
}
int main() {
printf("Input Array: ");
display();
printline(50);
selectionSort();
printf("Output Array: ");
display();
printline(50);
}
**************quick sort***********
#include<stdio.h>
#include<stdbool.h>
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
void display() {
int i;
printf("[");
// navigate through all items
for(i = 0;i < MAX;i++) {
printf("%d ",intArray[i]);
}
printf("]n");
}
void swap(int num1, int num2) {
int temp = intArray[num1];
intArray[num1] = intArray[num2];
intArray[num2] = temp;
}
int partition(intleft, int right, int pivot) {
int leftPointer = left -1;
int rightPointer = right;
while(true) {
while(intArray[++leftPointer]< pivot) {
//do nothing
}
while(rightPointer> 0 && intArray[--rightPointer] > pivot)
{
//do nothing
}
if(leftPointer >= rightPointer) {
break;
} else {
printf(" item swapped :%d,%dn",
intArray[leftPointer],intArray[rightPointer]);
swap(leftPointer,rightPointer);
}
}
printf(" pivot swapped :%d,%dn",
intArray[leftPointer],intArray[right]);
swap(leftPointer,right);
printf("Updated Array: ");
display();
return leftPointer;
}
void quickSort(int left, int right) {
if(right-left <= 0) {
return;
} else {
int pivot = intArray[right];
int partitionPoint= partition(left,right, pivot);
quickSort(left,partitionPoint-1);
quickSort(partitionPoint+1,right);
}
}
int main() {
printf("Input Array: ");
display();
quickSort(0,MAX-1);
printf("Output Array: ");
display();
}
*******************stack*************
#include<stdio.h>
#include<stdlib.h>
int stack[5];
int push();
int pop();
void traverse();
int is_empty();
int top_element();
int top = 0;
int main()
{
int element, choice;
for (;;)
{
printf("Stack Operations.n");
printf("1. Insert into stack (Push operation).n");
printf("2. Delete from stack (Pop operation).n");
printf("3. Print top element of stack.n");
printf("4. Check if stack is empty.n");
printf("5. Traverse stack.n");
printf("6. Exit.n");
printf("Enteryour choice.n");
scanf("%d",&choice);
switch (choice)
{
case 1:
if (top == 5)
printf("Error: Overflownn");
else {
printf("Enter the value to insert.n");
scanf("%d", &element);
push(element);
}
break;
case 2:
if (top == 0)
printf("Error: Underflow.nn");
else {
element = pop();
printf("Element removed from stack is %d.n",
element);
}
break;
case 3:
if (!is_empty()) {
element = top_element();
printf("Element at the top of stack is %dnn",
element);
}
else
printf("Stack is empty.nn");
break;
case 4:
if (is_empty())
printf("Stack is empty.nn");
else
printf("Stack isn't empty.nn");
break;
case 5:
traverse();
break;
case 6:
exit(0);
}
}
}
void push(int value) {
stack[top] = value;
top++;
}
int pop() {
top--;
return stack[top];
}
void traverse() {
int d;
if (top == 0) {
printf("Stack is empty.nn");
return;
}
printf("There are %d elements in stack.n", top);
for (d = top - 1; d >= 0; d--)
printf("%dn", stack[d]);
printf("n");
}
int is_empty() {
if (top == 0)
return 1;
else
return 0;
}
int top_element() {
return stack[top-1];
}

Mais conteúdo relacionado

Mais procurados

Double linked list
Double linked listDouble linked list
Double linked listSayantan Sur
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robinAbdullah Al Naser
 
System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical fileAnkit Dixit
 
Double linked list
Double linked listDouble linked list
Double linked listraviahuja11
 
various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)
various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)
various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)CODE BLUE
 
C program to insert a node in doubly linked list
C program to insert a node in doubly linked listC program to insert a node in doubly linked list
C program to insert a node in doubly linked listSourav Gayen
 
Defcon 23 - Daniel Selifonov - drinking from LETHE
Defcon 23 - Daniel Selifonov - drinking from LETHEDefcon 23 - Daniel Selifonov - drinking from LETHE
Defcon 23 - Daniel Selifonov - drinking from LETHEFelipe Prado
 
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานการเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานminkminkk
 
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานการเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานminkminkk
 
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานการเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานminkminkk
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซีkramsri
 
Travel management
Travel managementTravel management
Travel management1Parimal2
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซีkramsri
 
The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189Mahmoud Samir Fayed
 
Testing CLI tools with Go
Testing CLI tools with GoTesting CLI tools with Go
Testing CLI tools with GoRicardo Gerardi
 

Mais procurados (20)

Double linked list
Double linked listDouble linked list
Double linked list
 
Let's golang
Let's golangLet's golang
Let's golang
 
Linked lists
Linked listsLinked lists
Linked lists
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robin
 
System programs in C language.
System programs in C language.System programs in C language.
System programs in C language.
 
Quiz using C++
Quiz using C++Quiz using C++
Quiz using C++
 
System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical file
 
Gps c
Gps cGps c
Gps c
 
Double linked list
Double linked listDouble linked list
Double linked list
 
various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)
various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)
various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)
 
C program to insert a node in doubly linked list
C program to insert a node in doubly linked listC program to insert a node in doubly linked list
C program to insert a node in doubly linked list
 
Defcon 23 - Daniel Selifonov - drinking from LETHE
Defcon 23 - Daniel Selifonov - drinking from LETHEDefcon 23 - Daniel Selifonov - drinking from LETHE
Defcon 23 - Daniel Selifonov - drinking from LETHE
 
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานการเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
 
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานการเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
 
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐานการเขียนคำสั่งควบคุมขั้นพื้นฐาน
การเขียนคำสั่งควบคุมขั้นพื้นฐาน
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
 
Travel management
Travel managementTravel management
Travel management
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
 
The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189
 
Testing CLI tools with Go
Testing CLI tools with GoTesting CLI tools with Go
Testing CLI tools with Go
 

Semelhante a Data structures

Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfjillisacebi75827
 
Sorting programs
Sorting programsSorting programs
Sorting programsVarun Garg
 
The solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinThe solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinShariful Haque Robin
 
int ch=chdir(tokensleft[0]); if the change of director.pdf
      int ch=chdir(tokensleft[0]);     if the change of director.pdf      int ch=chdir(tokensleft[0]);     if the change of director.pdf
int ch=chdir(tokensleft[0]); if the change of director.pdfmdualudin007
 
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docxcmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docxgordienaysmythe
 
C programs Set 4
C programs Set 4C programs Set 4
C programs Set 4Koshy Geoji
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handlingargusacademy
 
#include stdio.h #include stdlib.h #include time.h #incl.pdf
#include stdio.h #include stdlib.h #include time.h #incl.pdf#include stdio.h #include stdlib.h #include time.h #incl.pdf
#include stdio.h #include stdlib.h #include time.h #incl.pdfrishabjain5053
 
C-Program Custom Library, Header File, and Implementation FilesI .pdf
C-Program Custom Library, Header File, and Implementation FilesI .pdfC-Program Custom Library, Header File, and Implementation FilesI .pdf
C-Program Custom Library, Header File, and Implementation FilesI .pdfherminaherman
 
C basics
C basicsC basics
C basicsMSc CST
 
In C programming- I'm working on a shell and I have a function to pars.pdf
In C programming- I'm working on a shell and I have a function to pars.pdfIn C programming- I'm working on a shell and I have a function to pars.pdf
In C programming- I'm working on a shell and I have a function to pars.pdfshreeaadithyaacellso
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)mrecedu
 
#include iostream #include cstring #include vector #i.pdf
 #include iostream #include cstring #include vector #i.pdf #include iostream #include cstring #include vector #i.pdf
#include iostream #include cstring #include vector #i.pdfanandatalapatra
 

Semelhante a Data structures (20)

Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdf
 
Sorting programs
Sorting programsSorting programs
Sorting programs
 
The solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinThe solution manual of programming in ansi by Robin
The solution manual of programming in ansi by Robin
 
int ch=chdir(tokensleft[0]); if the change of director.pdf
      int ch=chdir(tokensleft[0]);     if the change of director.pdf      int ch=chdir(tokensleft[0]);     if the change of director.pdf
int ch=chdir(tokensleft[0]); if the change of director.pdf
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docxcmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
 
C programs Set 4
C programs Set 4C programs Set 4
C programs Set 4
 
Files
FilesFiles
Files
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
#include stdio.h #include stdlib.h #include time.h #incl.pdf
#include stdio.h #include stdlib.h #include time.h #incl.pdf#include stdio.h #include stdlib.h #include time.h #incl.pdf
#include stdio.h #include stdlib.h #include time.h #incl.pdf
 
C program
C programC program
C program
 
Vcs26
Vcs26Vcs26
Vcs26
 
C-Program Custom Library, Header File, and Implementation FilesI .pdf
C-Program Custom Library, Header File, and Implementation FilesI .pdfC-Program Custom Library, Header File, and Implementation FilesI .pdf
C-Program Custom Library, Header File, and Implementation FilesI .pdf
 
C basics
C basicsC basics
C basics
 
In C programming- I'm working on a shell and I have a function to pars.pdf
In C programming- I'm working on a shell and I have a function to pars.pdfIn C programming- I'm working on a shell and I have a function to pars.pdf
In C programming- I'm working on a shell and I have a function to pars.pdf
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
 
Cquestions
Cquestions Cquestions
Cquestions
 
C Language Unit-5
C Language Unit-5C Language Unit-5
C Language Unit-5
 
#include iostream #include cstring #include vector #i.pdf
 #include iostream #include cstring #include vector #i.pdf #include iostream #include cstring #include vector #i.pdf
#include iostream #include cstring #include vector #i.pdf
 

Último

ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchrohitcse52
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesDIPIKA83
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Sean Meyn
 
solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging systemgokuldongala
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Bahzad5
 
The relationship between iot and communication technology
The relationship between iot and communication technologyThe relationship between iot and communication technology
The relationship between iot and communication technologyabdulkadirmukarram03
 
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS Bahzad5
 
Clutches and brkesSelect any 3 position random motion out of real world and d...
Clutches and brkesSelect any 3 position random motion out of real world and d...Clutches and brkesSelect any 3 position random motion out of real world and d...
Clutches and brkesSelect any 3 position random motion out of real world and d...sahb78428
 
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Amil baba
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxrealme6igamerr
 
nvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxnvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxjasonsedano2
 
Nodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxNodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxwendy cai
 
Landsman converter for power factor improvement
Landsman converter for power factor improvementLandsman converter for power factor improvement
Landsman converter for power factor improvementVijayMuni2
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptxSaiGouthamSunkara
 
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....santhyamuthu1
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxNaveenVerma126
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecTrupti Shiralkar, CISSP
 

Último (20)

ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display Devices
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
 
solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging system
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)
 
The relationship between iot and communication technology
The relationship between iot and communication technologyThe relationship between iot and communication technology
The relationship between iot and communication technology
 
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
 
Clutches and brkesSelect any 3 position random motion out of real world and d...
Clutches and brkesSelect any 3 position random motion out of real world and d...Clutches and brkesSelect any 3 position random motion out of real world and d...
Clutches and brkesSelect any 3 position random motion out of real world and d...
 
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
 
nvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxnvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptx
 
Lecture 4 .pdf
Lecture 4                              .pdfLecture 4                              .pdf
Lecture 4 .pdf
 
計劃趕得上變化
計劃趕得上變化計劃趕得上變化
計劃趕得上變化
 
Lecture 2 .pptx
Lecture 2                            .pptxLecture 2                            .pptx
Lecture 2 .pptx
 
Nodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxNodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptx
 
Landsman converter for power factor improvement
Landsman converter for power factor improvementLandsman converter for power factor improvement
Landsman converter for power factor improvement
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptx
 
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
 

Data structures

  • 1. DATA STRUCTURES ************acess element using pointer***************** #include<stdio.h> int main() { int data[5], i; printf("Enter elements: "); for(i = 0; i < 5; ++i) scanf("%d", data + i); printf("You entered: n"); for(i = 0; i < 5; ++i) printf("%dn", *(data + i)); return 0; } *****************addmaloc*****************
  • 2. #include<stdio.h> #include<stdlib.h> int main() { //1 int i,j; int count; int *arr; int sum = 0; int product=1; //2 arr = (int *)malloc(count* sizeof(int)); printf("Enter the total number of elements you want to enter : "); scanf("%d",&count); printf("adresses of allocatedmeroryn"); for(i = 0;i<count;++i) printf("%ut",arr+i);
  • 3. //4 for(i = 0;i<count;i++){ //5 printf("nEnterelement %d : ",(i+1)); scanf("%d",arr+i); //6 sum += *(arr+i); product *= *(arr+i); } //7 printf("sum is %d n",sum); printf("product is %d n",product); //8 free(arr); return 0; } ******************addmaloc size************** #include<stdio.h> #include<stdlib.h>
  • 4. int main() { //1 int i,j,s1,s2; int count; int *arr; int sum = 0; int product=1; //2 arr = (int *)malloc(count* sizeof(int)); printf("Enter the total number of elements you want to enter : "); scanf("%d",&count); printf("adresses of allocatedmeroryn"); for(i = 0;i<count;++i) printf("%ut",arr+i); s1=sizeof(int); s2=count * s1; printf("size of int=%d , size of one data =%dn",s1,s2);
  • 5. printf("Size of integer type array having total %d * %d = %d bytesn",s2/s1,s1,s2); for(i = 0;i<count;i++) { //5 printf("nEnterelement %d : ",(i+1)); scanf("%d",arr+i); //6 sum += *(arr+i); product *= *(arr+i); } //7 printf("sum is %d n",sum); printf("product is %d n",product); //8 free(arr); return 0; } **************reallocatingthe memory to 0***************
  • 6. #include<stdio.h> #include<stdlib.h> int main(void) { int *ptr = (int*) malloc(10); /* we are calling realloc with size = 0 */ realloc(ptr, 0); return 0; } *****************limittest using malloc*********** /*C program to input and print text using Dynamic Memory Allocation.*/ #include<stdio.h> #include<stdlib.h>
  • 7. int main() { int n; char *text; printf("Enterlimit of the text: "); scanf("%d",&n); /*allocatememory dynamically*/ text=(char*)malloc(n*sizeof(char)); printf("Entertext: "); scanf(" "); /*clear input buffer*/ gets(text); printf("Inputtedtext is: %sn",text); /*Free Memory*/ free(text);
  • 8. return 0; } ****************malloc********** #include<stdio.h> main() { float *list, sortnum, j, average = 0, sum = 0; printf("Enter the number of data pointsto average: "); scanf("%f",&sortnum); list = (float *)malloc(sortnum * sizeof(int)); for (j = 0; j < sortnum; j++) scanf("%f", list + j); printf("You entered the following:n");
  • 9. for (j = 0; j < sortnum; j++) printf("%fn", *(list + j)); free(list); return 0; } ******************calloc******************** #include<stdio.h> #include<stdlib.h> int main() { int i, num; float *data; printf("Entertotal number of elements(1 to 100): "); scanf("%d", &num); // Allocatesthe memory for 'num' elements. data = (float*) calloc(num, sizeof(float));
  • 10. if(data == NULL) { printf("Error!!! memory not allocated."); exit(0); } printf("n"); // Stores the number entered by the user. for(i = 0; i < num; ++i) { printf("Enter Number %d: ", i + 1); scanf("%f", data + i); } // Loop to store largest number at address data for(i = 1; i < num; ++i) { // Change < to > if you want to find the smallest number
  • 11. if(*data < *(data + i)) *data = *(data + i); } printf("Largest element = %.2f", *data); return 0; } *******************array additionand multiplication using pointers************* #include<stdio.h> main() { int arr[5]; int sum,product, i; int s1=sizeof(arr); int s2=sizeof(int);
  • 12. printf("Size of int=%d bytesn",s2); printf("Size of one data=%d bytesn",sizeof(arr[0])); printf("Size of integer type array having %d elements = %d bytesn",s1/s2, s1); /*read array elements*/ printf("nenter elements:n"); for(i=0;i<5;i++) { printf("enter arr[%d]",i); scanf("%d",&arr[i]); } /*calculate sum and product*/ sum=0; product=1; for(i=0;i<5;i++) { sum=sum+arr[i]; product=product*arr[i]; } printf("nsum of array is: %d",sum);
  • 13. printf("nproduct of array is: %d",product); } *****************binaryfile using fwrite with pointer*************** #include<stdio.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:program.bin","wb")) == NULL){
  • 14. printf("Error! opening file"); // Program exits if the file pointerreturns NULL. exit(1); } for(n = 1; n < 5; ++n) { num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } fclose(fptr); return 0; } ***************code to read a file*********** #include<stdio.h>
  • 15. #include<stdlib.h> // For exit() function int main() { char c[1000]; FILE *fptr; if ((fptr = fopen("program.txt", "r")) == NULL) { printf("Error! openingfile"); // Program exits if file pointer returns NULL. exit(1); } // reads text until newline fscanf(fptr,"%[^n]", c); printf("Datafrom the file:n%s", c); fclose(fptr); return 0;
  • 16. } ****************reverse in a file********** /* * C Program to Reverse the Contents of a File and Print it */ #include<stdio.h> #include<errno.h> long count_characters(FILE *); int main()
  • 17. { int i; long cnt; char ch, ch1; FILE *fp1, *fp2; if (fp1 = fopen("file1.txt", "r")) { printf("The FILE hasbeen opened...n"); fp2 = fopen("file123.txt", "w");
  • 18. cnt = count_characters(fp1); // to count the total number of characters inside the source file fseek(fp1, -1L, 2); // makes the pointerfp1 to point at the last character of the file printf("Number of characters to be copied %dn", ftell(fp1)); while (cnt) { ch = fgetc(fp1); fputc(ch, fp2); fseek(fp1, -2L, 1); // shifts the pointerto the previouscharacter
  • 19. cnt--; } printf("n**File copied successfully in reverse order**n"); } else { perror("Error occuredn"); } fclose(fp1);
  • 20. fclose(fp2); } // count the total number of characters in the file that *f pointsto long count_characters(FILE *f) { fseek(f, -1L, 2); long last_pos= ftell(f); // returns the positionof the last element of the file last_pos++; return last_pos;
  • 21. } ******************struct student in file******* #include<stdio.h> struct student { char name[50]; int height; }; int main(){ struct student stud1[5], stud2[5]; FILE *fptr; int i; fptr = fopen("file.txt","wb"); for(i = 0; i < 5; ++i) { fflush(stdin); printf("Enter name: "); gets(stud1[i].name);
  • 22. printf("Enter height: "); scanf("%d", &stud1[i].height); } fwrite(stud1, sizeof(stud1), 1, fptr); fclose(fptr); fptr = fopen("file.txt", "rb"); fread(stud2, sizeof(stud2), 1, fptr); for(i = 0; i < 5; ++i) { printf("Name: %snHeight: %d", stud2[i].name, stud2[i].height); } fclose(fptr); } **************write student data into file********* #include<stdio.h> int main() {
  • 23. char name[50]; int marks, i, num; printf("Enter number of students: "); scanf("%d", &num); FILE *fptr; fptr = (fopen("student.txt", "w")); if(fptr == NULL) { printf("Error!"); return 0; } for(i = 0; i < num; ++i) { printf("Forstudent%dnEnter name: ", i+1); scanf("%s", name); printf("Entermarks: ");
  • 24. scanf("%d", &marks); fprintf(fptr,"nName: %s nMarks=%d n", name, marks); } fclose(fptr); return 0; } ***************concatenatefiles*************** #include<stdio.h> #include<stdlib.h> int main() { FILE *fs1, *fs2, *ft,*fs3; char ch, file1[20], file2[20], file3[20],ch1; int charcount,wordcount,linecount;
  • 25. printf("Enter name of first filen"); gets(file1); printf("Enter name of second filen"); gets(file2); printf("Enter name of file which will store contents of the two filesn"); gets(file3); fs1 = fopen(file1, "r"); fs2 = fopen(file2, "r"); if(fs1 == NULL || fs2 == NULL) { perror("Error "); printf("Press any key to exit...n"); exit(EXIT_FAILURE); }
  • 26. ft = fopen(file3, "w"); // Opening in write mode if(ft == NULL) { perror("Error "); printf("Press any key to exit...n"); exit(EXIT_FAILURE); } while((ch = fgetc(fs1)) != EOF) fputc(ch,ft); while((ch = fgetc(fs2)) != EOF) fputc(ch,ft); printf("The two files were merged into %s file successfully.n", file3); { ft=fopen(file3,"r");
  • 27. fs3=fopen("file3.txt","w"); if (ft) { while ((ch1=getc(ft)) != EOF) { // Increment character count if NOT new line or space if (ch1 != ' ' && ch1 != 'n') { ++charcount; } // Increment word count if new line or space character if (ch1 == ' ' || ch1 == 'n') { ++wordcount; } // Increment line count if new line character if (ch1 == 'n') { ++linecount;} } if (charcount > 0) { ++linecount;
  • 28. ++wordcount; } } else { printf("Failedto open the filen"); } fprintf(fs3,"Lines : %d n", linecount); fprintf(fs3,"Words : %d n", wordcount); fprintf(fs3,"Characters : %d n", charcount); getchar(); fclose(fs1); fclose(fs2); fclose(ft); fclose(fs3);
  • 29. } return 0; } **************to count word and character********** #include<stdio.h> int main() { FILE *fp1,*fp2; char filename1[100],filename2[100]; char ch; int linecount,wordcount, charcount; // Initialize countervariables linecount = 0; wordcount = 0; charcount = 0; // Prompt user to enter filename printf("Entera filename :n");
  • 30. gets(filename1); printf("enter file name2:n"); gets(filename2); // Open file in read-only mode fp1 = fopen(filename1,"r"); fp2=fopen(filename2,"w"); // If file opened successfully, then write the string to file if ( fp1 ) { //Repeat until End Of File character is reached. while ((ch=getc(fp1)) != EOF) { // Increment character count if NOT new line or space if (ch != ' ' && ch != 'n') { ++charcount;} // Increment word count if new line or space character if (ch == ' ' || ch == 'n') { ++wordcount; }
  • 31. // Increment line count if new line character if (ch == 'n') { ++linecount;} } if (charcount > 0) { ++linecount; ++wordcount; } } else { printf("Failedto open the filen"); } fprintf(fp2,"Lines : %d n", linecount); fprintf(fp2,"Words : %d n", wordcount);
  • 32. fprintf(fp2,"Characters : %d n", charcount); getchar(); return(0); } ***********concatenatetwo files************ #include<stdio.h> int main() { FILE *fp1,*fp2,*fp3; int i,j,temp,count1,count,size,size2; char str[100]={"This is a pattern matching"}; char substr[20]={"pattern"}; char ch[100],ch1[100],filename1[100],filename2[100],filename3[1 00]; printf("Entera filename :n"); gets(filename1); printf("enter file name2:n");
  • 33. gets(filename2); printf("enter file name2:n"); gets(filename3); // Open file in read-only mode fp1 = fopen(filename1,"r"); fp2=fopen(filename2,"r"); fp3=fopen(filename3,"w"); if(fp1&&fp2) { while((ch[i]= fgetc(fp1)) != EOF) fseek(fp1, 0, 2); /* file pointerat the end of file */ size = ftell(fp1); /* take a positionof file pointerun size variable*/ while((ch1[i] = fgetc(fp2)) != EOF) fseek(fp2, 0, 2); /* file pointer at the end of file */
  • 34. size2 = ftell(fp2); /* take a position of file pointerun size variable*/ for (i = 0; i < size;) { j = 0; count = 0; while ((ch[i] == ch1[j])) { count++; i++;
  • 35. j++; } if (count == size2) { count1++; count = 0; } else i++; }
  • 36. fprintf(fp3," %d times in %s",count1, str); } } return 0; } ***************employ record using files******** /* * C Program to Update Detailsof Employee using Files */ #include<stdio.h> #include<stdlib.h> #include<string.h>
  • 37. struct emp { int empid; char *name; }; int count = 0; void add_rec(char*a); void display(char*a); void update_rec(char*a);
  • 38. void main(intargc, char *argv[]) { int choice; while (1) { printf("MENU:n"); printf("1.Add a recordn"); printf("2.Displaythe filen"); printf("3.Update the recordn");
  • 39. printf("Enter your choice:"); scanf("%d", &choice); switch(choice) { case 1: add_rec(argv[1]); break; case 2: display(argv[1]);
  • 41. } void add_rec(char*a) { FILE *fp; fp = fopen(a, "a+"); struct emp *temp = (struct emp *)malloc(sizeof(struct emp)); temp->name = (char *)malloc(50*sizeof(char)); if (fp == NULL)
  • 42. printf("Error!!!"); else { printf("Enter the employee idn"); scanf("%d", &temp->empid); fwrite(&temp->empid, sizeof(int), 1, fp); printf("enter the employee namen"); scanf(" %[^n]s", temp->name); fwrite(temp->name, 50, 1, fp); count++;
  • 44. int rec = count; fp = fopen(a, "r"); struct emp *temp = (struct emp *)malloc(sizeof(struct emp)); temp->name = (char *)malloc(50*sizeof(char)); if (fp == NULL) printf("Error!!"); else { while (rec) {
  • 45. fread(&temp->empid, sizeof(int), 1, fp); printf("%d", temp->empid); fread(temp->name, 50, 1, fp); printf(" %sn", temp->name); rec--; } } fclose(fp); free(temp); free(temp->name);
  • 46. } void update_rec(char*a) { FILE *fp; char ch, name[5]; int rec, id, c; fp = fopen(a, "r+"); struct emp *temp = (struct emp *)malloc(sizeof(struct emp));
  • 47. temp->name = (char *)malloc(50*sizeof(char)); printf("Enter the employee id to update:n"); scanf("%d", &id); fseek(fp, 0, 0); rec = count; while (rec) { fread(&temp->empid, sizeof(int), 1, fp); printf("%d", temp->empid); if (id == temp->empid)
  • 48. { printf("Enterthe employee name to be updated"); scanf(" %[^n]s", name); c = fwrite(name, 50, 1, fp); break; } fread(temp->name, 50, 1, fp); rec--; } if (c == 1)
  • 49. printf("Record updatedn"); else printf("Update not successfuln"); fclose(fp); free(temp); free(temp->name); } *****************delete a displayedtree********* #include<stdio.h> int array[100], n;
  • 50. main() { int choice, num; n = 0;/*Represents number of nodes in the heap*/ while(1) { printf("1.Insert the element n"); printf("2.Delete the element n"); printf("3.Display all elements n"); printf("4.Quit n");
  • 51. printf("Enter your choice : "); scanf("%d", &choice); switch(choice) { case 1: printf("Enter the element to be inserted to the list : "); scanf("%d", &num); insert(num, n); n = n + 1; break;
  • 52. case 2: printf("Enter the elements to be deleted from the list: "); scanf("%d", &num); delete(num); break; case 3: display(); break; case 4: exit(0);
  • 53. default: printf("Invalidchoice n"); }/*End of switch */ }/*End of while */ }/*End of main()*/ display() { int i; if (n == 0)
  • 54. { printf("Heap is empty n"); return; } for (i = 0; i < n; i++) printf("%d ", array[i]); printf("n"); }/*End of display()*/ insert(int num, int location)
  • 55. { int parentnode; while (location> 0) { parentnode =(location - 1)/2; if (num <= array[parentnode]) { array[location]= num; return; }
  • 56. array[location]= array[parentnode]; location = parentnode; }/*End of while*/ array[0] = num; /*assign number to the root node */ }/*End of insert()*/ delete(int num) { int left, right, i, temp, parentnode;
  • 57. for (i = 0; i < num; i++) { if (num == array[i]) break; } if (num != array[i]) { printf("%d not found in heap listn", num); return; } array[i] = array[n - 1];
  • 58. n = n - 1; parentnode=(i - 1) / 2; /*find parentnode of node i */ if (array[i] > array[parentnode]) { insert(array[i], i); return; } left = 2 * i + 1; /*left child of i*/ right = 2 * i + 2; /* right childof i*/ while (right < n)
  • 59. { if (array[i] >= array[left] && array[i] >= array[right]) return; if (array[right] <= array[left]) { temp = array[i]; array[i] = array[left]; array[left] = temp; i = left; }
  • 60. else { temp = array[i]; array[i] = array[right]; array[right] = temp; i = right; } left = 2 * i + 1; right = 2 * i + 2; }/*End of while*/
  • 61. if (left == n - 1 && array[i]) { temp = array[i]; array[i] = array[left]; array[left] = temp; } } **********************float multiplicationusing malloc************ #include<stdio.h> #include<stdlib.h> main() { //1
  • 62. int i,j,s1,s2; float count; float *arr; int sum = 0; int product=1; //2 arr = (float *)malloc(count* sizeof(float)); { printf("Enter the total number of elements you want to enter : "); scanf("%d",&count); printf("adresses of allocatedmeroryn"); for(i = 0;i<count;++i) printf("%ut",arr+i); } s1=sizeof(float); s2=count * s1; printf("nsize of float=%f n",s1);
  • 63. printf("Size of integer type array having total %f * %f = %f bytesn",s2/s1,s1,s2); for(i = 0;i<count;i++) { //5 printf("nEnterelement %d : ",(i+1)); scanf("%f",arr+i); //6 sum += *(arr+i); product *= *(arr+i); } //7 printf("sum is %.2f n",sum); printf("product is %.2f n",product); //8 free(arr); return 0; } *****************displaythe count of line word ans characters***********
  • 64. #include<stdio.h> int main() { FILE *fp1,*fp2; char filename1[100],filename2[100]; char ch; int linecount,wordcount, charcount; // Initialize countervariables linecount = 0; wordcount = 0; charcount = 0; // Prompt user to enter filename printf("Entera filename :n"); gets(filename1); printf("enter file name2:n"); gets(filename2); // Open file in read-only mode
  • 65. fp1 = fopen(filename1,"r"); fp2=fopen(filename2,"w"); // If file opened successfully, then write the string to file if ( fp1 ) { //Repeat until End Of File character is reached. while ((ch=getc(fp1)) != EOF) { // Increment character count if NOT new line or space if (ch != ' ' && ch != 'n') { ++charcount;} // Increment word count if new line or space character if (ch == ' ' || ch == 'n') { ++wordcount; } // Increment line count if new line character if (ch == 'n') { ++linecount;}
  • 66. } if (charcount > 0) { ++linecount; ++wordcount; } } else { printf("Failedto open the filen"); } fprintf(fp2,"Lines : %d n", linecount); fprintf(fp2,"Words : %d n", wordcount); fprintf(fp2,"Characters : %d n", charcount); getchar(); return(0); }
  • 67. ***********file length calculation********* #include<stdio.h> int main() { FILE *fp; char ch; int size = 0; fp = fopen("words2.txt", "r"); if (fp == NULL)
  • 68. printf("nFile unableto open "); else printf("nFile opened "); fseek(fp, 0, 2); /* file pointer at the end of file */ size = ftell(fp); /* take a positionof file pointer un size variable*/ printf("The size of given file is : %dn", size); fclose(fp); } **************write a sentence into a file******** #include<stdio.h> #include<stdlib.h> /* For exit() function */
  • 69. int main() { char sentence[1000]; FILE *fptr; fptr = fopen("program1.txt", "w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf("Enter a sentence:n"); gets(sentence); fprintf(fptr,"%s", sentence); fclose(fptr); return 0; }
  • 70. *************file********* #include<stdio.h> int main() { FILE *fptr; int i,num,marks; char name[50]; fptr=(fopen("file1.txt","wb")); if (fptr==NULL) { printf("error"); return 1; } for(i=0;i<num;i++) { printf("for student %d n enter name:",i+1); scanf("%s",name); printf("enter marks:"); scanf("%d",&marks);
  • 71. fprintf(fptr,"n name:%s n marks=%d n",name ,marks); } fclose(fptr); return 0; } **************** ****************fseek example********** #include<stdio.h> struct threeNum { int n1, n2, n3; }; int main() {
  • 72. int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:program.bin","rb")) == NULL){ printf("Error! opening file"); // Program exits if the file pointerreturns NULL. exit(1); } // Moves the cursor to the end of the file fseek(fptr, sizeof(struct threeNum), SEEK_END); for(n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %dtn2: %dtn3: %d", num.n1, num.n2, num.n3); } fclose(fptr);
  • 73. return 0; } ********************doublylinkedlist*************** #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *prev; struct node *next; }; struct node *head = NULL; struct node *last = NULL; struct node *current = NULL;
  • 74. //Create Linked List void insert(int data) { // Allocate memory for new node; struct node *link = (struct node*) malloc(sizeof(struct node)); link->data= data; link->prev = NULL; link->next = NULL; // If head is empty, create new list if(head==NULL) { head = link; return; } current = head; // move to the end of the list while(current->next!=NULL)
  • 75. current = current->next; // Insert link at the end of the list current->next = link; last = link; link->prev = current; } //display the list void printList() { struct node *ptr = head; printf("n[head]<=>"); //start from the beginning while(ptr->next != NULL) { printf(" %d <=>",ptr->data); ptr = ptr->next; }
  • 76. printf(" %d <=>",ptr->data); printf(" [head]n"); } int main() { insert(10); insert(20); insert(30); insert(1); insert(40); insert(56); printList(); return 0; } **************mallocmemory***************** #include<stdio.h> #include<stdlib.h> struct course
  • 77. { int marks; char subject[30]; }; int main() { struct course *ptr; int i, noOfRecords; printf("Enter number of records: "); scanf("%d", &noOfRecords); // Allocatesthe memory for noOfRecords structures with pointerptr pointingto the base address. ptr = (struct course*) malloc (noOfRecords * sizeof(struct course)); for(i = 0; i < noOfRecords; ++i) { printf("Enter name of the subject and marks respectively:n");
  • 78. scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks); } printf("DisplayingInformation:n"); for(i = 0; i < noOfRecords ; ++i) printf("%st%dn", (ptr+i)->subject, (ptr+i)->marks); return 0; } *************mallocexample*************** #include<stdio.h> #include<stdlib.h> struct course { int marks; char subject[30]; };
  • 79. int main() { struct course *ptr; int i, noOfRecords; printf("Enter number of records: "); scanf("%d", &noOfRecords); // Allocatesthe memory for noOfRecords structures with pointerptr pointingto the base address. ptr = (struct course*) malloc (noOfRecords * sizeof(struct course)); for(i = 0; i < noOfRecords; ++i) { printf("Enter name of the subject and marks respectively:n"); scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks); } printf("DisplayingInformation:n");
  • 80. for(i = 0; i < noOfRecords ; ++i) printf("%st%dn", (ptr+i)->subject, (ptr+i)->marks); return 0; } ***************doublylinkedlist 1********************* #include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node *next; struct Node *prev; }node; void insert(node *pointer, int data) { /* Iterate through the list till we encounterthe last node.*/ while(pointer->next!=NULL)
  • 81. { pointer= pointer -> next; } /* Allocate memory for the new node and put data in it.*/ pointer->next = (node *)malloc(sizeof(node)); (pointer->next)->prev = pointer; pointer = pointer->next; pointer->data = data; pointer->next = NULL; } int find(node*pointer, int key) { pointer = pointer -> next; //First node is dummy node. /* Iterate through the entire linked list and search for the key. */ while(pointer!=NULL) { if(pointer->data== key) //key is found. {
  • 82. return 1; } pointer= pointer -> next;//Search in the next node. } /*Key is not found */ return 0; } void delete(node *pointer, int data) { /* Go to the node for which the node next to it has to be deleted */ while(pointer->next!=NULL && (pointer->next)->data != data) { pointer= pointer -> next; } if(pointer->next==NULL) { printf("Element %d is not present in the listn",data); return;
  • 83. } /* Now pointerpointsto a node and the node next to it has to be removed */ node *temp; temp = pointer -> next; /*temp pointsto the node which has to be removed*/ pointer->next = temp->next; temp->prev = pointer; /*We removed the node which is next to the pointer (which is also temp) */ free(temp); /* Beacuse we deleted the node, we no longer require the memory used for it . free() will deallocatethe memory. */ return; } void print(node *pointer) { if(pointer==NULL) {
  • 84. return; } printf("%d ",pointer->data); print(pointer->next); } int main() { /* start alwayspoints to the first node of the linked list. temp is used to point to the last node of the linked list.*/ node *start,*temp; start = (node *)malloc(sizeof(node)); temp = start; temp -> next = NULL; temp -> prev = NULL; /* Here in this code, we take the first node as a dummy node. The first nozdoes not contain data, but it used because to avoid handlingspecialcases in insert and delete functions. */
  • 85. printf("1. Insertn"); printf("2. Deleten"); printf("3. Printn"); printf("4. Findn"); while(1) { int query; scanf("%d",&query); if(query==1) { int data; scanf("%d",&data); insert(start,data); } else if(query==2) { int data; scanf("%d",&data); delete(start,data); }
  • 86. else if(query==3) { printf("The list is "); print(start->next); printf("n"); } else if(query==4) { int da ta; scanf("%d",&data); int status = find(start,data); if(status) { printf("ElementFoundn"); } else { printf("ElementNot Foundn"); }
  • 87. } } } ****************binarytree using linkedlist************ /* * C Program to Implement Binary Tree using Linked List */ #include<stdio.h> #include<malloc.h> struct node {
  • 88. struct node * left; char data; struct node * right; }; struct node *constructTree( int ); void inorder(struct node *); char array[ ] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', '0', '0', 'H' }; int leftcount[ ] = { 1, 3, 5, -1, 9, -1, -1, -1, -1, -1 };
  • 89. int rightcount[ ] = { 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 }; int main() { struct node *root; root = constructTree( 0 ); printf("In-order Traversal: n"); inorder(root); } struct node * constructTree( int index) {
  • 90. struct node *temp = NULL; if (index!= -1) { temp = (struct node *)malloc( sizeof ( struct node ) ); temp->left = constructTree( leftcount[index]); temp->data = array[index]; temp->right = constructTree( rightcount[index] ); } return temp; }
  • 91. void inorder( struct node *root ) { if (root != NULL) { inorder(root->left); printf("%ct", root->data); inorder(root->right); } } *************post to prefix************ #include<string.h> #include<stdio.h> #include<stdlib.h> #define MAX 20
  • 92. char str[MAX], stack[MAX]; int top = -1; char pop() { return stack[top--]; } void push(char ch) { stack[++top] = ch; } void postfix_to_prefix(char expression[]) { int count, length; length = strlen(expression); printf("nPrefix Expression:t"); for(count = length - 1; count >= 0; count--)
  • 93. { printf("%c", expression[count]); } } int main() { char postfix_expression[35]; printf("nEnterPostfix Expression:t"); scanf("%s", postfix_expression); postfix_to_prefix(postfix_expression); printf("n"); return 0; } *******************bubblesort************** #include<stdio.h> #define MAX 10
  • 94. int list[MAX] = {1,8,4,6,0,3,5,2,7,9}; void display() { int i; printf("["); // navigate through all items for(i = 0; i < MAX; i++) { printf("%d ",list[i]); } printf("]n"); } void bubbleSort() { int temp; int i,j; bool swapped = false;
  • 95. // loop through all numbers for(i = 0; i < MAX-1; i++) { swapped = false; // loopthrough numbers falling ahead for(j = 0; j < MAX-1-i; j++) { printf(" Items compared: [ %d, %d ] ", list[j],list[j+1]); // check if next number is lesser than current no // swap the numbers. // (Bubble up the highest number) if(list[j] > list[j+1]) { temp = list[j]; list[j] = list[j+1]; list[j+1] = temp; swapped = true; printf(" => swapped [%d, %d]n",list[j],list[j+1]);
  • 96. } else { printf(" => not swappedn"); } } // if no number was swapped that means // array is sorted now, break the loop. if(!swapped) { break; } printf("Iteration%d#: ",(i+1)); display(); } } int main() { printf("Input Array: ");
  • 97. display(); printf("n"); bubbleSort(); printf("nOutput Array: "); display(); } ***********shell sort******************** #include<stdio.h> #include<stdbool.h> #define MAX 7 int intArray[MAX] = {4,6,3,2,1,9,7}; void display() { int i; printf("[");
  • 98. // navigate through all items for(i = 0;i < MAX;i++) { printf("%d ",intArray[i]); } printf("]n"); } void shellSort() { int inner, outer; int valueToInsert; int interval = 1; int elements = MAX; int i = 0; while(interval<= elements/3) { interval= interval*3 +1; }
  • 99. while(interval> 0) { printf("iteration%d#:",i); display(); for(outer = interval;outer < elements; outer++) { valueToInsert= intArray[outer]; inner = outer; while(inner> interval -1 && intArray[inner - interval] >= valueToInsert) { intArray[inner] = intArray[inner - interval]; inner -=interval; printf(" item moved :%dn",intArray[inner]); } intArray[inner]= valueToInsert; printf(" item inserted :%d, at position :%dn",valueToInsert,inner); }
  • 100. interval= (interval -1) /3; i++; } } int main() { printf("Input Array: "); display(); shellSort(); printf("Output Array: "); display(); return 1; } *******************selectionsort*************** #include<stdio.h> #include<stdbool.h> #define MAX 7
  • 101. int intArray[MAX] = {4,6,3,2,1,9,7}; /*void printline(intcount) { int i; for(i = 0;i < count-1;i++) { printf("="); } printf("=n"); }*/ void display() { int i; printf("["); // navigate through all items for(i = 0;i < MAX;i++) { printf("%d ", intArray[i]); }
  • 102. printf("]n"); } void selectionSort() { int indexMin,i,j; // loop through all numbers for(i = 0; i < MAX-1; i++) { // set current element as minimum indexMin= i; // check the element to be minimum for(j = i+1;j < MAX;j++) { if(intArray[j] < intArray[indexMin]) { indexMin= j; } }
  • 103. if(indexMin!= i) { printf("Items swapped: [ %d, %d ]n" , intArray[i], intArray[indexMin]); // swap the numbers int temp = intArray[indexMin]; intArray[indexMin]= intArray[i]; intArray[i] = temp; } printf("Iteration%d#:",(i+1)); display(); } } int main() { printf("Input Array: "); display(); printline(50); selectionSort();
  • 104. printf("Output Array: "); display(); printline(50); } **************quick sort*********** #include<stdio.h> #include<stdbool.h> #define MAX 7 int intArray[MAX] = {4,6,3,2,1,9,7}; void display() { int i; printf("["); // navigate through all items for(i = 0;i < MAX;i++) {
  • 105. printf("%d ",intArray[i]); } printf("]n"); } void swap(int num1, int num2) { int temp = intArray[num1]; intArray[num1] = intArray[num2]; intArray[num2] = temp; } int partition(intleft, int right, int pivot) { int leftPointer = left -1; int rightPointer = right; while(true) { while(intArray[++leftPointer]< pivot) { //do nothing }
  • 106. while(rightPointer> 0 && intArray[--rightPointer] > pivot) { //do nothing } if(leftPointer >= rightPointer) { break; } else { printf(" item swapped :%d,%dn", intArray[leftPointer],intArray[rightPointer]); swap(leftPointer,rightPointer); } } printf(" pivot swapped :%d,%dn", intArray[leftPointer],intArray[right]); swap(leftPointer,right); printf("Updated Array: "); display(); return leftPointer;
  • 107. } void quickSort(int left, int right) { if(right-left <= 0) { return; } else { int pivot = intArray[right]; int partitionPoint= partition(left,right, pivot); quickSort(left,partitionPoint-1); quickSort(partitionPoint+1,right); } } int main() { printf("Input Array: "); display(); quickSort(0,MAX-1); printf("Output Array: "); display(); }
  • 108. *******************stack************* #include<stdio.h> #include<stdlib.h> int stack[5]; int push(); int pop(); void traverse(); int is_empty(); int top_element(); int top = 0; int main() { int element, choice; for (;;) { printf("Stack Operations.n");
  • 109. printf("1. Insert into stack (Push operation).n"); printf("2. Delete from stack (Pop operation).n"); printf("3. Print top element of stack.n"); printf("4. Check if stack is empty.n"); printf("5. Traverse stack.n"); printf("6. Exit.n"); printf("Enteryour choice.n"); scanf("%d",&choice); switch (choice) { case 1: if (top == 5) printf("Error: Overflownn"); else { printf("Enter the value to insert.n"); scanf("%d", &element); push(element); } break;
  • 110. case 2: if (top == 0) printf("Error: Underflow.nn"); else { element = pop(); printf("Element removed from stack is %d.n", element); } break; case 3: if (!is_empty()) { element = top_element(); printf("Element at the top of stack is %dnn", element); } else printf("Stack is empty.nn"); break;
  • 111. case 4: if (is_empty()) printf("Stack is empty.nn"); else printf("Stack isn't empty.nn"); break; case 5: traverse(); break; case 6: exit(0); } } } void push(int value) { stack[top] = value;
  • 112. top++; } int pop() { top--; return stack[top]; } void traverse() { int d; if (top == 0) { printf("Stack is empty.nn"); return; } printf("There are %d elements in stack.n", top); for (d = top - 1; d >= 0; d--) printf("%dn", stack[d]);
  • 113. printf("n"); } int is_empty() { if (top == 0) return 1; else return 0; } int top_element() { return stack[top-1]; }