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

Unit-2_Array+P1

The document provides notes for B.Tech. CSE 4th semester students on Linear Data Structures, specifically focusing on arrays and stacks. It covers definitions, types, advantages, disadvantages, and operations of arrays, as well as detailed explanations and implementations of stack operations using both arrays and linked lists. Additionally, it includes example C programs for various array operations and stack functionalities.

Uploaded by

Ghana Uni Help
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit-2_Array+P1

The document provides notes for B.Tech. CSE 4th semester students on Linear Data Structures, specifically focusing on arrays and stacks. It covers definitions, types, advantages, disadvantages, and operations of arrays, as well as detailed explanations and implementations of stack operations using both arrays and linked lists. Additionally, it includes example C programs for various array operations and stack functionalities.

Uploaded by

Ghana Uni Help
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

DS Notes Class: B.Tech.

CSE 4th Sem

Unit-II
[Linear Data Structures and their Sequential Representation: Array, stack, queue, circular queue and
their operations and applications.]

Array

Students have already studied this concept in earlier semesters. So, They are expected to revise
following questions and answers.

1. Define array and types of array.


An array is collection of homogeneous elements stored in consecutive memory locations.
Array is declared as:
type arrayName [ arraySize ];

A specific element in an array is accessed by an index, which ranges from 0 to 'arraySize-1'.

Types of array:
➢ Single Dimensional Array: Single or One Dimensional array is used to represent
and store data in a linear form. It has only one subscript variable and it is also called
Linear Array.

Ex: int a[5] = {4, 7, 8, 9, 6};

➢ Multi Dimensional Array: Array having more than one subscript variable is called
Multi-Dimensional array. It is also called as Matrix.

Ex: int a[2][2] = {4, 5, 6, 8};

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

2. What are the advantages and disadvantages of an Array ?

Following are main advantages of using an array :

1. Arrays are the most convenient way of storing the fixed amount of data that can
be accessed in an unpredictable fashion

2. Another advantage of array is that iterating through an array is more faster than
compared to other data structure types like linked list because of its good
locality of reference.

Following are the main disadvantages of using an Array :


1. The size of the array should be know up priori i.e. before the compile time.
2. C language does not have a checking mechanism for the array sizes.

3. How can we use pointers for accessing array elements?

Consider an array:
int arr[4];

In C programming, name of the array always points to address of the first element of an
array. In the above example, arr and &arr[0] points to the address of the first element.
➢ &arr[0] is equivalent to arr and arr[0] is equivalent to *arr (value of an address of
the pointer)
Similarly,
➢ &arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
➢ &arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
➢ &arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3)
..............
..............
➢ &arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

4. How to pass array as function arguments in C?


The array is passed to a function using its name, which denotes its base address. But the
formal parameters for the corresponding array arguments can be one of the followings:
➢ Pointers
➢ Array (sized or unsized)
Example: Find average of the numbers entered in an array:
Using Pointers:
/* Program to find average of the numbers entered in an array */
#include <stdio.h>
/* function declaration */
float getAverage(int arr[], int size);
void main () {
int arr[50], size, i;
float avg;
/* ask user for size of array */
printf("\nEnter the size of array.. \t");
scanf("%d", &size);
/* ask user for elements of array */
printf("Enter the elements of array:\t");
for(i = 0; i < size; i++){
scanf("%d", &arr[i]);
}
/* display the array elements */
printf("Array elements are:\t\t[ ");
for(i = 0; i < size; i++){
printf("%d ", arr[i]);
}
printf("]\n");
/* pass pointer to the array as an argument */
avg = getAverage( arr, size ) ;
/* output the returned value */
printf( "\nAverage value is: %f \n", avg );
}
/* function definition */
float getAverage(int arr[], int size) {
int i;
float avg;
float sum = 0;
for (i = 0; i < size; i++) {
sum = sum + arr[i];
}
avg = sum / size;
return avg;
}

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

