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

Assignment

The document discusses structures, pointers, and algorithms in C programming. It provides an algorithm to check if a string is a palindrome using a stack. The algorithm pushes characters of the input string to the stack and then pops characters from the stack, comparing each popped character to the corresponding character in the input string. If a mismatch is found, the string is not a palindrome. The document also provides an algorithm to convert an infix expression to postfix expression. It scans the infix expression from left to right, pushing operators to a stack or popping operators from the stack based on the precedence of operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Assignment

The document discusses structures, pointers, and algorithms in C programming. It provides an algorithm to check if a string is a palindrome using a stack. The algorithm pushes characters of the input string to the stack and then pops characters from the stack, comparing each popped character to the corresponding character in the input string. If a mismatch is found, the string is not a palindrome. The document also provides an algorithm to convert an infix expression to postfix expression. It scans the infix expression from left to right, pushing operators to a stack or popping operators from the stack based on the precedence of operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.What is a Structure?

A structure is a collection of data elements, encapsulated into one unit.


A structure definition is like a blueprint for the structure. It takes up no
storage space itself -- it just specifies what variables of this structure type
will look like
An actual structure variable is like a box with multiple data fields inside of it.
Consider the idea of a student database. One student record contains multiple items
of information (name, address, SSN, GPA, etc)
Properties of a structure:
internal elements may be of various data types
order of elements is arbitrary (no indexing, like with arrays)
Fixed size, based on the combined sizes of the internal elements.

USES
A structure is a collection of variables of same or different datatypes. It is
useful in storing or using informations or databases.

Example: An employee’s record must show its salary, position, experience, etc. It
all can be stored in one single variable using structures.

struct Employee
{
char ename[20];
int id;
float salary,experience;
};
Structure written inside another structure is called as nesting of two structures.
Nested Structures are allowed in C Programming Language. We can write one Structure
inside another structure as member of another structure.

Example:

struct date
{
int date;
int month;
int year;
};

struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
};
Here, struct date is passed as a member of struct employee. Hence, nested.

4. pointer

C Pointers
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-bit
architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an
integer.

int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the
variable n of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also
known as indirection pointer used to dereference a pointer.

int *a;//pointer to int


char *c;//pointer to char
Pointer Example
An example of using pointers to print the address and value is given below.

pointer example
As you can see in the above figure, pointer variable stores the address of number
variable, i.e., fff4. The value of number variable is 50. But the address of
pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable
p.

Let's see the pointer example as explained for the above figure.

#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number
therefore printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to
dereference a pointer therefore if we print *p, we will get the value stored at the
address contained by p.
return 0;
}
Output

Address of number variable is fff4


Address of p variable is fff4
Value of p variable is 50
Pointer to array
int arr[10];
int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an
integer array arr.
Pointer to a function
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address of a function
Pointer to structure
struct st {
int i;
float f;
}ref;
struct st *p = &ref;
c pointers
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees, etc. and used with arrays, structures, and functions.

ADVERTISEMENT
2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc()


functions where the pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It


reduces the code and improves the performance.

Address Of (&) Operator


The address of operator '&' returns the address of a variable. But, we need to use
%u to display the address of a variable.

#include<stdio.h>
int main(){
int number=50;
printf("value of number is %d, address of number is %u",number,&number);
return 0;
}
Output

value of number is 50, address of number is fff4


NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If
you don't have any address to be specified in the pointer at the time of
declaration, you can assign NULL value. It will provide a better approach.

int *p=NULL;
In the most libraries, the value of the pointer is 0 (zero).

part 2
11.List Applications Of Stacks. Using Stack Write An Algorithm To Determine If A
Given String Is Palindrome And Print Suitable Message As Output.
-> application
Following are the applications of stack:

1. Expression Evaluation
2. Expression Conversion
i. Infix to Postfix
ii. Infix to Prefix
iii. Postfix to Infix
iv. Prefix to Infix
3. Backtracking
4. Memory Management

A string is palindrome, if string remains same after reversing the sequence of it's
character. For example, "asdfdsa" is a palindrome string whereas string "mango" is
not a palindrome string.

