Вы находитесь на странице: 1из 104

Westbridge Institute of Technology Inc.

Brgy. Banlic, City of Cabuyao Laguna


Tel # (049) 544-1325 / westbridge.educ@yahoo.com

PROGRAM
COMPILATIONS
CC 104-DATA STRUCTURES AND
ALGORITHM

Bachelor of Science in Computer Science


2ND Semester, Academic Year 2019-2020

Submitted by:

Carl Gabriel M. Palustre


Cristine Joy Permejo

Submitted to:

MARLON L. ATANACIO, MSIT


Instructor

March 2020
10 EXAMPLES OF LIST
PROGRAM
1. Turbo C++: Singly Linked List
#include <iostream.h>
#include <string.h>

struct SLinkList
{
int data;
SLinkList *next;

SLinkList();
SLinkList(int value);

SLinkList* InsertNext(int value);


int DeleteNext();

void Traverse(SLinkList *node = NULL);


};

SLinkList::SLinkList() : data(0), next(NULL)


{
}

SLinkList::SLinkList(int value) : data(value), next(NULL)


{
}

SLinkList* SLinkList::InsertNext(int value)


{
SLinkList *node = new SLinkList(value);
if(this->next == NULL)
{
// Easy to handle
node->next = NULL; // already set in constructor
this->next = node;
}
else
{
// Insert in the middle
SLinkList *temp = this->next;
node->next = temp;
this->next = node;
}
return node;
}

int SLinkList::DeleteNext()
{
if(this->next == NULL)
return 0;

SLinkList *pNode = this->next;


this->next = this->next->next; // can be NULL here
delete pNode;
return 1;
}

void SLinkList::Traverse(SLinkList *node)


{
if(node == NULL)
node = this;
cout << "\n\nTraversing in Forward Direction\n\n";

while(node != NULL)
{
cout << node->data;
cout << "\n";
node = node->next;
}
}

int main()
{
SLinkList *node1 = new SLinkList(1);
SLinkList *node2 = node1->InsertNext(2);
SLinkList *node3 = node2->InsertNext(3);
SLinkList *node4 = node3->InsertNext(4);
SLinkList *node5 = node4->InsertNext(5);

node1->Traverse();

node3->DeleteNext(); // delete the node "FOUR"

node2->Traverse();

cout << "\n";


return 0;
}

Reference:http://www.softwareandfinance.com/Turbo_CPP/Turbo_CPP_Singly_Linked
_List.html

Program Explanation
Filling elements and traversal in forward direction.
2. Turbo C++: Reverse singly linked list
#include <iostream.h>

struct SLinkList
{
int data;
SLinkList *next;

SLinkList();
SLinkList(int value);

SLinkList* InsertNext(int value);


int DeleteNext();

void Traverse(SLinkList *node = NULL);


};

SLinkList::SLinkList() : data(0), next(NULL)


{
}

SLinkList::SLinkList(int value) : data(value), next(NULL)


{
}

SLinkList* SLinkList::InsertNext(int value)


{
SLinkList *node = new SLinkList(value);
if(this->next == NULL)
{
// Easy to handle
node->next = NULL; // already set in constructor
this->next = node;
}
else
{
// Insert in the middle
SLinkList *temp = this->next;
node->next = temp;
this->next = node;
}
return node;
}

int SLinkList::DeleteNext()
{
if(this->next == NULL)
return 0;

SLinkList *pNode = this->next;


this->next = this->next->next; // can be NULL here
delete pNode;
return 1;
}

void SLinkList::Traverse(SLinkList *node)


{
if(node == NULL)
node = this;
cout << "\n\nTraversing in Forward Direction\n\n";

while(node != NULL)
{
cout << node->data;
cout << "\n";
node = node->next;
}
}

SLinkList* Reverse_With_Bubble(SLinkList *head)


{
SLinkList *testnode = NULL;
if(head == NULL)
return head;

while(1)
{
SLinkList *p = head;
if(p->next == testnode)
break;
while(1)
{
int temp = p->data;
p->data = p->next->data;
p->next->data = temp;
p = p->next;
if(p->next == testnode)
{
testnode = p;
break;
}
}
}
return head;
}

SLinkList* Reverse(SLinkList *head)


{
if(head == NULL)
return head;

SLinkList *cp = head;


SLinkList *prev = NULL;

while(cp != NULL)
{
SLinkList *next = cp->next;
cp->next = prev;
prev = cp;
cp = next;
}
head = prev;
return head;
}

SLinkList* Reverse_with_copy(SLinkList *head)


{
SLinkList *p = head;
SLinkList *newhead = NULL;
while(1)
{
if(p == NULL)
return newhead;
SLinkList *newnode = new SLinkList(p->data);
newnode->next = newhead;
newhead = newnode;
p = p->next;
}
return newhead;
}

int main()
{
SLinkList *head = new SLinkList(1);
SLinkList *p = head->InsertNext(2);
p = p->InsertNext(3);
p = p->InsertNext(4);
p = p->InsertNext(5);
p = p->InsertNext(6);
p = p->InsertNext(7);
p = p->InsertNext(8);

head->Traverse();

SLinkList *newhead = Reverse(head);

newhead->Traverse();

cout << "\n";


return 0;
}

Reference:
http://www.softwareandfinance.com/Turbo_CPP/Turbo_CPP_Reverse_Singly_Linked_L
ist.html

Program Explanation

Reversing a singly linked list is very easy. The SLinkList* Reverse(SLinkList


*head) function is about ten lines of code that does the magic.
3. Turbo C++: Doubly linked list
#include <iostream.h>

struct DLinkList
{
int data;

DLinkList *next;
DLinkList *prev;

DLinkList();
DLinkList(int value);

DLinkList* InsertNext(int value);


DLinkList* InsertPrev(int value);
void TraverseFront(DLinkList *node = NULL);
void TraverseBack(DLinkList *node = NULL);
};

DLinkList::DLinkList() : data(0), next(NULL), prev(NULL) { }

DLinkList::DLinkList(int value) : data(value), next(NULL), prev(NULL) { }

DLinkList* DLinkList::InsertNext(int value)


{
DLinkList *node = new DLinkList(value);
if(this->next == NULL)
{

// Easy to handle
node->prev = this;
node->next = NULL; // already set in constructor
this->next = node;
}
else
{
// Insert in the middle
DLinkList *temp = this->next;
node->prev = this;
node->next = temp;
this->next = node;
temp->prev = node;
// temp->next does not have to be changed
}
return node;
}

DLinkList* DLinkList::InsertPrev(int value)


{
DLinkList *node = new DLinkList(value);
if(this->prev == NULL)
{
node->prev = NULL; // already set on constructor
node->next = this;
this->prev = node;
}
else
{

// Insert in the middle


DLinkList *temp = this->prev;
node->prev = temp;
node->next = this;
this->prev = node;
temp->next = node;
// temp->prev does not have to be changed
}
return node;
}

void DLinkList::TraverseFront(DLinkList *node)


{
if(node == NULL)
node = this;
cout << "\n\nTraversing in Forward Direction\n\n";

while(node != NULL)
{
cout << node->data;
cout << "\n";
node = node->next;
}
}

void DLinkList::TraverseBack(DLinkList *node)


{
if(node == NULL)
node = this;
cout << "\n\nTraversing in Backward Direction\n\n";
while(node != NULL)
{
cout << node->data;
cout << "\n";
node = node->prev;
}
}

int main()
{
DLinkList *node1 = new DLinkList(1);
DLinkList *node3 = node1->InsertNext(3);
DLinkList *node2 = node3->InsertPrev(2);
DLinkList *node5 = node3->InsertNext(5);
DLinkList *node4 = node5->InsertPrev(4);

node1->TraverseFront();
node5->TraverseBack();

cout << "\n";


return 0;
}

Reference:
http://www.softwareandfinance.com/Turbo_CPP/Turbo_CPP_Doubly_Linked_List.html
Program Explanation

I have given here Turbo C++ sample code for doubly linked list, filling elements and
traversal in forward and backward direction. I have NOT given the code for deleting the
nodes. It is easy to implement by changing the insert functions.
4. Turbo C++: Singly Linked Circular List
#include <iostream.h>

struct SLinkCircularList
{
int data;
SLinkCircularList *next;

SLinkCircularList();
SLinkCircularList(int value);

SLinkCircularList* InsertNext(int data);


int DeleteNext();
void Traverse(SLinkCircularList *node = NULL);
int GetNumberOfNodes(SLinkCircularList *node = NULL);
};

SLinkCircularList::SLinkCircularList() : data(0), next(this) { }

SLinkCircularList::SLinkCircularList(int value) : data(value), next(this) { }

SLinkCircularList* SLinkCircularList::InsertNext(int value)