Using array:
/* Program to find average of the numbers entered in an array */
#include <stdio.h>
/* function declaration */
float getAverage(int *arr, int size);
void main () {
int arr[50], size, i;
float avg;
/* ask user for size of array */
printf("\nEnter the size of array.. \t");
scanf("%d", &size);
/* ask user for elements of array */
printf("Enter the elements of array:\t");
for(i = 0; i < size; i++){
scanf("%d", &arr[i]);
}
/* display the array elements */
printf("Array elements are:\t\t[ ");
for(i = 0; i < size; i++){
printf("%d ", arr[i]);
}
printf("]\n");
/* pass pointer to the array as an argument */
avg = getAverage( arr, size ) ;
/* output the returned value */
printf( "\nAverage value is: %f \n", avg );
}
/* function definition */
float getAverage(int *arr, int size) {
int i;
float avg;
float sum = 0;
for (i = 0; i < size; i++) {
sum = sum + *(arr + i);
//sum = sum + arr[i];
}
avg = sum / size;
return avg;
}

OUTPUT

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

5. Write a C program to search an element in the 2-D array using linear search.

/* Search user input key in 2D array */


#include <stdio.h>
/* Function Definition */
void searchKeyIn2D(int *p, int k, int r, int c){
int i, j, flag=0;
/* Display the 2D array */
printf("The 2D array: \n");
for(i=0; i<r; i++){
for(j=0; j<c; j++){
printf("%d \t", (*p+i*c+j));
}
printf("\n");
}
/* Searching the entered key */
for(i=0; i<r; i++){
for(j=0; j<c; j++){
if (k == (*p+i*c+j)){
printf("\nSearch Key = %d is found at row = %d and col =
%d \n", k, i+1, j+1);
flag = 1;
break;
}
}
}
if (flag == 0){
printf("\nSearch Key = %d is not found in the given 2D array\n",k);
}
}
void main(){
int arr[50][50], i, j, row, col, key, flag = 0;
printf("\nEnter the number of rows and columns for 2D array:\t");
scanf("%d %d", &row, &col);
printf("Enter the elements of the 2D array:\t");
/* Enter the 2D array Elements */
for(i=0; i<row; i++){
for(j=0; j<col; j++){
scanf("%d", &arr[i][j]);
}
}
/* Display the 2D array */
printf("The 2D array: \n");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d \t", arr[i][j]);

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

//printf("%d \t", *(*(arr+i) + j));


//printf("%d \t", *(arr[i] + j));
//printf("%d \t", (*(arr + i))[j]);
}
printf("\n");
}
/* ask user to enter the search key */
printf("Enter the key you want to search: \t");
scanf("%d", &key);
/* Call the function to search elements linearly */
searchKeyIn2D(arr, key, row, col);
}

OUTPUT

Assignments on Array

1. Write a C program to delete an element from an array at specified position.


2. Write a C program to find sum of main diagonal elements of a matrix.
3. Write a C program to find second largest element in an array using function.
4. Write a C program to merge two character array to third array.
5. Write a C program to copy all elements from an array to another array.

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

STACK

Stack is a special type of data structure where elements are inserted from one end and elements are
deleted from the same end. The position from where elements a are inserted and from where
elements are deleted is termed as top of the stack.

Thus stack is a homogeneous collection of elements of any one type, arranged linearly with access
at one end only. Stack is also called Last In First Out (LIFO) data structure.

OPERATION ON STACK:
• Push
• Pop

1. Push Operation: The procedure of inserting a new element to the top of the stack is known
as push operation. A pointer TOP is used to point the top element in the stack, which gets
incremented by 1 after every insertion.

If the stack is full and does not contain enough space to accept the given element or data, the
stack is then considered to be in an overflow state.

2. Pop Operation: The procedure of removing element from the top of the stack is called pop
operation. Only one element can be deleted at a time and element has to be deleted only
from the top of the stack. After every deletion, TOP gets decremented by 1.

When elements are being deleted, there is a possibility of stack being empty. When stack is
empty, it is not possible to delete any element. Trying to delete an element from an empty
stack results in stack underflow.

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