A stack is LAST IN FIRST OUT (LIFO) data structure. The element which is inserted
last, is accessed first. Insertion and deletion of elements happens only at top of
the Stack. The sequence of exit of elements from a stack is reverse of the sequence
of their entry in stack.
Sequence of Entry.
A --> B --> C -- > D --> E
Sequence of Exit.
E --> D --> C --> B --> A
Algorithm to check palindrome string using stack
Find the length of the input string using strlen function and store it in a integer
variable "length".
Using a for loop, traverse input string from index 0 to length-1 and push all
characters in stack.
Remove (Pop) characters from stack one by one using a for loop and compare it with
corresponding character of input string from beginning(traverse from index 0 to
length-1). If we found a mismatch the input string is not a palindrome string
otherwise palindrome string.
C program to check a string is palindrome or not using a stack
#include <stdio.h>
#include <string.h>

#define MAXSIZE 100


#define TRUE 1
#define FALSE 0

// Structure defining Stack data structure


struct Stack {
int top;
int array[MAXSIZE];
} st;

/*
Initializes the top index to -1
*/
void initialize() {
st.top = -1;
}

/*
Checks if Stack is Full or not
*/
int isFull() {
if(st.top >= MAXSIZE-1)
return TRUE;
else
return FALSE;
}

/*
Checks if Stack is Empty or not
*/
int isEmpty() {
if(st.top == -1)
return TRUE;
else
return FALSE;
}

/*
Adds an element to stack and then increment top index
*/
void push(int num) {
if (isFull())
printf("Stack is Full...\n");
else {
st.array[st.top + 1] = num;
st.top++;
}
}

/*
Removes top element from stack and decrement top index
*/
int pop() {
if (isEmpty())
printf("Stack is Empty...\n");
else {
st.top = st.top - 1;
return st.array[st.top+1];
}
}

int main() {
char inputString[100], c;
int i, length;
initialize();
printf("Enter a string\n");
gets(inputString);
length = strlen(inputString);
/* Push all characters of input String to Stack */
for(i = 0; i < length; i++){
push(inputString[i]);
}
/* Poping characters from stack returs the characters of input string
in reverse order. We will then compare it with corresponding
characters of input string. If we found a mismatch the input
string is not a palindrome string */
for(i = 0; i < length; i++){
if(pop() != inputString[i]) {
printf("Not a Palindrome String\n");
return 0;
}
}

printf("Palindrome String\n");
return 0;
}
</string.h></stdio.h>

Output
Enter a string
ASDFGFDSA
Palindrome String
Enter a string
TECHCRASHCOURSE
Not a Palindrome String

16. Write An Algorithm For Converting Infix Expression To Post-Fix Expression.


Trace The Algorithm
Indicating Content Of Stack For Expression (A-B)/(C*D)+E.
Infix expression: The expression of the form a op b. When an operator is in-between
every pair of operands.
Postfix expression: The expression of the form a b op. When an operator is followed
for every pair of operands.
Why postfix representation of the expression?
The compiler scans the expression either from left to right or from right to left.
Consider the below expression: a op1 b op2 c op3 d
If op1 = +, op2 = *, op3 = +
The compiler first scans the expression to evaluate the expression b * c, then
again scan the expression to add a to it. The result is then added to d after
another scan.
The repeated scanning makes it very in-efficient. It is better to convert the
expression to postfix(or prefix) form before evaluation.
The corresponding expression in postfix form is: abc*+d+. The postfix expressions
can be evaluated easily using a stack. We will cover postfix expression evaluation
in a separate post.
Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
1 If the precedence of the scanned operator is greater than the precedence of
the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push
it.
2 Else, Pop all the operators from the stack which are greater than or equal
to in precedence than that of the scanned operator. After doing that Push the
scanned operator to the stack. (If you encounter parenthesis while popping then
stop there and push the scanned operator in the stack.)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is
encountered, and discard both the parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Print the output
8. Pop and output from the stack until it is not empty.
Infix:
(A-B)/(C*D)+E

Infix to Postfix

Postfix:
AB-CD*/E+

Step by step output for "" expression


