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

arrays

Uploaded by

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

arrays

Uploaded by

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

array is linear data structure in which same type of elements are stored in contiguous memory locations

DATA STRUCTURES
Arrays in Data Structures

An array is a linear data structure that collects elements of the same data type and stores them
in contiguous and adjacent memory locations. Arrays work on an index system starting from 0 to
(n-1), where n is the size of the array.

What Are the Types of Arrays?


There are majorly two types of arrays, they are: 1d
2d
One-Dimensional Arrays:

You can imagine a 1d array as a row, where elements are stored one after another.

Two-Dimensional Arrays:
You can imagine it like a table where each cell contains elements.

How Do You Declare an Array? int[] arr=new int[size];

Arrays are typically defined with square brackets with the size of the arrays as its argument.
Here is the syntax for arrays:
1D Arrays: int arr[n];
2D Arrays: int arr[m][n];
How Do You Initialize an Array?
You can initialize an array in four different ways:
• Method 1:
int a[6] = {2, 3, 5, 7, 11, 13};
• Method 2:
int arr[]= {2, 3, 5, 7, 11};
• Method 3:
int n;
scanf(“%d”,&n);
int arr[n];
for(int i=0;i<5;i++)
{
scanf(“%d”,&arr[i]);
}
• Method 4:
int arr[5];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;

How Can You Access Elements of Arrays in Data Structures?

You can access elements with the help of the index at which you stored them. Let's discuss it with
a code:

#include<stdio.h>
int main()
{
int a[5] = {2, 3, 5, 7, 11};
printf(“%d\n”,a[0]); // we are accessing
printf(“%d\n”,a[1]);
printf(“%d\n”,a[2]);
printf(“%d\n”,a[3]);
printf(“%d”,a[4]);
return 0;
}

What Operations Can You Perform on an Array?


• Traversal
• Insertion
• Deletion
• Searching
• Sorting
Traversing the Array:

Traversal in an array is a process of visiting each element once.

Code:

#include<stdio.h>
int main() for (int i=0;i<n-1;i++)

{
int a[5] = {2, 3, 5, 7, 11};
for(int i=0;i<5;i++)
{
//traversing ith element in the array
printf(“%d\n”,a[i]);
}
return 0;
}

Insertion:
Insertion in an array is the process of including one or more elements in an array.
Insertion of an element can be done:
• At the beginning
• At the end and
• At any given index of an array.
At the Beginning:
Code:
#include<stdio.h>
int main()
{
int array[10], n,i, item;
printf("Enter the size of array: ");
scanf("%d", &n);
printf("\nEnter Elements in array: ");
for(i=0;i<n;i++)
{
scanf("%d", &array[i]);
}
printf("\n enter the element at the beginning");
scanf("%d", &item);
n++;
for(i=n; i>1; i--)
{
array[i-1]=array[i-2];
}
array[0]=item;
printf("resultant array element");
for(i=0;i<n;i++)
{
printf("\n%d", array[i]);
}
getch();
return 0;
}
At the End:
Code:
#include<stdio.h>
#include<conio.h>
int main()
{
int array[10], i, values;
printf("Enter 5 Array Elements: ");
for(i=0; i<5; i++)
scanf("%d", &array[i]);
printf("\nEnter Element to Insert: ");
scanf("%d", &values);
array[i] = values;
printf("\nThe New Array is:\n");
for(i=0; i<6; i++)
printf("%d ", array[i]);
getch();
return 0;
}
Lists
The arrangement of elements in some sequence is called list. There are two types of list.
i) Ordered List
ii) Unordered List

i) Ordered List storing elements in proper order


The proper sequence of elements is called ordered list. For example
The days of week, the month of year, seasons of year.
storing elements not in proper order
ii) Unordered List
In this type of list the storage of element is not take place in proper order.
For example, Stack, Queue, Dequeue, Circular Queue, Link List
the linear data structure in which elements can be
added and deleted from one end called as top
STACKS
A Stack is linear data structure. A stack is a list of elements in which an element may be
inserted or deleted only at one end, called the top of the stack. Stack principle is LIFO (last in,
first out). Which element inserted last on to the stack that element deleted first from the
stack.
As the items can be added or removed only from the top i.e. the last item to be added to a
stack is the first item to be removed.
Real life examples of stacks are:

Example
i) Pile of Trays in Cafeteria
ii) Stack of iron shorts (Box)
iii) Pile of bricks
iv) Pile of books in Library

Computer related Example


i) Expression, evolution in the stack process
ii) Calling functions/ Procedures and returned value stored in stack
iii) Conversion of decimal to binary is also a stack process.
Operations on stack:
The two basic operations associated with stacks are:
1. Push
2. Pop
While performing push and pop operations the following test must be conducted on the stack.
a) Stack is empty or not b) stack is full or not

1. Push: Push operation is used to add new elements into the stack. At the time of addition first
check the stack is full or not. If the stack is full it generates an error message "stack overflow".

2. Pop: Pop operation is used to delete elements from the stack. At the time of deletion first
check the stack is empty or not. If the stack is empty it generates an error message "stack
underflow".

All insertions and deletions take place at the same end, so the last element added to the stack
will be the first element removed from the stack. When a stack is created, the stack base remains
fixed while the stack top changes as elements are added and removed. The most accessible
element is the top and the least accessible element is the bottom of the stack.

Representation of Stack (or) Implementation of stack:


The stack should be represented in two ways:
1. Stack using array
2. Stack using linked list

1. Stack using array:

Let us consider a stack with 5 elements capacity. This is called as the size of the stack. The number
of elements to be added should not exceed the maximum size of the stack. If we attempt to add
new element beyond the maximum size, we will encounter a stack overflow condition. Similarly,
you cannot remove elements beyond the base of the stack. If such is the case, we will reach a
stack underflow condition.
1.push(): When an element is added to a stack, the operation is performed by push(). Below
Figure shows the creation of a stack and addition of elements using push().
Initially top=-1, increment the top value i.e top=top+1, and insert element into the stack. We can
insert an element into the stack first check the condition is stack isfull or not. i.e top>=size-1.
Otherwise add the element in to the stack.

ALGORITHM FOR THE INSERTION OF ELEMENT IN THE STACK (PUSH)


Algorithm push (stack, N, item, Top)
[ This algorithm is used to insert the element in the stack where Stack = Array, size-1 = Total
number of elements, x = which is to be inserted, top = Top pointer/ Counter ]

Step 1: START
Step 2: if top>=size-1 then
Write “ Stack is Overflow”
Goto Step-4
Step 3: Otherwise
3.1: read data value ‘x’
3.2: top=top+1;
3.3: stack[top]=x;
3.4: Goto Step-2
Step 4: END

CODE:
void push()
{
int x;
if(top >= n-1)
{
printf("\n\nStack Overflow..");
return;
}
else
{
printf("\n\nEnter data: ");
scanf("%d", &x);
top = top + 1;
stack[top] = x;
printf("\n\nData Pushed into the stack");
}
}

2.Pop(): When an element is taken off from the stack, the operation is performed by pop(). Below
figure shows a stack initially with three elements and shows the deletion of elements using pop().
We can delete/remove an element from the stack, decrement the top value i.e top=top-1.
We can delete element from the stack first check the condition is stack isempty or not. i.e top= -
1. Otherwise remove the element from the stack.

ALGORITHM FOR THE INSERTION OF ELEMENT IN THE STACK (POP)


Algorithm pop (stack, item, Top)
[This algorithm is used to delete an element from the stack where Stack = Array, top = Top
pointer/ Counter.]

Step 1: START
Step 2: if top==-1 then
Write “Stack is Underflow”
Goto Step-4
Step 3: otherwise
3.1: print “deleted element”
3.2: top=top-1;
3.3: Goto Step-2
Step 4: END

CODE:
Void pop()
{
If(top==-1)
{
Printf(“Stack is Underflow”);
}
else
{
printf(“Delete data %d”,stack[top]);
top=top-1;
}
}
3.display(): This operation performed display the elements in the stack. We display the element
in the stack check the condition is stack is empty or not i.e top==-1.Otherwise display the list of
elements in the stack.
Algorithms Display:
Step 1: START
Step 2: if top==-1 then
Write “Stack is Underflow”
Goto Step-4
Step 3: otherwise
3.1: print “Display elements are”
3.2: for top to 0
Print ‘stack[i]’
Step 4: END

CODE:
void display()
{
If(top==-1)
{
Printf(“Stack is Underflow”);
}
else
{
printf(“Display elements are:);
for(i=top;i>=0;i--)
printf(“%d”,stack[i]);
}
}

Source code for stack operations, using array:


_______________________________________________________
#include<stdio.h>
#inlcude<conio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
____________________________________________________________
int main()
{
//clrscr();
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
}
while(choice!=4);
return 0;
}
_______________________________________________________________
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
____________________________________________________________________
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
____________________________________________________________________
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}

Applications 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 and evaluating Algebraic expressions:

An algebraic expression is a legal combination of operators and operands. Operand is the


quantity on which a mathematical operation is performed. Operand may be a variable like x, y, z
or a constant like 5, 4, 6 etc. Operator is a symbol which signifies a mathematical or logical
operation between the operands. Examples of familiar operators include +, -, *, /, ^ etc.

An algebraic expression can be represented using three different notations. They are infix, postfix
and prefix notations:
Infix: It is the form of an arithmetic expression in which we fix (place) the arithmetic operator in
between the two operands.
Example: A + B
Prefix: It is the form of an arithmetic notation in which we fix (place) the arithmetic operator
before (pre) its two operands. The prefix notation is called as polish notation.
Example: + A B
Postfix: It is the form of an arithmetic expression in which we fix (place) the arithmetic operator
after (post) its two operands. The postfix notation is called as suffix notation and is also referred
to reverse polish notation.
Example: A B +
Conversion from infix to postfix:
Procedure to convert from infix expression to postfix expression is as follows:
1. Scan the infix expression from left to right.
2. a) If the scanned symbol is left parenthesis, push it onto the stack.
b) If the scanned symbol is an operand, then place directly in the postfix expression
(output).
c) If the symbol scanned is a right parenthesis, then go on popping all the items from the
stack and place them in the postfix expression till we get the matching left parenthesis.
d) If the scanned symbol is an operator, then go on removing all the operators from the
stack and place them in the postfix expression, if and only if the precedence of the
operator which is on the top of the stack is greater than (or greater than or equal) to the
precedence of the scanned operator and push the scanned operator onto the stack
otherwise, push the scanned operator onto the stack.
The three important features of postfix expression are:
1. The operands maintain the same order as in the equivalent infix expression.
2. The parentheses are not needed to designate the expression unambiguously.
3. While evaluating the postfix expression the priority of the operators is no longer relevant.

We consider five binary operations: +, -, *, / and $ or ↑ (exponentiation). For these binary operations,
the following in the order of precedence (highest to lowest):
Evaluation of postfix expression:
The postfix expression is evaluated easily by the use of a stack.
1. When a number is seen, it is pushed onto the stack;
2. When an operator is seen, the operator is applied to the two numbers that are popped from the
stack and the result is pushed onto the stack.
3. When an expression is given in postfix notation, there is no need to know any precedence rules;
this is our obvious advantage.

You might also like