Implementation of stack:

1. Static Implementation (Using Arrays) : Though array implementation is a simple


technique, it provides less flexibility and is not very efficient with respect to memory
organization. This is because once a size of an array is declared, its size cannot be modified
during program execution. If the number of elements to be stored in a stack is less than the
allocated memory, then memory is wasted and if we want to store more elements than
declared, array cannot be expanded. It is suitable only when we exactly know the number of
elements to be stored.

2. Dynamic Implementation (Using Linked List) : The limitations of static implementation


can be removed using dynamic implementation. The memory is efficiently utilized with
pointers. Memory is allocated only after element is inserted to the stack. The stack can grow
or shrink as the program demands it to. However, if a small and/or fixed amount of data is
being dealt with, it is often simpler to implement the stack as an array.

Implementation of stack using array:

Push Operation:

Description: Here STACK is an array with MAX locations. TOP points to the top most
element and ITEM is the value to be inserted.

1. If (TOP == MAX) Then //[Check for overflow]


2. Print: Overflow
3. Else
4. Set TOP = TOP + 1 //[Increment TOP by 1]
5. Set STACK[TOP] = ITEM //[Assign ITEM to top of STACK]
6. Print: ITEM inserted //[End of If]
7. Exit

Pop Operation:

Description: Here STACK is an array with MAX locations. TOP points to the top most
element.

1. If (TOP == 0) Then //[Check for underflow]


2. Print: Underflow
3. Else
4. Set ITEM = STACK[TOP] //[Assign top of STACK to ITEM]
5. Set TOP = TOP - 1 //[Decrement TOP by 1]
6. Print: ITEM deleted //[End of If]
7. Exit

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

Implementation of stack using Linked List:

To implement stack using linked list, we need to set the following things before implementing
actual operations.
• Define a 'Node' structure with two members data and next.
• Define a Node pointer 'top' and set it to NULL.

Push Operation:

Step 1: Create a 'newNode' with given value.


Step 2: If (top == NULL)
Step 3: Print 'stack is Empty'
Step 4: set newNode → next = NULL.
Step 5: End of If
Step 6: Else
Step 7: set newNode → next = top.
Step 8: set top = newNode.
Step 9: End of Else

Pop Operation:

Step 1: If (top == NULL)


Step 2: Print 'stack is Empty, Deletion is not possible'
Step 3: End of If
Step 4: Else
Step 5: Define a Node pointer 'temp' and set it to 'top'
temp = top
Step 6: top = top → next
Step 7: Delete temp using free (temp)
Step 8: End of Else

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

Display Operation:

Step 1: If (top == NULL)


Step 2: Print 'stack is Empty'
Step 3: End of If
Step 4: Else
Step 5: Define a Node pointer 'temp' and set it to 'top'
temp = top
Step 6: while(temp → next != NULL)
Step 7: Display temp → data
Step 8: temp = temp → next
Step 9: End of while
Step 10: End of Else

PROGRAM OF LINKED STACK:


#include<stdio.h>

// Node Structure
struct Node
{
int data;
struct Node *next;
}*top = NULL; // Initially top is NULL

//Function declaration
void push(int);
void pop();
void display();

void main()
{
int choice, value;

printf("\n:: Stack using Linked List ::\n");


while(1){
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

printf("Enter your choice: ");


scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try
again!!!\n");
}
}
}

/* Push operation */
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode­>data = value;
if(top == NULL)
newNode­>next = NULL;
else
newNode­>next = top;
top = newNode;
printf("\nInsertion is Success!!!\n");
display();
} // End of Push

/* Pop operation */
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
printf("\nDeleted element: %d\n", temp­>data);
top = temp­>next;
free(temp);
}
display();
} // End of Pop

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

/* Display */
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
while(temp­>next != NULL){
printf("%d­­­>",temp­>data);
temp = temp ­> next;
}
printf("%d­­­>NULL \n",temp­>data);
}
} // End of display

Output

:: Stack using Linked List ::

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 10

Insertion is Success!!!
10­­­>NULL

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 30