{
SLinkCircularList *node = new SLinkCircularList(value);
if(this->next == this) // only one node in the circular list
{
// Easy to handle, after the two lines of executions,
// there will be two nodes in the circular list

node->next = this;
this->next = node;
}
else
{
// Insert in the middle

SLinkCircularList *temp = this->next;


node->next = temp;
this->next = node;
}
return node;

int SLinkCircularList::DeleteNext()
{
if(this->next == this)
{
cout << "\nThe node can not be deleted as there is only one node in the
circular list\n";
return 0;
}

SLinkCircularList *pNode = this->next;


this->next = this->next->next;
delete pNode;
return 1;
}

void SLinkCircularList::Traverse(SLinkCircularList *node)


{
if(node == NULL)
node = this;
cout << "\n\nTraversing in Forward Direction\n\n";
SLinkCircularList *startnode = node;

do
{
cout << node->data;
cout << "\n";
node = node->next;
}
while(node != startnode);
}

int SLinkCircularList::GetNumberOfNodes(SLinkCircularList *node)


{
if(node == NULL)
node = this;

int count = 0;
SLinkCircularList *startnode = node;
do
{
count++;
node = node->next;
}
while(node != startnode);

cout << "\nCurrent Node Value: " << node->data;


cout << "\nTotal nodes in Circular List: " << count;

cout << "\n";

return count;
}

int main()
{
SLinkCircularList *node1 = new SLinkCircularList(1);
node1->DeleteNext(); // Delete will fail in this case.

SLinkCircularList *node2 = node1->InsertNext(2);


node1->DeleteNext(); // It will delete the node2.

node2 = node1->InsertNext(2); // Insert it again

SLinkCircularList *node3 = node2->InsertNext(3);


SLinkCircularList *node4 = node3->InsertNext(4);
SLinkCircularList *node5 = node4->InsertNext(5);

node1->GetNumberOfNodes();
node3->GetNumberOfNodes();
node5->GetNumberOfNodes();

node1->Traverse();
node3->DeleteNext(); // delete the node "FOUR"
node2->Traverse();
cout << "\n";

node1->GetNumberOfNodes();
node3->GetNumberOfNodes();
node5->GetNumberOfNodes();
cout << "\n";
return 0;
}
Reference:
http://www.softwareandfinance.com/Turbo_CPP/Turbo_CPP_Singly_Circular_List.html

Program Explanation

The main difference between singly linked list and singly linked circular list are the next
node pointer of last node is NULL in case of singly linked list where as next node pointer
of last node is first node in case of singly linked circular list.
5. Turbo C++: Program to Search for an Element
in the Linked List using Recursion
#include <stdio.h>
#include <stdlib.h>

struct node
{
int a;
struct node *next;
};

void generate(struct node **, int);


void search(struct node *, int, int);
void delete(struct node **);

int main()
{
struct node *head;
int key, num;

printf("Enter the number of nodes: ");


scanf("%d", &num);
generate(&head, num);
printf("\nEnter key to search: ");
scanf("%d", &key);
search(head, key, num);
delete(&head);
}

void generate(struct node **head, int num)


{
int i;
struct node *temp;

for (i = 0; i < num; i++)


{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = rand() % num;
printf("%d ", temp->a);
if (*head == NULL)
{
*head = temp;
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}

void search(struct node *head, int key, int index)


{
if (head->a == key)
{
printf("Key found at Position: %d\n", index);
}
if (head->next == NULL)
{
return;
}
search(head->next, key, index - 1);
}

void delete(struct node **head)


{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
Reference: https://www.includehelp.com/cpp-programming-examples-solved-cpp-
programs.aspx

Program Explanation
This C Program uses recursive function & search for an element in a linked list. A linked
list is an ordered set of data elements, each containing a link to its successor.
6. Turbo C++: Program to Search for an Element
in the Linked List without using Recursion
#include <stdio.h>
#include <stdlib.h>

struct node
{
int a;
struct node *next;
};

void generate(struct node **, int);


void search(struct node *, int);
void delete(struct node **);

int main()
{
struct node *head = NULL;
int key, num;

printf("Enter the number of nodes: ");


scanf("%d", &num);
printf("\nDisplaying the list\n");
generate(&head, num);
printf("\nEnter key to search: ");
scanf("%d", &key);
search(head, key);
delete(&head);

return 0;
}

void generate(struct node **head, int num)


{
int i;
struct node *temp;

for (i = 0; i < num; i++)


{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = rand() % num;
if (*head == NULL)
{
*head = temp;
temp->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
printf("%d ", temp->a);
}
}

void search(struct node *head, int key)


{
while (head != NULL)
{
if (head->a == key)
{
printf("key found\n");
return;
}
head = head->next;
}
printf("Key not found\n");
}

void delete(struct node **head)


{
struct node *temp;

while (*head != NULL)


{
temp = *head;
*head = (*head)->next;
free(temp);
}
}

Reference:https://www.sanfoundry.com/c-program-search-linked-list-without-recursion/

Program Explanation

This C program, using iteration, searches for an element in a linked list. A linked list is
an ordered set of data elements, each containing a link to its successor.
7. Turbo C++: Program to Display the Nodes of a
Linked List in Reverse using Recursion
#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node *next;
};

void print_reverse_recursive (struct node *);


void print (struct node *);
void create_new_node (struct node *, int );

//Driver Function
int main ()
{
struct node *head = NULL;
insert_new_node (&head, 1);
insert_new_node (&head, 2);
insert_new_node (&head, 3);
insert_new_node (&head, 4);
printf ("LinkedList : ");
print (head);
printf ("\nLinkedList in reverse order : ");
print_reverse_recursive (head);
printf ("\n");
return 0;
}

//Recursive Reverse
void print_reverse_recursive (struct node *head)
{
if (head == NULL)
{
return;
}

//Recursive call first


print_reverse_recursive (head -> next);
//Print later
printf ("%d ", head -> data);
}

//Print the linkedlist normal


void print (struct node *head)
{
if (head == NULL)
{
return;
}
printf ("%d ", head -> data);
print (head -> next);
}

//New data added in the start


void insert_new_node (struct node ** head_ref, int new_data)
{
struct node * new_node = (struct node *) malloc (sizeof (struct node));
new_node -> data = new_data;
new_node -> next = (*head_ref);
(*head_ref) = new_node;
}
Reference: https://www.sanfoundry.com/c-program-linked-list-reverse-using-recursion/

Program Explanation
This C Program uses recursive function & reverses the nodes in a linked list and
displays the list. A linked list is an ordered set of data elements, each containing a link
to its successor. This program makes each data element to link to its predecessor.
8. Turbo C++: Program to Display all the Nodes
in a Linked List using Recursion
#include <stdio.h>
#include <stdlib.h>

struct node
{
int a;
struct node *next;
};

void generate(struct node **);


void display(struct node*);
void delete(struct node **);

int main()
{
struct node *head = NULL;

generate(&head);
display(head);
delete(&head);
return 0;
}

void generate(struct node **head)


{
int num = 10, i;
struct node *temp;

for (i = 0; i < num; i++)


{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = i;
if (*head == NULL)
{
*head = temp;
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}

void display(struct node *head)


{
printf("%d ", head->a);
if (head->next == NULL)
{
return;
}
display(head->next);
}

void delete(struct node **head)


{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
Reference: https://www.sanfoundry.com/c-program-display-linked-list-using-recursion/

Program Explanation

This C Program uses recursive function & displays a linked list. A linked list is an
ordered set of data elements, each containing a link to its successor.
9. Turbo C++: Program to Display all the Nodes
in a Linked List without using Recursion

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

struct node
{
int a;
struct node *next;
};

void generate(struct node **);


void display(struct node*);
void delete(struct node **);

int main()
{
struct node *head = NULL;

generate(&head);
display(head);
delete(&head);
return 0;
}

void generate(struct node **head)


{
int num = 10, i;
struct node *temp;

for (i = 0; i < num; i++)


{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = i;
if (*head == NULL)
{
*head = temp;
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}

void display(struct node *head)


{
while (head != NULL)
{
printf("%d ", head->a);
head = head->next;
}
printf("\n");
}

void delete(struct node **head)


{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
Reference: https://www.sanfoundry.com/c-program-display-linked-list-without-recursion/

Program Explanation
This C program, using iteration, displays a linked list. A linked list is an ordered set of
data elements, each containing a link to its successor.
10. Turbo C++: Program to Print the Alternate
Nodes in a Linked List without using
Recursion
#include <stdio.h>
#include <stdlib.h>

struct node
{
int a;
struct node *next;
};

void generate(struct node **);


void display(struct node *);
void delete(struct node **);

int main()
{
struct node *head = NULL;

generate(&head);
printf("\nDisplaying the alternate nodes\n");
display(head);
delete(&head);

return 0;
}

void display(struct node *head)


{
int flag = 0;

while(head != NULL)
{
if (!(flag % 2))
{
printf("%d ", head->a);
}
flag++;
head = head->next;
}
}

void generate(struct node **head)


{
int num, i;
struct node *temp;

printf("Enter length of list: ");


scanf("%d", &num);
for (i = num; i > 0; i--)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = i;
if (*head == NULL)
{
*head = temp;
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}

void delete(struct node **head)


{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
}
Reference: https://www.sanfoundry.com/c-program-alternate-nodes-without-recursion/

Program Explanation

This C program, using iteration, displays the alternate nodes in a linked list.A linked list
is an ordered set of data elements, each containing a link to its successor.
10 EXAMPLES OF ARRAY
PROGRAM
1. C Program to Calculate Sum & Average of an
Array
#include <stdio.h>

int main()
{
int i, num;
float total = 0.0, average;
printf ("Enter the value of N \n");
scanf("%d", &num);
int array[num];

printf("Enter %d numbers (-ve, +ve and zero) \n", num);

for (i = 0; i < num; i++)


{
scanf("%d", &array[i]);
}

printf("Input array elements \n");

for (i = 0; i < num; i++)


{
printf("%+3d\n", array[i]);
}

/* Summation starts */

for (i = 0; i < num; i++)


{
total+=array[i];/* this means total=total+array[i]; */
}

average = total / num;

printf("\n Sum of all numbers = %.2f\n", total);

printf("\n Average of all input numbers = %.2f\n", average);

}
Reference: https://www.sanfoundry.com/c-program-sum-average-array/
Program Explanation

This is a C Program to calculate the sum & average of an array.

From users, take a number N as input, which will indicate the number of elements in the
array.
1. Create an array of integer of user-defined size.
2. Iterating through for loops (from [0 to N)), take integers as input from the user and
print them. These inputs are the elements of the array.
Now, start summation by iterating through all the elements and adding numbers
to calculate and print sum as well as to calculate average.
To calculate the average, the overall sum is divided by the total number of
elements in the array.
3. Print the average calculated.
2. C Program to Calculate the Sum of the Array
Elements using Pointer
#include <stdio.h>
#include <malloc.h>

void main()
{
int i, n, sum = 0;
int *a;

printf("Enter the size of array A \n");


scanf("%d", &n);

a = (int *) malloc(n * sizeof(int));

printf("Enter Elements of the List \n");


for (i = 0; i < n; i++)
{
scanf("%d", a + i);
}

/* Compute the sum of all elements in the given array */

for (i = 0; i < n; i++)


{
sum = sum + *(a + i);
/* this *(a+i) is used to access the value stored at the address*/
}

printf("Sum of all elements in array = %d\n", sum);


return 0;
}

Reference: https://www.sanfoundry.com/c-program-sum-array-elements-using-pointer/
Program Explanation

Create a pointer variable a, which points to an integer data.


2. Now, create another variable N (size of array), whose input should be taken by users,
and a variable sum (initial value of sum = 0), which will store total sum of all the
elements of the array.
3. Now create size_of_array(N) * size_of_each_element (integer) times space using
malloc() function, assigning the starting address of this space to the pointer variable, a.
4. Using for loop (0 to size), start iteration, reach at every array element location by
adding the value of i to the value of a, taking array element as input.
5. Again, start iteration, this time reach at each array element location, and accessing
them to add to the sum variable.
6. Print sum.
3. C Program to Calculate Sum of all Elements of
an Array using Pointers as Arguments
#include <stdio.h>

void main()
{
static int array[5] = { 200, 400, 600, 800, 1000 };
int sum;

int addnum(int *ptr);


sum = addnum(array);

printf("Sum of all array elements = %5d\n", sum);

int addnum(int *ptr)


{
int index, total = 0;
for (index = 0; index < 5; index++)
{
total += *(ptr + index);
}
return(total);

}
Reference: https://www.sanfoundry.com/c-program-sum-all-elements-array-using-
pointers/

Program Explanation

1. Declare a static array of some fixed size along with array element definition.
2. Take a variable sum, which will store the total sum of all the array elements.
3. Create a function with a single argument, in which we will pass the above created
array argument. This function will return the sum.
4. Inside this function, a for loop will run from 0 to array size-1, accessing each element
of array by adding the iterator i to the pointer variable (array argument, which was
passed to this function).
5. Elements will get add and the total sum will be returned from this function.
6. Variable sum inside main() function, will get this returned value and will be printed.
4. C Program to Compute the Sum of two One
Dimensional Arrays using Malloc
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

void main()
{

int i, n;
int *a, *b, *c;

printf("Enter the size of the arrays\n");


scanf("%d", &n);

a = (int *)malloc(n * sizeof(int));


b = (int *)malloc(n * sizeof(int));
c = (int *)malloc(n * sizeof(int));

printf("Enter Elements of First List\n");

for (i = 0; i < n; i++)


{
scanf("%d", a + i);
}

printf("Enter Elements of Second List\n");

for (i = 0; i < n; i++)


{
scanf("%d", b + i);
}

for (i = 0; i < n; i++)


{
*(c + i) = *(a + i) + *(b + i);
}

printf("Resultant List is\n");

for (i = 0; i < n; i++)


{
printf("%d\n", *(c + i));
}
return 0;
}
Reference: https://www.sanfoundry.com/c-program-compute-sum-two-one-dimensional-
arrays-using-malloc/
Program Explanation
1. Declare a variable (n), in which the size of the array(s) will be stored.
2. Declare 3 pointer variables of integer type, to hold starting address of 3 different
arrays (a, b and c).
3. Using for loop running from 0 to arraySize-1, go at every location by adding the value
of integer i(the iterator)to the starting address of the array(s) and then take the input by
storing values to those locations.
4. Do the previous step for 2 arrays (i.e a and b).
5. Now, again using for loop, adding the value of i to the starting address of both the
arrays (a and b), extract each element from both the arrays holdd by a and b, add the
elements and store the result in third array (i.e c).
6. Print the elements of array c.
5. C Program to Find the Sum of Contiguous
Subarray within a 1 – D Array of Numbers
which has the Largest Sum
#include<stdio.h>

int main()
{
int size,m=0,l=0;

printf("Type the length of the array\n");


scanf("%d",&size);
int array[size];
printf("type the elements of the array\n");

for(int i=0;i<size;i++)
{
scanf("%d",&array[i]);

int largest=array[0];
for(int i=0;i<size;i++)
{
int sum=0;
for(int j=i;j<size;j++)
{
sum=sum+array[j];
if(sum>largest)
{
m=i;l=j;
largest=sum;
}
}
}

printf("\n The largest contigous subarray is");


for(int z=m;z<=l;z++)
{
printf(" %d ",array[z]);
}
printf("\n The sum of the largest contigous subarray is");
printf(" %d",largest);
return 0;
}
Reference: https://www.sanfoundry.com/c-program-sum-contiguous-subarray/
Program Explanation

Declare a variable (n), in which the size of the array(s) will be stored.
2. Declare 3 pointer variables of integer type, to hold starting address of 3 different
arrays (a, b and c).
3. Using for loop running from 0 to arraySize-1, go at every location by adding the value
of integer i(the iterator)to the starting address of the array(s) and then take the input by
storing values to those locations.
4. Do the previous step for 2 arrays (i.e a and b).
5. Now, again using for loop, adding the value of i to the starting address of both the
arrays (a and b), extract each element from both the arrays holdd by a and b, add the
elements and store the result in third array (i.e c).
6. Print the elements of array c.
6. C Program to Put Even & Odd Elements of an
Array in 2 Separate Arrays
#include <stdio.h>
void main()
{

long int ARR[10], OAR[10], EAR[10];


int i, j = 0, k = 0, n;

printf("Enter the size of array AR n");


scanf("%d", &n);

printf("Enter the elements of the array n");


for (i = 0; i < n; i++)
{
scanf("%ld", &ARR[i]);
fflush(stdin);
}

/* Copy odd and even elements into their respective arrays */

for (i = 0; i < n; i++)


{
if (ARR[i] % 2 == 0)
{
EAR[j] = ARR[i];
j++;
}
else
{
OAR[k] = ARR[i];
k++;
}
}

printf("The elements of OAR are n");


for (i = 0; i < k; i++)
{
printf("%ldn", OAR[i]);
}

printf("The elements of EAR are n");


for (i = 0; i < j; i++)
{
printf("%ldn", EAR[i]);
}

}
Reference: https://www.sanfoundry.com/c-program-even-odd-elements-2-separate-
arrays/
Program Explanation
1. Create three integer arrays namely ARR, OAR, EAR of some fixed capacity, 10.
2. Take size of the array as input from users and define the first array, ARR by
inserting elements of the array.
3. Using for loop, scan each and every element of the first array, check whether
they are even or odd by taking modulo of 2 on those numbers.
4. If the array element modulo 2, returns 0, this means the number is divisible by
2 and it is an even number. Add this number to second array.
5. If the array element modulo 2, returns 1, this means the number is not divisible
by 2 and it is an odd number. Add this number to third array.
6. Repeat steps 4 and 5 until all the elements of first array are checked.
7. At last, we will be having arrays second third holding all the even and odd
elements of first array respectively.
8. Print both the OAR AND EAR.
9. Exit.
7. C Program to Insert an Element in a Specified
Position in a given Array
#include <stdio.h>
void main()
{
int array[10];
int i, j, n, m, temp, key, pos;

printf("Enter how many elements \n");


scanf("%d", &n);
printf("Enter the elements \n");

for (i = 0; i < n; i++)


{
scanf("%d", &array[i]);
}

printf("Input array elements are \n");


for (i = 0; i < n; i++)
{
printf("%d\n", array[i]);
}

// Sorting the elements of the array


for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}

printf("Sorted list is \n");


for (i = 0; i < n; i++)
{
printf("%d\n", array[i]);
}

printf("Enter the element to be inserted \n");


scanf("%d", &key);

for (i = 0; i < n; i++)


{
if (key < array[i])
{
pos = i;
break;
}
if (key > array[n-1])
{
pos = n;
break;
}
}
if (pos != n)
{
m = n - pos + 1 ;
for (i = 0; i <= m; i++)
{
array[n - i + 2] = array[n - i + 1] ;
}
}

array[pos] = key;

printf("Final list is \n");


for (i = 0; i < n + 1; i++)
{
printf("%d\n", array[i]);
}
}
Reference: https://www.sanfoundry.com/c-program-insert-element-specified-position-
array/

Program Explanation

1. Declare a one dimentional array, a of some fixed capacity, 10.


2. Take an input for size of the array, n. The size of the array must be at least one
smaller than array’s capacity, 10.
3. Using for loop, fill the array with elements to its size.
4. Print all the elements of the array.
5. Sort the elements of the array in ascending order. In this case, we have used
Insertion sort.
6. Now, take a value from users, which needs to be inserted inside array.
7. Run a for loop from 0 to arraySize-1, checking and comparing each element of array
i) If new element is smaller than array element, then the position is array element is
saved.
ii) If new element is bigger than the last element of array (biggest element of array),
then the size of array is saved.
8. Position saved is where the new element will be inserted.
9. All the elements at that position in the array and after that are shifted backwards by 1.
10. Print all the elements of the new array.
8. C Program to Delete the Specified Integer
from an Array
#include <stdio.h>
void main()
{
int vectorx[10];
int i, n, pos, element, found = 0;

printf("Enter how many elements\n");


scanf("%d", &n);
printf("Enter the elements\n");

for (i = 0; i < n; i++)


{
scanf("%d", &vectorx[i]);
}

printf("Input array elements are\n");


for (i = 0; i < n; i++)
{
printf("%d\n", vectorx[i]);
}

printf("Enter the element to be deleted\n");


scanf("%d", &element);

for (i = 0; i < n; i++)


{
if (vectorx[i] == element)
{
found = 1;
pos = i;
break;
}
}

if (found == 1)
{
for (i = pos; i < n - 1; i++)
{
vectorx[i] = vectorx[i + 1];
}

printf("The resultant vector is \n");


for (i = 0; i < n - 1; i++)
{
printf("%d\n", vectorx[i]);
}

}
else
printf("Element %d is not found in the vector\n", element);

}
Reference: https://www.sanfoundry.com/c-program-delete-specified-integer-array/
Program Explanation

1. Declare an array, vectorx of some fixed capacity, 10.


2. Take size of the array as input from users.
3. Using for loop, define the elements of the array.
4. Now, take a number form users as input, which needs to be deleted.
5. Run a for loop, comparing each element of the array to that number if both have
same magnitude.
6. If the number is present in the array, then save its location. If number is not present in
the array, then print appropriate message.
7. Run a for loop from that saved location to the size of array, shifting each element of
the array leftwards by one.
8. This way, the number gets deleted.
9. Exit
9. C Program to Cyclically Permute the
Elements of an Array
#include <stdio.h>
void main ()
{

int i, n, number[30];
printf("Enter the value of the n = ");
scanf("%d", &n);

printf("Enter the numbers\n");


for (i = 0; i < n; ++i)
{
scanf("%d", &number[i]);
}

number[n] = number[0];
for (i = 0; i < n; ++i)
{
number[i] = number[i + 1];
}

printf("Cyclically permuted numbers are given below \n");


for (i = 0; i < n; ++i)
printf("%d\n", number[i]);

}
Reference: https://www.sanfoundry.com/c-program-cyclically-permute-elements-array/
Program Explanation

1. Create an array of integer of some certain maximum capacity (10, in this case).
2. From users, take a number N as input, which will indicate the number of elements in
the array (N < = maximum capacity)
3. Iterating through for loops (from [0 to N) ), take integers as input from user and print
them. These input are the elements of the array.
4. Now assign the value of first element of the array at 0th position to the nth position of
the array.
5. Starting a for loop, with i as iterator from 0 to size-1, assigning each element at
(i+1)th position to ith position, hence each element shifts left by one.
6. And value of last element at (n-1)th position would be assigned a value at nth
position. Remember we stored the very first value of array at nth position.
10. C Program to Find the Biggest Number in
an Array of Numbers using Recursion
#include <stdio.h>
int large(int[], int, int);

int main()
{

int size;
int largest;
int list[20];
int i;

printf("Enter size of the list:");


scanf("%d", &size);

printf("Printing the list:\n");


for (i = 0; i < size ; i++)
{
list[i] = rand() % size;
printf("%d \t", list[i]);
}

if (size == 0)
{
printf("Empty list\n");
}

else
{
largest = list[0];
largest = large(list, size - 1, largest);
printf("\nThe largest number in the list is: %d\n", largest);
}

int large(int list[], int position, int largest)


{

if (position == 0)
return largest;

if (position > 0)
{
if (list[position] > largest)
{
largest = list[position];
}
return large(list, position - 1, largest);
}

Reference: https://www.sanfoundry.com/c-program-biggest-number-array-using-
recursion/
Program Explanation
1. Declare an array of some fixed capacity, 20 and take size from the users and define
elements in unsorted fashion using rand() functions to insert random number less than
size ( rand() % size )
2. Assume first element of the array to be the largest number.
2. Create a function with three parameters i.e the array, last index of array (size -1) and
largest element of the array.
4. Call this function.
5. Inside it, the largest number is compared with the element at position passed to the
function (initially the position passed is the last index of the array) and make necessary
updation if largest number is smaller than the number compared.
6. After comparison, this function is again called inside itself but with position being
previous position(last index)-1.
7. This way all elements are compared with largest number making updation wherever
needed via recursion.
8. This process stops when the variable position reaches the 0th position.
10 EXAMPLES OF STACKS
PROGRAM
1. C Program to Implement a Stack
#include <stdio.h>
#define MAXSIZE 5

struct stack
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;

void push(void);
int pop(void);
void display(void);

void main ()
{
int choice;
int option = 1;
s.top = -1;

printf ("STACK OPERATION\n");


while (option)
{
printf ("------------------------------------------\n");
printf (" 1 --> PUSH \n");
printf (" 2 --> POP \n");
printf (" 3 --> DISPLAY \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");

printf ("Enter your choice\n");


scanf ("%d", &choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
/* Function to add an element to the stack */
void push ()
{
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}
/* Function to delete an element from the stack */
int pop ()
{
int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);
}
else
{
num = s.stk[s.top];
printf ("poped element is = %dn", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);
}
/* Function to display the status of the stack */
void display ()
{
int i;
if (s.top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\n The status of the stack is \n");
for (i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}
Reference: https://www.sanfoundry.com/c-program-stack-implementation/
Program Explanation

1. Ask the user for the operation like push, pop, display and exit. Use the variable top to
represent the top of the stack.
2. According to the option entered, access its respective function using switch
statement.
3. In the function push(), firstly check if the stack is full. If it is, then print the output as
“Stack is Full”. Otherwise take the number to be inserted as input and store it in the
variable num. Copy the number to the array stk[] and increment the variable top by 1.
4. In the function pop(), firstly check if the stack is empty. If it is, then print the output as
“Stack is Empty”. Otherwise print the top most element of the array stk[] and decrement
the variable top by 1.
5. In the function display(), using for loop print all the elements of the array.
6. Exit.
2. C Program to Reverse a Stack using
Recursion
#include <stdio.h>
#include <stdlib.h>

struct node
{
int a;
struct node *next;
};

void generate(struct node **);


void display(struct node *);
void stack_reverse(struct node **, struct node **);
void delete(struct node **);

int main()
{
struct node *head = NULL;

generate(&head);
printf("\nThe sequence of contents in stack\n");
display(head);
printf("\nInversing the contents of the stack\n");
if (head != NULL)
{
stack_reverse(&head, &(head->next));
}
printf("\nThe contents in stack after reversal\n");
display(head);
delete(&head);

return 0;
}

void stack_reverse(struct node **head, struct node **head_next)


{
struct node *temp;

if (*head_next != NULL)
{
temp = (*head_next)->next;
(*head_next)->next = (*head);
*head = *head_next;
*head_next = temp;
stack_reverse(head, head_next);
}
}

void display(struct node *head)


{
if (head != NULL)
{
printf("%d ", head->a);
display(head->next);
}
}

void generate(struct node **head)


{
int num, i;
struct node *temp;
printf("Enter length of list: ");
scanf("%d", &num);
for (i = num; i > 0; i--)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = i;
if (*head == NULL)
{
*head = temp;
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}

void delete(struct node **head)


{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
Reference: https://www.sanfoundry.com/c-program-reverse-stack-using-
recursion/

Program Explanation
This C program, using recursion, reverses a stack content. Stack here is represented
using a linked list. A linked list is an ordered set of data elements, each containing a link
to its successor.
3. C Program to Reverse a Stack without using
Recursion
#include <stdio.h>
#include <stdlib.h>

struct node
{
int a;
struct node *next;
};

void generate(struct node **);


void display(struct node *);
void stack_reverse(struct node **);
void delete(struct node **);

int main()
{
struct node *head = NULL;

generate(&head);
printf("\nThe sequence of contents in stack\n");
display(head);
printf("\nInversing the contents of the stack\n");
stack_reverse(&head);
printf("\nThe contents in stack after reversal\n");
display(head);
delete(&head);
return 0;
}

void stack_reverse(struct node **head)


{
struct node *temp, *prev;

if (*head == NULL)
{
printf("Stack does not exist\n");
}
else if ((*head)->next == NULL)
{
printf("Single node stack reversal brings no difference\n");
}
else if ((*head)->next->next == NULL)
{
(*head)->next->next = *head;
*head = (*head)->next;
(*head)->next->next = NULL;
}
else
{
prev = *head;
temp = (*head)->next;
*head = (*head)->next->next;
prev->next = NULL;
while ((*head)->next != NULL)
{
temp->next = prev;
prev = temp;
temp = *head;
*head = (*head)->next;
}
temp->next = prev;
(*head)->next = temp;
}
}

void display(struct node *head)


{
if (head != NULL)
{
printf("%d ", head->a);
display(head->next);
}
}

void generate(struct node **head)


{
int num, i;
struct node *temp;

printf("Enter length of list: ");


scanf("%d", &num);
for (i = num; i > 0; i--)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = i;
if (*head == NULL)
{
*head = temp;
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}

void delete(struct node **head)


{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
Reference: https://www.sanfoundry.com/c-program-reverse-stack-without-recursion/
Program Explanation

This C program, using iteration, reverses a stack content. Stack here is represented
using a linked list. A linked list is an ordered set of data elements, each containing a link
to its successor.
4. C Program to Implement two Stacks using a
Single Array & Check for Overflow &
Underflow
#include <stdio.h>
#define SIZE 10

int ar[SIZE];
int top1 = -1;
int top2 = SIZE;

//Functions to push data


void push_stack1 (int data)
{
if (top1 < top2 - 1)
{
ar[++top1] = data;
}
else
{
printf ("Stack Full! Cannot Push\n");
}
}
void push_stack2 (int data)
{
if (top1 < top2 - 1)
{
ar[--top2] = data;
}
else
{
printf ("Stack Full! Cannot Push\n");
}
}

//Functions to pop data


void pop_stack1 ()
{
if (top1 >= 0)
{
int popped_value = ar[top1--];
printf ("%d is being popped from Stack 1\n", popped_value);
}
else
{
printf ("Stack Empty! Cannot Pop\n");
}
}
void pop_stack2 ()
{
if (top2 < SIZE)
{
int popped_value = ar[top2++];
printf ("%d is being popped from Stack 2\n", popped_value);
}
else
{
printf ("Stack Empty! Cannot Pop\n");
}
}

//Functions to Print Stack 1 and Stack 2


void print_stack1 ()
{
int i;
for (i = top1; i >= 0; --i)
{
printf ("%d ", ar[i]);
}
printf ("\n");
}
void print_stack2 ()
{
int i;
for (i = top2; i < SIZE; ++i)
{
printf ("%d ", ar[i]);
}
printf ("\n");
}

int main()
{
int ar[SIZE];
int i;
int num_of_ele;

printf ("We can push a total of 10 values\n");

//Number of elements pushed in stack 1 is 6


//Number of elements pushed in stack 2 is 4

for (i = 1; i <= 6; ++i)


{
push_stack1 (i);
printf ("Value Pushed in Stack 1 is %d\n", i);
}
for (i = 1; i <= 4; ++i)
{
push_stack2 (i);
printf ("Value Pushed in Stack 2 is %d\n", i);
}

//Print Both Stacks


print_stack1 ();
print_stack2 ();

//Pushing on Stack Full


printf ("Pushing Value in Stack 1 is %d\n", 11);
push_stack1 (11);

//Popping All Elements From Stack 1


num_of_ele = top1 + 1;
while (num_of_ele)
{
pop_stack1 ();
--num_of_ele;
}

//Trying to Pop From Empty Stack


pop_stack1 ();

return 0;
}
Reference: https://www.sanfoundry.com/c-program-two-stacks-single-array/
Program Explanation
This C Program Implements two Stacks using a Single Array & Check for Overflow &
Underflow. A Stack is a linear data structure in which a data item is inserted and deleted
at one record. A stack is called a Last In First Out (LIFO) structure. Because the data
item inserted last is the data item deleted first from the stack.
To implement two stacks in one array, there can be two methods.
First is to divide the array in to two equal parts and then give one half two each stack.
But this method wastes space.
So a better way is to let the two stacks to push elements by comparing tops of each
other, and not up to one half of the array.
Push and Pop functions of both stack in the following code has their Time Complexity
as O(1). They take constant time.
Print is O(n), where n is the number of elements in the stack.
The program has an array of size 10. 6 values are pushed in stack 1 and 4 in two. All
conditions are being checked
5. C Program to Implement a Stack using Linked
List
#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;

int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();

int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");

create();

while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);

switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}

/* Create empty stack */


void create()
{
top = NULL;
}

/* Count stack elements */


void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}

/* Push data into stack */


void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}

/* Display stack elements */


void display()
{
top1 = top;

if (top1 == NULL)
{
printf("Stack is empty");
return;
}

while (top1 != NULL)


{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}

/* Pop Operation on stack */


void pop()
{
top1 = top;

if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}

/* Return top element */


int topelement()
{
return(top->info);
}

/* Check if stack is empty or not */


void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}

/* Destroy entire stack */


void destroy()
{
top1 = top;

while (top1 != NULL)


{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;

printf("\n All stack elements destroyed");


count = 0;
}
Reference: https://www.sanfoundry.com/c-program-stack-using-linked-list/
Program Explanation
This C Program implement a stack using linked list. Stack is a type of queue that in
practice is implemented as an area of memory that holds all local variables and
parameters used by any function, and remembers the order in which functions are
called so that function returns occur correctly. Each time a function is called, its local
variables and parameters are “pushed onto” the stack. When the function returns,these
locals and parameters are “popped.” Because of this, the size of a program’s stack
fluctuates constantly as the program is running, but it has some maximum size. stack is
as a last in, first out (LIFO) abstract data type and linear data structure. Linked list is a
data structure consisting of a group of nodes which together represent a sequence.
Here we need to apply the application of linkedlist to perform basic operations of stack.
6. C Program to Check String is Palindrome
using Stack
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50

int top = -1, front = 0;


int stack[MAX];
void push(char);
void pop();

void main()
{
int i, choice;
char s[MAX], b;
while (1)
{
printf("1-enter string\n2-exit\n");
printf("enter your choice\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the String\n");
scanf("%s", s);
for (i = 0;s[i] != '\0';i++)
{
b = s[i];
push(b);
}
for (i = 0;i < (strlen(s) / 2);i++)
{
if (stack[top] == stack[front])
{
pop();
front++;
}
else
{
printf("%s is not a palindrome\n", s);
break;
}
}
if ((strlen(s) / 2) = = front)
printf("%s is palindrome\n", s);
front = 0;
top = -1;
break;
case 2:
exit(0);
default:
printf("enter correct choice\n");
}
}
}

/* to push a character into stack */


void push(char a)
{
top++;
stack[top] = a;
}
/* to delete an element in stack */
void pop()
{
top--;
}
Reference: https://www.sanfoundry.com/c-program-palindrome-stack/

Program Explanation

1. Take a string as input and store it in the array s[].


2. Load each character of the array s[] into the array stack[].
3. Use variables front and top to represent the last and top element of the array stack[].
4. Using for loop compare the top and last element of the array stack[]. If they are equal,
then delete the top element, increment the variable front by 1 and compare again.
5. If they are not equal, then print the output as “It is not a palindrome”.
6. Compare the elements in the steps 4-5 upto the middle element of the array stack[].
7. If every characters of the array is equal, then it is a paliandrome.
7. C Program to Check Stack is Full or Not
#include <stdio.h>
#include <conio.h>
int MAXSIZE = 8;
int stack[8];
int top = -1;

int isempty() {

if(top == -1)
return 1;
else
return 0;
}

int isfull() {

if(top == MAXSIZE)
return 1;
else
return 0;
}

int peek() {
return stack[top];
}

int pop() {
int data;

if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}

int push(int data) {

if(!isfull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}

int main() {
// push items on to the stack
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);

printf("Element at top of the stack: %d\n" ,peek());


printf("Elements: \n");

// print stack data


while(!isempty()) {
int data = pop();
printf("%d\n",data);
}

printf("Stack full: %s\n" , isfull()?"true":"false");


printf("Stack empty: %s\n" , isempty()?"true":"false");

getch();
return 0;
}
Reference:
https://www.tutorialspoint.com/data_structures_algorithms/stack_program_in_c.htm

Program Explanation
If we compile and run the above program, it will produce a list of elements and the
program will determine whether the stack is full or not
8. C Program to Illustrate Stack Operations using
MACROS
#include <stdio.h>
#include <stdlib.h>

#define MAX 5
#define EMPTY "Stack is Empty"
#define OVERFLOW "Stack Overflow"
#define ISOVERFLOW top >= MAX - 1 /*Macro to find whether the stack is full*/
#define ISEMPTY top == -1 /*Macro to find whether the stack is empty*/

void push(int);
void pop();
void display();
void stacksize();
void destroy();
void stackfull();

int top = -1;


int stack[MAX];

void main()
{
int choice, value;

while (1)
{
printf("Enter Your choice:\n");

printf("1.PUSH\n2.POP\n3.DISPLAY\n4.STACKSIZE\n5.DESTROY\n6.SATCKFULL
CHECK\n7.EXIT");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("enter the value to be pushed on to the stack");
scanf("%d", &value);
push(value);
continue;
case 2:
pop();
continue;
case 3:
display();
continue;
case 4:
stacksize();
continue;
case 5:
destroy();
continue;
case 6:
stackfull();
continue;
case 7:
exit(0);
default:
printf("YOU HAVE ENTERD A WRONG CHOICE");
}
}
}

/*Function to add an element into the stack*/


void push(int value)
{
if (ISOVERFLOW)
{
printf(OVERFLOW);
return;
}
top++;
stack[top] = value;
}

/*Function to delete an element from the stack*/


void pop()
{
if (ISEMPTY)
{
printf(EMPTY);
return;
}
printf("the popped element is %d", stack[top]);
top--;
}

/*Function to display all the elements in the stack*/

void display()
{
int temp = top;

if (ISEMPTY)
{
printf(EMPTY);
return;
}
while (temp + 1)
{
printf("%d\n", stack[temp]);
temp--;
}
}

/* Function to check whether the stack is full using macro */


void stackfull()
{
int temp = top, count = 0;

if (ISEMPTY)
{
printf(EMPTY);
return;
}
while (temp + 1)
{
printf("%d\n", stack[temp]);
temp--;
count++;
}
if (count >= MAX)
{
printf("Stack is full");
}
else
{
printf("there are %d more spaces in the stack", (MAX-count));
}
}

/* Function to return the size of the stack */


void stacksize()
{
int temp = top, count = 0;
if (ISEMPTY)
{
printf(EMPTY);
return;
}
while (temp + 1)
{
temp--;
count++;
}
printf("the size of the stack is %d\n", count);
}

/* Function to delete all the elements in the stack */

void destroy()
{
if (ISEMPTY)
{
printf("nothing is there to destroy");
}
while (top != -1)
{
pop();
}
}
Reference:https://www.sanfoundry.com/c-program-stack-operations-using-macros/
Program Explanation
1. Ask the user for the operations like push, pop, display etc.
2. According to the entered option access the respective functions. Use switch
statement to access the functions.
3. Use #define function to define macros as mentioned in the program.
4. In the push() function, ask the user to enter the number to be inserted and store the
value in the variable value and copy this value into the array stack[]. Use the variable
top to represent the top of the stack.
5. In the pop() function, delete the element at the top of the array and decrement the
variable top.
6. In the display() function, print all the elements from the top of stack to the bottom.
7. In the stack_size() function, print the number of elelments in the array stack.
8. In the destroy() function, pop all the elements from the array stack[].
9. In the stackfull() function, check if the array stack[] is full or not.
9. C Program to Implement Stack Operations
using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node *link;
}*top = NULL;

#define MAX 5

// function prototypes
void push();
void pop();
void empty();
void stack_full();
void stack_count();
void destroy();
void print_top();

void main()
{
int choice;

while (1)
{
printf("1. push an element \n");
printf("2. pop an element \n");
printf("3. check if stack is empty \n");
printf("4. check if stack is full \n");
printf("5. count/display elements present in stack \n");
printf("6. empty and destroy stack \n");
printf("7. Print top of the stack \n");
printf("8. exit \n");
printf("Enter your choice \n");
scanf("%d",&choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
empty();
break;
case 4:
stack_full();
break;
case 5:
stack_count();
break;
case 6:
destroy();
break;
case 7:
print_top();
break;
case 8:
exit(0);
default:
printf("wrong choice\n");
}
}
}

// to insert elements in stack


void push()
{
int val,count;
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));

count = st_count();
if (count <= MAX - 1)
{
printf("\nEnter value which you want to push into the stack :\n");
scanf("%d",&val);
temp->data = val;
temp->link = top;
top = temp;
}
else
printf("WARNING: STACK FULL\n");
}

// to delete elements from stack


void pop()
{
struct node *temp;
if (top = = NULL)
printf("**Stack is empty**\n");
else
{
temp = top;
printf("Value popped out is %d \n",temp->data);
top = top->link;
free(temp);
}
}

// to check if stack is empty


void empty()
{
if (top == NULL)
printf("STACK IS EMPTY\n");
else
printf("elements are present, stack is not empty \n");
}

// to check if stack is full


void stack_full()
{
int count;

count = st_count();
if (count = = MAX)
{
printf("stack is full\n");
}
else
printf("stack is not full \n");
}
// to count the number of elements
void stack_count()
{
int count = 0;
struct node *temp;

temp = top;
while (temp! = NULL)
{
printf(" %d\n",temp->data);
temp = temp->link;
count++;
}
printf("size of stack is %d \n",count);
}

int st_count()
{
int count = 0;
struct node *temp;
temp = top;
while (temp! = NULL)
{
temp = temp->link;
count++;
}
return count;
}

// to empty and destroy the stack


void destroy()
{
struct node *temp;
temp = top;
while (temp! = NULL)
{
pop();
temp = temp->link;
}
printf("stack destroyed\n");
}

// to print top element of stack


void print_top()
{
if (top == NULL)
printf("\n**Top is not available for an EMPTY stack**\n");
else
printf("\nTop of the stack is %d \n",top->data);
}
Reference: https://www.sanfoundry.com/c-program-implement-stack-operations/
Program Explanation
1. Ask the user for the operations like push, pop, display etc.
2. According to the entered option access the respective functions. Use switch
statement to access the functions.
3. Use structure with a data and a pointer as the data module. Use malloc function to
assign the memory dynamically.
4. In the push() function ask the user to enter the number to be inserted and store it in
the variable val.
5. Copy the value to the new data module’s data.
6. In the pop() function delete the element at the top.
7. In the display() function using for loop display all the data starting from top to the
bottom.
10. C Program to Identify whether the String is
Palindrome or not using Stack
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50

int top = -1, front = 0;


int stack[MAX];
void push(char);
void pop();

void main()
{
int i, choice;
char s[MAX], b;
while (1)
{
printf("1-enter string\n2-exit\n");
printf("enter your choice\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the String\n");
scanf("%s", s);
for (i = 0;s[i] != '\0';i++)
{
b = s[i];
push(b);
}
for (i = 0;i < (strlen(s) / 2);i++)
{
if (stack[top] == stack[front])
{
pop();
front++;
}
else
{
printf("%s is not a palindrome\n", s);
break;
}
}
if ((strlen(s) / 2) = = front)
printf("%s is palindrome\n", s);
front = 0;
top = -1;
break;
case 2:
exit(0);
default:
printf("enter correct choice\n");
}
}
}

/* to push a character into stack */


void push(char a)
{
top++;
stack[top] = a;
}
/* to delete an element in stack */
void pop()
{
top--;
}
Reference: https://www.sanfoundry.com/c-program-check-string-palindrome-stack/

Program Explanation
1. Take a string as input and store it in the array s[].
2. Load each character of the array s[] into the array stack[].
3. Use variables front and top to represent the last and top element of the array stack[].
4. Using for loop compare the top and last element of the array stack[]. If they are equal,
then delete the top element, increment the variable front by 1 and compare again.
5. If they are not equal, then print the output as “It is not a palindrome”.
6. Compare the elements in the steps 4-5 upto the middle element of the array stack[].
7. If every characters of the array is equal, then it is a paliandrome.
10 EXAMPLES OF QUEUE
PROGRAM
1. C Program to Implement a Queue using an
Array
#include <stdio.h>

#define MAX 50

void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */

void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */

void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */

void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
Reference: https://www.sanfoundry.com/c-program-queue-using-array/

Program Explanation

1. Ask the user for the operation like insert, delete, display and exit.
2. According to the option entered, access its respective function using switch
statement. Use the variables front and rear to represent the first and last element of the
queue.
3. In the function insert(), firstly check if the queue is full. If it is, then print the output as
“Queue Overflow”. Otherwise take the number to be inserted as input and store it in the
variable add_item. Copy the variable add_item to the array queue_array[] and
increment the variable rear by 1.
4. In the function delete(), firstly check if the queue is empty. If it is, then print the output
as “Queue Underflow”. Otherwise print the first element of the array queue_array[] and
decrement the variable front by 1.
5. In the function display(), using for loop print all the elements of the array starting from
front to rear.
6. Exit.
2. C Program to Implement Queue Data Structure
using Linked List
#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();

int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}

/* Create an empty queue */


void create()
{
front = rear = NULL;
}

/* Returns queue size */


void queuesize()
{
printf("\n Queue size : %d", count);
}

/* Enqueing the queue */


void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;

rear = temp;
}
count++;
}

/* Displaying the queue elements */


void display()
{
front1 = front;

if ((front1 == NULL) && (rear == NULL))


{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}

/* Dequeing the queue */


void deq()
{
front1 = front;

if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}

/* Returns the front element of queue */


int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}

/* Display if queue is empty or not */


void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
Reference: https://www.sanfoundry.com/c-program-queue-using-linked-list/
Program Explanation

This C Program implements queue using linked list. Queue is a particular kind of
abstract data type or collection in which the entities in the collection are kept in order
and the principal (or only) operations on the collection are the addition of entities to the
rear terminal position, known as enqueue, and removal of entities from the front terminal
position, known as dequeue. This makes the queue a First-In-First-Out (FIFO) data
structure. Linked list is a data structure consisting of a group of nodes which together
represent a sequence. Here we need to apply the application of linked list to perform
basic operations of queue.
3. C Program to Implement Priority Queue to
Add and Delete Elements
#include <stdio.h>
#include <stdlib.h>

#define MAX 5

void insert_by_priority(int);
void delete_by_priority(int);
void create();
void check(int);
void display_pqueue();

int pri_que[MAX];
int front, rear;

void main()
{
int n, ch;

printf("\n1 - Insert an element into queue");


printf("\n2 - Delete an element from queue");
printf("\n3 - Display queue elements");
printf("\n4 - Exit");

create();

while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);

switch (ch)
{
case 1:
printf("\nEnter value to be inserted : ");
scanf("%d",&n);
insert_by_priority(n);
break;
case 2:
printf("\nEnter value to delete : ");
scanf("%d",&n);
delete_by_priority(n);
break;
case 3:
display_pqueue();
break;
case 4:
exit(0);
default:
printf("\nChoice is incorrect, Enter a correct choice");
}
}
}

/* Function to create an empty priority queue */


void create()
{
front = rear = -1;
}

/* Function to insert value into priority queue */


void insert_by_priority(int data)
{
if (rear >= MAX - 1)
{
printf("\nQueue overflow no more elements can be inserted");
return;
}
if ((front == -1) && (rear == -1))
{
front++;
rear++;
pri_que[rear] = data;
return;
}
else
check(data);
rear++;
}

/* Function to check priority and place element */


void check(int data)
{
int i,j;

for (i = 0; i <= rear; i++)


{
if (data >= pri_que[i])
{
for (j = rear + 1; j > i; j--)
{
pri_que[j] = pri_que[j - 1];
}
pri_que[i] = data;
return;
}
}
pri_que[i] = data;
}

/* Function to delete an element from queue */


void delete_by_priority(int data)
{
int i;

if ((front==-1) && (rear==-1))


{
printf("\nQueue is empty no elements to delete");
return;
}

for (i = 0; i <= rear; i++)


{
if (data == pri_que[i])
{
for (; i < rear; i++)
{
pri_que[i] = pri_que[i + 1];
}

pri_que[i] = -99;
rear--;

if (rear == -1)
front = -1;
return;
}
}
printf("\n%d not found in queue to delete", data);
}

/* Function to display queue elements */


void display_pqueue()
{
if ((front == -1) && (rear == -1))
{
printf("\nQueue is empty");
return;
}

for (; front <= rear; front++)


{
printf(" %d ", pri_que[front]);
}

front = 0;
}
Reference: https://www.sanfoundry.com/c-program-priority-queue/

Program Explanation

Program to implement priority queue to add and delete elements.


4. C Program to Implement various Queue
Functions using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
#define MAX 10

struct node
{
int data;
struct node *link;
}*front, *rear;

// function protypes
void insert();
void delete();
void queue_size();
void check();
void first_element();

void main()
{
int choice, value;

while(1)
{
printf("enter the choice \n");
printf("1 : create an empty queue \n2 : Insert element\n");
printf("3 : Dequeue an element \n4 : Check if empty\n");
printf("5. Get the first element of the queue\n");
printf("6. Get the number of entries in the queue\n");
printf("7. Exit\n");
scanf("%d", &choice);
switch (choice) // menu driven program
{
case 1:
printf("Empty queue is created with a capacity of %d\n", MAX);
break;
case 2:
insert();
break;
case 3:
delete();
break;
case 4:
check();
break;
case 5:
first_element();
break;
case 6:
queue_size();
break;
case 7:
exit(0);
default:
printf("wrong choice\n");
break;
}
}
}

// to insert elements in queue


void insert()
{
struct node *temp;

temp = (struct node*)malloc(sizeof(struct node));


printf("Enter value to be inserted \n");
scanf("%d", &temp->data);
temp->link = NULL;
if (rear == NULL)
{
front = rear = temp;
}
else
{
rear->link = temp;
rear = temp;
}
}

// delete elements from queue


void delete()
{
struct node *temp;

temp = front;
if (front == NULL)
{
printf("queue is empty \n");
front = rear = NULL;
}
else
{
printf("deleted element is %d\n", front->data);
front = front->link;
free(temp);
}
}

// check if queue is empty or not


void check()
{
if (front == NULL)
printf("\nQueue is empty\n");
else
printf("*************** Elements are present in the queue **************\n");
}

// returns first element of queue


void first_element()
{
if (front == NULL)
{
printf("**************** The queue is empty ****************\n");
}
else
printf("**************** The front element is %d ***********\n", front->data);
}

// returns number of entries and displays the elements in queue


void queue_size()
{
struct node *temp;

temp = front;
int cnt = 0;
if (front == NULL)
{
printf(" queue empty \n");
}
while (temp)
{
printf("%d ", temp->data);
temp = temp->link;
cnt++;
}
printf("********* size of queue is %d ******** \n", cnt);
}
Reference: https://www.sanfoundry.com/c-program-implement-queue-functions/

Program Explanation

1. Ask the user for the operations like insert, delete, display etc.
2. According to the entered option access the respective functions. Use switch
statement to access the functions.
3. Use structure with a data and a pointer as the data module. Use malloc function to
assign the memory dynamically.
4. In the insert() function ask the user to enter the number to be inserted and store the
value into the new data module’s data.
5. In the delete() function delete the element at the front.
6. In the check() function, check if the queue is empty or not.
7. In the first_element() function, print the first element of the queue.
5. C Program to Implement Queue Functions
Using Arrays and Macros
#include <stdio.h>
#include<stdlib.h>

/* Macro Definition */
#define MAX 10
#define EMPTY "QUEUE EMPTY"
#define ISFULL rear >= MAX - 1
#define FULL "QUEUE FULL"
#define ISEMPTY rear == -1

/* Global Variable Declaration */


int queue[MAX], front = 0, rear = -1;

/* Fucntion Prototypes */
void insert_rear();
void delete_front();
void display_queue();
void empty_queue();
void front_ele();
int queue_size();
void destroy();

void main()
{
int choice, n, flag = 0;
char ch;

do
{
printf("MENU\n");
printf("Enter 1 to INSERT an element in the queue\n");
printf("Enter 2 to DELETE an element in the queue\n");
printf("Enter 3 to DISPLAY the elements of the queue\n");
printf("Enter 4 to CHECK if the queue is EMPTY\n");
printf("Enter 5 to KNOW the FIRST element of the queue\n");
printf("Enter 6 to KNOW the queue SIZE\n");
printf("Enter 7 to Destroy the Queue\n");
printf("Enter 8 to EXIT the program\n");
printf("Enter your Choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert_rear();
break;
case 2:
delete_front();
break;
case 3:
display_queue();
break;
case 4:
empty_queue();
break;
case 5:
front_ele();
break;
case 6:
n = queue_size();
printf("\nthe queue size is: %d", n);
break;
case 7:
destroy();
flag = 1;
break;
case 8:
exit(0);
break;
default:
printf("WRONG CHOICE\n");
}
printf("\nDo you want to continue:");
scanf(" %c", &ch);
} while(ch == 'y' || ch == 'Y');
if (flag == 0)
{
destroy();
}
}

/* Code to Insert the element in Queue */


void insert_rear()
{
int val;

if (ISFULL)
{
printf(FULL);
}
else
{
printf("\nEnter the value you want to insert in the queue:");
scanf("%d", &val);
rear++;
queue[rear] = val;
printf("\nElement successfully inserted in the queue");
}
}

/* Code to Delete the element in Queue */


void delete_front()
{
if (ISEMPTY)
{
printf(EMPTY);
}
else
{
printf("\nThe deleted element is: %d", queue[front]);
front++;
}
}

/* Code to Display the Elements of Queue */


void display_queue()
{
int i;

if (ISEMPTY)
{
printf(EMPTY);
}
else
{
for (i = front;i <= rear;i++)
{
printf("%d->", queue[i]);
}
}
}

/* Code to Check the Queue is Empty or Not */


void empty_queue()
{
if (ISEMPTY)
{
printf(EMPTY);
}
else
{
printf("\nTHE QUEUE has elements\n");
}
}

/* Code to Check the First element of Queue */


void front_ele()
{
if (ISEMPTY)
{
printf(EMPTY);
}
else
{
printf("The first element of the queue is: %d", queue[front]);
}
}

/* Code to Check the Size of Queue */


int queue_size()
{
int i = 0, count = 0;

if (ISEMPTY)
{
printf(EMPTY);
}
else
{
for (i = front;i <= rear;i++)
{
count++;
}
}
return count;
}

/* Code to destroy the queue */


void destroy()
{
int size, i;

if (ISEMPTY)
{
printf("EMPTY QUEUE CANNOT BE DESTROYED");
}
else
{
size = queue_size();

for (i = 0;i < size;i++)


{
front++;
}
front = 0;
rear = -1;
printf("\n\nQUEUE DESTROYED");
}
}
Reference: https://www.sanfoundry.com/c-program-implement-queue-functions-using-
arrays-macros/

Program Explanation

1. Ask the user for the operations like insert, delete, display etc.
2. According to the entered option access the respective functions. Use switch
statement to access the functions.
3. Use #define function to define macros as mentioned in the program.
4. In the insert_rear() function, ask the user to enter the number to be inserted and store
the value in the variable val and copy this value into the array queue[]. Use the variable
rear and front to represent the last and first element of the queue.
5. In the delete_front() function, delete the first element of the array and increment the
variable front.
6. In the display_queue() function, print all the elements of the array queue.
7. In the front_ele() function, check for the first element of the array queue[].
8. In the empty_queue() function, check if the array queue[] is empty or not.
9. In the queuesize() function, check the size of the array queue[].
10. In the destroy() function, delete all the elements from the array queue[].
6. C Program to Implement Queues using Stacks
#include <stdio.h>
#include <stdlib.h>

void push1(int);
void push2(int);
int pop1();
int pop2();
void enqueue();
void dequeue();
void display();
void create();

int st1[100], st2[100];


int top1 = -1, top2 = -1;
int count = 0;

void main()
{
int ch;

printf("\n1 - Enqueue element into queue");


printf("\n2 - Dequeu element from queue");
printf("\n3 - Display from queue");
printf("\n4 - Exit");
create();
while (1)
{
printf("\nEnter choice");
scanf("%d", &ch);
switch (ch)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Wrong choice");
}
}
}

/*Function to create a queue*/


void create()
{
top1 = top2 = -1;
}

/*Function to push the element on to the stack*/


void push1(int data)
{
st1[++top1] = data;
}

/*Function to pop the element from the stack*/


int pop1()
{
return(st1[top1--]);
}

/*Function to push an element on to stack*/


void push2(int data)
{
st2[++top2] = data;
}

/*Function to pop an element from th stack*/

int pop2()
{
return(st2[top2--]);
}

/*Function to add an element into the queue using stack*/


void enqueue()
{
int data, i;

printf("Enter data into queue");


scanf("%d", &data);
push1(data);
count++;
}

/*Function to delete an element from the queue using stack*/

void dequeue()
{
int i;

for (i = 0;i <= count;i++)


{
push2(pop1());
}
pop2();
count--;
for (i = 0;i <= count;i++)
{
push1(pop2());
}
}

/*Function to display the elements in the stack*/

void display()
{
int i;

for (i = 0;i <= top1;i++)


{
printf(" %d ", st1[i]);
}
}
Reference: https://www.sanfoundry.com/c-program-implement-queues-using-stacks/
Program Explanation

1. Ask the user for the operations like insert, delete and display.
2. According to the entered option access the respective function using switch
statement.
3. In the enqueue() function push the element into the array st1[].
4. In the dequeue () function, firstly transfer all the elements of the array st1[] into the
new array st2[]. Then the pop the first element of the new array.
5. In the display() function print all the elements of the st1[].
7. C program to implement queue using array/
linear implementation of queue
#include <stdio.h>
#define MAX 10

int QUEUE[MAX],front=-1,rear=-1;

/** function : insert_in_Q(),


to push an item into queue.
**/
void insert_in_Q(int queue[],int ele)
{
if(rear==-1)
{
front=rear=0;
queue[rear]=ele;
}
else if(rear==MAX-1)
{
printf("\nQUEUE is full.\n");
return;
}
else
{
rear++;
queue[rear]=ele;
}
printf("\nItem inserted..");
}

/** function : display_Q(),


to display queue elements
**/

void display_Q(int queue[])


{ int i;
if(rear==-1) { printf("\nQUEUE is Empty."); return; }
for(i=front;i<=rear;i++)
{ printf("%d,",queue[i]); }

/** function : remove_from_Q(),


to remove (pop) an item from queue.
**/
void remove_from_Q(int queue[])
{
int ele;
if(front==-1)
{
printf("QUEUE is Empty.");
return;
}
else if(front==rear)
{
ele=queue[front];
front=rear=-1;
}
else
{
ele=queue[front];
front++;
}
printf("\nItem removed : %d.",ele);
}

int main()
{
int ele,choice;
while(1)
{
//clrscr();
printf("\nQUEUE Elements are :");
display_Q(QUEUE);
printf("\n\nEnter choice (1:Insert,2:Display,3:Remove,0:Exit):");
scanf("%d",&choice);
switch(choice)
{
case 0:
exit(1);
break;
case 1:
printf("Enter an element to insert:");
scanf("%d",&ele);
insert_in_Q(QUEUE,ele);
break;
case 2:
display_Q(QUEUE);
break;
case 3:
remove_from_Q(QUEUE);
break;
default:
printf("\nInvalid choice\n");
break;
}

} //end of while(1)
return 0;
}

Reference: https://www.includehelp.com/c-programs/c-program-data-structure-queue-
implementation-using-array.aspx
Program Explanation
The program ask the user to input a number based on the instruction on the program, if
you click “1” it will ask to input a number to insert in the queue, if you click “2” it will
display the queue number you have given, if you click “3” it will remove the queue
number you have input in the program and if you click “0” the program will be
terminated.
8. Queue Implementation using C programming
#include<stdio.h>
#define SIZE 5

void enQueue(int);
void deQueue();
void display();

int items[SIZE], front = -1, rear = -1;

int main()
{
//deQueue is not possible on empty queue
deQueue();

//enQueue 5 elements
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);

//6th element can't be added to queue because queue is full


enQueue(6);

display();

//deQueue removes element entered first i.e. 1


deQueue();

//Now we have just 4 elements


display();

return 0;

void enQueue(int value){


if(rear == SIZE-1)
printf("\nQueue is Full!!");
else {
if(front == -1)
front = 0;
rear++;
items[rear] = value;
printf("\nInserted -> %d", value);
}
}

void deQueue(){
if(front == -1)
printf("\nQueue is Empty!!");
else{
printf("\nDeleted : %d", items[front]);
front++;
if(front > rear)
front = rear = -1;
}
}

void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
else{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",items[i]);
}
}

Reference: https://www.programiz.com/dsa/queue

Program Explanation
Two pointers called FRONT and REAR are used to keep track of the first and last
elements in the queue.
When initializing the queue, we set the value of FRONT and REAR to -1.
On enqueing an element, we increase the value of REAR index and place the new
element in the position pointed to by REAR.
On dequeueing an element, we return the value pointed to by FRONT and increase
the FRONT index.
Before enqueing, we check if queue is already full.
Before dequeuing, we check if queue is already empty.
When enqueing the first element, we set the value of FRONT to 0.
When dequeing the last element, we reset the values of FRONT and REAR to -1.
9. Simple Queue Program
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

#define MAX_SIZE 100

int main() {
int item, choice, i;
int arr_queue[MAX_SIZE];
int rear = 0;
int front = 0;
int exit = 1;

printf("\nSimple Queue Example - Array");


do {
printf("\n\n Queue Main Menu");

printf("\n1.Insert \n2.Remove \n3.Display \nOthers to exit");


printf("\nEnter Your Choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
if (rear == MAX_SIZE)
printf("\n## Queue Reached Max!!");
else {
printf("\nEnter The Value to be Insert : ");
scanf("%d", &item);
printf("\n## Position : %d , Insert Value : %d ", rear + 1, item);
arr_queue[rear++] = item;
}
break;
case 2:
if (front == rear)
printf("\n## Queue is Empty!");
else {
printf("\n## Position : %d , Remove Value : %d ", front, arr_queue[front]);
front++;
}
break;
case 3:
printf("\n## Queue Size : %d ", rear);
for (i = front; i < rear; i++)
printf("\n## Position : %d , Value : %d ", i, arr_queue[i]);
break;
default:
exit = 0;
break;
}
} while (exit);

return 0;
}

Reference: https://www.c-lang.thiyagaraaj.com/data-structures/c-queue-
programs/simple-queue-program-in-c-programming
Program Explanation

In each of the cases, the customer or object at the front of the line was the first one to
enter, while at the end of the line is the last to have entered. Every time a customer
finishes paying for their items (or a person steps off the escalator, or the machine part is
removed from the assembly line, etc.) that object leaves the queue from the front. This
represents the queue ? dequeue? function. Every time another object or customer
enters the line to wait, they join the end of the line and represent the ? enqueue?
function. The queue ?size? function would return the length of the line, and the ?empty?
function would return true only if there was nothing in the line.
10. C Program for Hospital Queue
#include <stdio.h>
#include<stdlib.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
int main()
{
int choice;
while (1)
{
printf("1.Insert element to queue n");
printf("2.Delete element from queue n");
printf("3.Display all elements of queue n");
printf("4.Quit n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice n");
}
}
}
void insert()
{
int item;
if(rear == MAX - 1)
printf("Queue Overflow n");
else
{
if(front== - 1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue_array[rear] = item;
}
}
void delete()
{
if(front == - 1 || front > rear)
{
printf("Queue Underflow n");
return;
}
else
{
printf("Element deleted from queue is : %dn", queue_array[front]);
front = front + 1;
}
}
void display()
{
int i;
if(front == - 1)
printf("Queue is empty n");
else
{
printf("Queue is : n");
for(i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("n");
}
}

Reference:https://www.edureka.co/blog/queue-in-c/

Program Explanation
This code is a menu-driven implementation of a queue. First, define the size of MAX
variable to be 50. Then, the array called queue array is declared of size MAX. There are
three functions that are to be declared. The functions are, insert, display and delete
functions. A menu-driven main function is used. The user is asked to enter his choice
and call the appropriate function to perform the task.
There are 2 pointers, the front is at the front of the queue and rear is at the back of the
queue. We add elements from the back of the queue and remove them from the front of
the queue.
Moving on with this article on Queue In C,

Вам также может понравиться