Input String Output Stack Operator Stack
(A-B)/(C*D)+E (
(A-B)/(C*D)+E A (
(A-B)/(C*D)+E A (-
(A-B)/(C*D)+E AB (-
(A-B)/(C*D)+E AB-
(A-B)/(C*D)+E AB- /
(A-B)/(C*D)+E AB- /(
(A-B)/(C*D)+E AB-C /(
(A-B)/(C*D)+E AB-C /(*
(A-B)/(C*D)+E AB-CD /(*
(A-B)/(C*D)+E AB-CD* /
(A-B)/(C*D)+E AB-CD*/ +
(A-B)/(C*D)+E AB-CD*/E +
(A-B)/(C*D)+E AB-CD*/E+
part 3
1.
What is a Linear Queue
A linear queue is a queue that is similar to a straight line. It consists of a set
of data elements one after the other. Therefore, it is possible to add new
elements to the queue from one end. Hence, we call this operation enqueue.
Similarly, it is possible to remove the element from the queue from the other end.
And, we call this operation dequeue. The front of the queue is head and end of the
queue is tail or rear. In a linear queue, it is possible to insert new items from
the rear and remove the items from the front. Moreover, a queue is similar to
people waiting in a straight line to access ATM machine. A new person comes and
joins at the end of the queue, and the first person in the queue get access to the
machine.

Difference Between Linear and Circular Queue


Figure 1: Linear Queue

We can perform several operations on a linear queue. We can initialize a queue to


zero. We can also check whether the queue is empty or not. Another operation is to
find whether the queue is empty or not. These are some common operations to perform
on a linear queue, in addition to enqueue and dequeue operations.

Even though a linear queue is simple to implement, it has some drawbacks. Removing
items from the queue can create more space. However, it can still be difficult to
enter new elements as this can cause an underflow condition. A circular queue helps
to overcome this issue.

What is a Circlular Queue


In a circular queue, the last item connects back to the first item to create a
circle. Therefore, a circular queue is also called a ring buffer.

Main Difference - Linear vs Circular Queue


Figure 2: A 24-byte Keyboard Circular Queue

As a circular queue connects the two ends, the first item comes after the last
item. There is no overflow condition in a circular queue until the queue is
actually full. Therefore, entering a new element is easy.

Furthermore, the circular queue works according to the below two conditions. The
maxSize indicates the maximum number of items the queue can consist of.

rear = (rear +1 ) % maxSize;

front = (front + 1) % maxSize;

part 4
6. What Is A Single Linked List? Explain With An Example How A Single Linked List
Can Be Used For
Sorting A Set Of N Numbers.
A singly linked list is a type of linked list that is unidirectional, that is, it
can be traversed in only one direction from head to the last node (tail).

Each element in a linked list is called a node. A single node contains data and a
pointer to the next node which helps in maintaining the structure of the list.

The first node is called the head; it points to the first node of the list and
helps us access every other element in the list. The last node, also sometimes
called the tail, points to NULL which helps us in determining when the list ends.
svg viewer
An example of a singly Linked List.
#include <stdio.h>

//Represent a node of the singly linked list


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

//Represent the head and tail of the singly linked list


struct node *head, *tail = NULL;

//addNode() will add a new node to the list


void addNode(int data) {
//Create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;

//Checks if the list is empty


if(head == NULL) {
//If list is empty, both head and tail will point to new node
head = newNode;
tail = newNode;
}
else {
//newNode will be added after tail such that tail's next will point to
newNode
tail->next = newNode;
//newNode will become new tail of the list
tail = newNode;
}
}

//sortList() will sort nodes of the list in ascending order


void sortList() {
//Node current will point to head
struct node *current = head, *index = NULL;
int temp;

if(head == NULL) {
return;
}
else {
while(current != NULL) {
//Node index will point to node next to current
index = current->next;

while(index != NULL) {
//If current node's data is greater than index's node data,
swap the data between them
if(current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}

//display() will display all the nodes present in the list


void display() {
//Node current will point to head
struct node *current = head;
if(head == NULL) {
printf("List is empty \n");
return;
}
while(current != NULL) {
//Prints each node by incrementing pointer
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main()
{
//Adds data to the list
addNode(9);
addNode(7);
addNode(2);
addNode(5);
addNode(4);

//Displaying original list


printf("Original list: \n");
display();

//Sorting list
sortList();

//Displaying sorted list


printf("Sorted list: \n");
display();

return 0;
}
Output:

Original list:
9 7 2 5 4
Sorted list:
2 4 5 7 9

11. write advantages of doubly linked list over singly linked list. write c
function that will insert a given integer value into an ordered doubly linked list.
Following are advantages/disadvantages of doubly linked list over singly linked
list.
Advantages over singly linked list
1) A DLL can be traversed in both forward and backward direction.
2) The delete operation in DLL is more efficient if pointer to the node to be
deleted is given.
3) We can quickly insert a new node before a given node.
In singly linked list, to delete a node, pointer to the previous node is needed. To
get this previous node, sometimes the list is traversed. In DLL, we can get the
previous node using previous pointer.

// C++ implementation to insert value in sorted way


// in a sorted doubly linked list
#include <bits/stdc++.h>

using namespace std;

// Node of a doubly linked list


struct Node {
int data;
struct Node* prev, *next;
};

// function to create and return a new node


// of a doubly linked list
struct Node* getNode(int data)
{
// allocate node
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));

// put in the data


newNode->data = data;
newNode->prev = newNode->next = NULL;
return newNode;
}

// function to insert a new node in sorted way in


// a sorted doubly linked list
void sortedInsert(struct Node** head_ref, struct Node* newNode)
{
struct Node* current;

// if list is empty
if (*head_ref == NULL)
*head_ref = newNode;

// if the node is to be inserted at the beginning


// of the doubly linked list
else if ((*head_ref)->data >= newNode->data) {
newNode->next = *head_ref;
newNode->next->prev = newNode;
*head_ref = newNode;
}

else {
current = *head_ref;

// locate the node after which the new node


// is to be inserted
while (current->next != NULL &&
current->next->data < newNode->data)
current = current->next;

/* Make the appropriate links */


newNode->next = current->next;
// if the new node is not inserted
// at the end of the list
if (current->next != NULL)
newNode->next->prev = newNode;

current->next = newNode;
newNode->prev = current;
}
}

// function to print the doubly linked list


void printList(struct Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}

// Driver program to test above


int main()
{
/* start with the empty doubly linked list */
struct Node* head = NULL;

// insert the following nodes in sorted way


struct Node* new_node = getNode(8);
sortedInsert(&head, new_node);
new_node = getNode(5);
sortedInsert(&head, new_node);
new_node = getNode(3);
sortedInsert(&head, new_node);
new_node = getNode(10);
sortedInsert(&head, new_node);
new_node = getNode(12);
sortedInsert(&head, new_node);
new_node = getNode(9);
sortedInsert(&head, new_node);

cout << "Created Doubly Linked Listn";


printList(head);
return 0;
}
Output:

Created Doubly Linked List


3 5 8 9 10 12

part 5
1. What Is An Algorithm? Write General Characteristics Of Design Analysis And
Algorithm.
Algorithm is a step-by-step procedure, which defines a set of instructions to be
executed in a certain order to get the desired output. Algorithms are generally
created independent of underlying languages, i.e. an algorithm can be implemented
in more than one programming language.

From the data structure point of view, following are some important categories of
algorithms −
Search − Algorithm to search an item in a data structure.

Sort − Algorithm to sort items in a certain order.

Insert − Algorithm to insert item in a data structure.

Update − Algorithm to update an existing item in a data structure.

Delete − Algorithm to delete an existing item from a data structure.

Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the
following characteristics −

Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one
meaning.

Input − An algorithm should have 0 or more well-defined inputs.

Output − An algorithm should have 1 or more well-defined outputs, and should match
the desired output.

Finiteness − Algorithms must terminate after a finite number of steps.

Feasibility − Should be feasible with the available resources.

Independent − An algorithm should have step-by-step directions, which should be


independent of any programming code.

11. Explain Divide-And-Conquer Method With One Example

In divide and conquer approach, the problem in hand, is divided into smaller sub-
problems and then each problem is solved independently. When we keep on dividing
the subproblems into even smaller sub-problems, we may eventually reach a stage
where no more division is possible. Those "atomic" smallest possible sub-problem
(fractions) are solved. The solution of all sub-problems is finally merged in order
to obtain the solution of an original problem.

Divide and Conquer


Broadly, we can understand divide-and-conquer approach in a three-step process.

Divide/Break
This step involves breaking the problem into smaller sub-problems. Sub-problems
should represent a part of the original problem. This step generally takes a
recursive approach to divide the problem until no sub-problem is further divisible.
At this stage, sub-problems become atomic in nature but still represent some part
of the actual problem.

Conquer/Solve
This step receives a lot of smaller sub-problems to be solved. Generally, at this
level, the problems are considered 'solved' on their own.

Merge/Combine
When the smaller sub-problems are solved, this stage recursively combines them
until they formulate a solution of the original problem. This algorithmic approach
works recursively and conquer & merge steps works so close that they appear as one.
Examples
The following computer algorithms are based on divide-and-conquer programming
approach −

Merge Sort
Quick Sort
Binary Search
Strassen's Matrix Multiplication
Closest pair (points)
There are various ways available to solve any computer problem, but the mentioned
are a good example of divide and conquer approach.

You might also like