Insertion is Success!!!
30­­­>10­­­>NULL

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 60

Insertion is Success!!!
60­­­>30­­­>10­­­>NULL

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 20

Insertion is Success!!!
20­­­>60­­­>30­­­>10­­­>NULL

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 50

Insertion is Success!!!
50­­­>20­­­>60­­­>30­­­>10­­­>NULL

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

Deleted element: 50
20­­­>60­­­>30­­­>10­­­>NULL

****** MENU ******


1. Push
2. Pop

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

3. Display
4. Exit
Enter your choice: 2

Deleted element: 20
60­­­>30­­­>10­­­>NULL

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

Deleted element: 60
30­­­>10­­­>NULL

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

Deleted element: 30
10­­­>NULL

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

Deleted element: 10

Stack is Empty!!!

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

Stack is Empty!!!

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

Stack is Empty!!!

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 4

APPLICATION OF STACK:

1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the processor’s
stack.
5. During a function call the return address and arguments are pushed onto a stack and on
return they are popped off.

Converting expressions using Stack:

It can be done as follows:


• Infix to postfix
• Infix to prefix
• Postfix to infix
• Postfix to prefix
• Prefix to infix
• Prefix to postfix

1. Infix to postfix:

1. Print operands as they arrive.


2. If the incoming symbol is a left parenthesis, push it on the stack.
3. If the stack is empty or contains a left parenthesis on top, push the incoming operator
onto the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the operators
until you see a left parenthesis. Discard the pair of parentheses.

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

5. If the incoming operator has higher precedence than the top of the stack, push it on
the stack.
6. If the incoming operator has lower precedence than the operator on the top of the
stack, pop the stack and print the top operator. Then test the incoming operator
against the new top of stack.
7. At the end of the expression, pop and print all operators on the stack. (No
parentheses should remain.)
Let us see how the above algorithm will be imlemented using an example.
Infix String : a+b*c-d
Initially the Stack is empty and our Postfix string has no characters.
• Now, the first character scanned is 'a'. 'a' is added to the Postfix string.
• The next character scanned is '+'. It being an operator, it is pushed to the stack.

Stack Postfix String


• Next character scanned is 'b' which will be placed in the Postfix string.
• Next character is '*' which is an operator. Now, the top element of the stack is '+' which has
lower precedence than '*', so '*' will be pushed to the stack.

Stack Postfix String


• The next character is 'c' which is placed in the Postfix string.
• Next character scanned is '-'. The topmost character in the stack is '*' which has a higher
precedence than '-'. Thus '*' will be popped out from the stack and added to the Postfix
string. Even now the stack is not empty. Now the topmost element of the stack is '+' which
has equal priority to '-', i.e priority of '-' is not greater than '+'. So pop the '+' from the stack
and add it to the Postfix string.
• The '-' will be pushed to the stack.

Stack Postfix String

Provided By: Shipra Swati, PSCET, Bihar


DS Notes Class: B.Tech. CSE 4th Sem

• Next character is 'd' which is added to Postfix string.


• At this stage we have only a '-' in the stack. It is popped out and added to the Postfix string.
So, after all characters are scanned, this is how the stack and Postfix string will be :

Stack Postfix String

End result :
• Infix String : a+b*c-d
• Postfix String : abc*+d-

2. Postfix to Infix:

1. Scan the postfix expression from left to right.


2. If the scanned symbol is an operand, then push it onto the stack.
3. If the scanned symbol is an operator, pop two symbols from the stack and create it as a
string by placing the operator in between the operands and push it onto the stack.
4. Repeat steps 2 and 3 till the end of the expression.

Evaluation of Postfix Expression:

Step 1 − scan the expression from left to right


Step 2 − if it is an operand push it to stack
Step 3 − if it is an operator pull operand from stack and perform operation
Step 4 − store the output of step 3, back to stack
Step 5 − scan the expression until all operands are consumed
Step 6 − pop the stack and perform operation

Provided By: Shipra Swati, PSCET, Bihar

You might also like