You are on page 1of 26

‫ﺟ ﺎ ﻣﻌ ﺔ ا ﻟﻤﻠ ﻚ ﺧ ﺎ ﻟﺪ‬

‫ﻛﻠﻴﺔ ﻋﻠﻮم اﻟﺤﺎﺳﺐ اﻵﻟﻲ‬


‫ﻗﺴﻢ ﻋﻠﻮم اﻟﺤﺎﺳﺐ اﻵﻟﻲ‬

King Khalid University


College of Computer Science
Department of Computer Sciences

LAB MANUAL

231CSM
Computer Modelling and Simulation
Academic Year 2021-22
Course Description (As per course Specification)

The course develops the student's understanding and abilities when using advanced
programming concepts and techniques in a wide variety of computer- science and real-
world problems, with the aim of achieving an efficient implementation for solving a
given problem. Thereby the course enhances the programming skills of the students.
Data Structures (Stacks, queues, Lists, Graph and trees), complexity analysis, recursive
algorithms, searching & sorting algorithms and Hashing are described as abstract data
types with their methods by training extensive examples and applications

Course Learning Outcomes (As per course Specification)

1. Describe the concepts of data structures and algorithms with its relevant types.
2. Describe the outline of linear and Non-linear structures and recognize the usage of
various algorithms.
3. Analyze, design and develop the algorithms for various data structures like Stacks,
Queues, and Linked List.
4. Compare and evaluate the complexity of algorithms for linear Data Structures
5. Demonstrate logical and technical skills required during application development.
6. Illustrate different ideas of applications in data structure and algorithms

Lab Description

The course allows the students to understand practically the Logical and physical
representation of arrays, lists, stacks, queues, sorting, searching, graphs and trees.
The algorithms that are discussed occur quite frequently in real applications, and
they can often arise as computational hot-spots where quite small amounts of
code limit the speed of a whole large program. Many applications call for slight
variations of adjustments of standard algorithms, and in other cases the selection
of a method to be used should depend on insight into patterns of use that will
arise in the program that is being designed.

Hardware / Software Requirements

Personal Computer or Laptop with high specifications

Java (JDK) + Editor (Jcreator, Ecllips or Netbeans)


Marks Distribution with assessment criteria (As per course Specification)

S. No Assessment Week Due Marks


1 Activities 1st-14th week 15

2 Assignment 15th week 5

3 Final exam
Total Marks 20

Instructions for assessment methods:


1.
2.

Week-wise Practical Schedule (15 weeks)

Week Lab/Exercise # Title of the Experiment / Exercise Page No.


Working with Arrays

1 1  The insertion process into arrays 6

 The deletion process from arrays

Working with Vectors


2 2  Important functions of Vector Collection: capacity, size, 9

ElementAt, firstElement, lastElement, addElement

Linked List

 Implementation of singly/doubly linked list

 Insert Node to the list (first, last and specific


3&4 3&4 12
location)

 Delete Node from the list (first, last and specific

location)
Demonstration of Stacks
5 5 16

 Array list implementation of Stack


6 Demonstration of Queue
6 20
 Array list implementation of Queue

Searching

7 7  Linear Search. 23
 Binary Search

Sort Algorithms – I

 Bubble Sort
8 8 26
 Selection Sort

 Insertion Sort

Recursion
Factorial
9 9 30
Fibonacci
 Binary Search (Recursive)

Sort Algorithms – II
10&11 10&11  Merge Sort 33
 Quick Sort

Binary Search Tree


Insertion
12&13 12&13 37
Search
 Traverse

14 14 Revision

15 15 Final Examination

References:
1. Adam Drozdek, Data Structures and Algorithms in Java, 4th edition, Cengage Learning Asia, 2013

2. Transactions on Algorithms: ACM Duane A Bailey, JAVA Structures, Williams College, September
2007
Michael S.Jenkins, Abstract Data types, McGRAW-HILL, 1998
Lab Session # 1 Week 1 #

Working with Arrays

 Objectives / Statement Purpose:


This lab will give you an overview of Array Concepts and Principles.
 Activity Outcomes:
This lab teaches you the following topics:

 The insertion process into arrays.

 The deletion process from arrays.

 Instructions for solving problems:


 Following the lab manual step by step
 Answering given questions concisely and precisely
 Practicing and implementing given examples correctly
 Writing code of required programming tasks
 Being focused, positive, interactive and serious during lab session
 Asking good questions or answering instructor questions if any
 Exercises (To be solved in Laboratory):

 Task 1
Write a java program for insertion and deletion for a single dimensional array.

Instructions
Insertion at the specified location in the array
To insert a value in an array at a desired position firstly we will have to shift all the elements forward to
accommodate the new element, and then we place the element at the required place.
Insertion Algorithm:
Step 1: Input the array elements, the position of the new element to be inserted and the new element.
Step 2: Insert the new element at that position and shift the rest of the elements to right by one position.
 Task 2
Deletion an element from an array
To delete an element from an array, we just have to find the element position then shift the position of
every element upward that are coming after the specified position
Deletion Algorithm:
Step one: Input the array elements, the position of the new element to be inserted and the new element.
Step two: Delete the element and shift the rest of the elements to left by one position.

 Activities:

Activity 1:

1. Write a java program that reads ten integers and displays them in the reverse of
the order in which they were read (0.5 mark).

Activity 2:

2. Write a java program that reads ten numbers, computes their average, and finds out
how many numbers are above the average (0.5 mark).
Lab Session # 2 (Week # 2)
Working with Vectors
Instructions

1.Vector
Vector implements a dynamic array. Vector proves to be very useful if you don't know the size of the
array in advance or you just need one that can change sizes over the lifetime of a program. The
Vector class is found in the java.util package.

2. Three ways to create vector class object:

Method 1:
Vector vec = new Vector();
It creates an empty Vector with the default initial capacity of 10. The Vector size would remain 10 till 10
insertions and once we try to insert the 11th element, it would become 20 (double of default capacity
10).

Method 2:
Syntax:
Vector object= new Vector(int initialCapacity); Vector vec = new Vector(3);
It will create a Vector of initial capacity of 3.

Method 3:
Syntax:
Vector object= new vector(int initialcapacity, capacityIncrement);
Vector vec= new Vector(4, 6);

Here we have provided two arguments. The initial capacity is 4 and capacity Increment is 6. It
means upon insertion of 5th element the size would be 10 (4+6) and on 11th insertion it would
be 16(10+6).

Exercises (To be solved in Laboratory):


 Task 1
Write a program to use a vector class in java for deletion, insertion, rotate left and rotate right.
 Task 2

Important methods of Vector Class:

void addElement(Object element): It inserts the element at the end of the Vector.
int capacity(): This method returns the current capacity of the vector.
int size(): It returns the current size of the vector.
Object elementAt(int index): It returns the element present at the specified location in
Vector.
Object firstElement(): It is used for getting the first element of the vector.
Object lastElement(): Returns the last element of the array.
Object get(int index): Returns the element at the specified index.
boolean isEmpty(): This method returns true if Vector doesn’t have any element.
boolean removeElement(Object element): Removes the specified element from vector.
boolean removeAll(Collection c): It Removes all those elements from vector which are present in the
Collection c.

 Activities:

Activity 1:

1.Write a java program to use a vector class that adds 5 names of students from
user input and then display them (0.5 mark).
Activity 2:

2. Write a java program that reads ten numbers, computes their average, and
finds out how many numbers are above the average using vector (0.5 mark).
Lab Session # 3&4 (Week # 3&4)
Singly/Doubly Linked List

 Objectives / Statement Purpose:


This lab will give you practice with Singly/Doubly linked lists.
 Activity Outcomes:
This lab teaches you the following topics:

 Singly/Doubly Linked List


 Implementation of singly/doubly linked list using java
 Insert Node to the list (first, last and specific location)
 Delete Node from the list (first, last and specific location)

Instructions for solving problems:


 Following the lab manual step by step
 Answering given questions concisely and precisely
 Practicing and implementing given examples correctly
 Writing code of required programming tasks
 Being focused, positive, interactive and serious during lab session
 Asking good questions or answering instructor questions if any
Note: performing given home activities or extra programming is highly recommended toimprove
your understanding, capability and programming skills.

 Exercises (To be solved in Laboratory):

 Task 1

Write a class for a singly/doubly linked list with the following methods:
-Insertion from head, tail and middle
-Deletion from head, tail and middle
 Singly Linked List
1. A singly linked list is a concrete data structure consisting of asequence of nodes
It has a head (or first) node pointer indicating the first node in list
It could have optionally a tail pointer node indication the last node inlist
2. Each node stores
 Element (data)
 Link to the node
3.The null object (at the end) is denoted as ∅.

 Doubly Linked Lists


1.The doubly linked list allows us to go in both directions in a linked list:
Forward
Reverse
2.Such lists allow for
 A variety of quick update operations, including insertion and removalat both ends, and in
the middle.
3. A node in a doubly linked list stores two references
 A next link, which points to the next node in the list.
 Aprev link, which points to the previous node in the list.

 Task 2

 Insertion Algorithms
1. Insert at the beginning
Step 1 - Allocate memory for new node
Step 2 - Store data
Step 3 - Change next of new node to point to head
Step 4 - Change head to point to recently created node
1. Insert at the End
Step 1 - Allocate memory for new node
Step 2 - Store data
Step 3 - Traverse to last node
Step 4 - Change next of last node to recently created node
2. Insert at the Middle
Step 1 - Allocate memory and store data for new node
Step 2 - Traverse to node just before the required position of newnode
Step 3 - Change next pointers to include new node in between

 Task 3

 Deletion Algorithms
1. Delete from beginning
Step 1 - Point head to the second node
2. Delete from end
Step 1 - Traverse to second last element
Step 2 - Change its next pointer to null
3. Delete from middle
Step 1 - Traverse to element before the element to be deleted
Step 2 - Change next pointers to exclude the node from the chain

 Activities:

Activity 1:

1.Write a java program using java.util package to add these elements to linked list {KKU, KSU,
KAU, NU} then add “KAUST” to index 2 and remove the KKU element (0.5 mark).

Activity 2:

2. Write a java program that reads ten numbers into a linked list, computes their average, and finds out how
many numbers are above the average (0.5 mark).
Lab Session # 5 (Week # 5)

5
Stacks

 Objectives / Statement Purpose:


This lab will give you practice with implementation of stacks.
 Activity Outcomes:
This lab teaches you the following topics:
 Implementation of stack using Array.
 Instructions for solving problems:
 Following the lab manual step by step
 Answering given questions concisely and precisely
 Practicing and implementing given examples correctly
 Writing code of required programming tasks
 Being focused, positive, interactive and serious during lab session
 Asking good questions or answering instructor questions if any

 Exercises (To be solved in Laboratory):


 Task 1

Write a class for generic data type stack with following methods
 Push - Inserting an element on the stack
 Pop - Removing an element from the stack
 Full - check if stack is full
 Empty - check if stack is empty
 Stack Representation
The following diagram depicts a stack and its operations:

 Push Operation
The process of putting a new data element onto stack is known as a PushOperation. Push operation
involves a series of steps:
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next emptyspace.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.
 Pop Operation
Accessing the content while removing it from the stack, is known as a Pop Operation. In an
implementation of pop() operation, the data element is not actually removed, instead top is decremented
lower position in the stack to point to the next value. But in linked-list implementation, pop()actually rem
data element and deallocates memory space. A Pop operation may involve the following steps:

Step 1 − Checks if the stack is empty.


Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element atwhich top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.

 Activities:

Activity 1:

1.Write a simple java code by using java.util.Stack that Push 3 elements then print it. Then pop all element
on the stack after that print it again? (0.5 mark).

Activity 2:

2. Write a java program to reverse a word using stack operation. Eg. HELP --> PLEH
(0.5 mark).
Lab Session # 6 (Week # 6)

6
Queues

 Objectives / Statement Purpose:


This lab will give you practice with implementation of queues.
 Activity Outcomes:
This lab teaches you the following topics:
 Implementation of queue using Array.
 Instructions for solving problems:
 Following the lab manual step by step
 Answering given questions concisely and precisely
 Practicing and implementing given examples correctly
 Writing code of required programming tasks
 Being focused, positive, interactive and serious during lab session
 Asking good questions or answering instructor questions if any

 Exercises (To be solved in Laboratory):


 Task 1

Write a class for generic data type queue with following methods
 Enqueue - add an item to the queue
 Dequeue - remove an item from the queue
 Full - check if queue is full
 Empty - check if queue is empty

 Queue Representation
As we now understand that in queue, we access both ends for different reasons. The following diagram g
below tries to explain queue representation as data structure:
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively diff
implement than that of stacks. The following steps should be taken to enqueue (insert) data into a queue:

Step 1 − Check if the queue is full.


Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the nextempty
space.
Step 4 − Add data element to the queue location, where the rear ispointing.
Step 5 − return success.

Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing
remove the data after access. The following steps are taken to perform dequeue operation:

Step 1 − Check if the queue is empty.


Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front ispointing.
Step 4 − Increment front pointer to point to the next available dataelement.
Step 5 − Return success.
 Activities:

Activity 1:

Write a Java program to add all the elements of a priority queue to another priority queue (0.5 mark)

Activity 2:

Write a Java program to remove all the elements from a priority queue (0.5 mark)
Lab Session # 7 (Week # 7)

7
Linear & Binary Search

 Objectives / Statement Purpose:


This lab will give you practice with implementation of Linear & Binary Search.
 Activity Outcomes:
This lab teaches you the following topics:
 Implementation of Linear Search using Array.
 Implementation of Binary Search using Array.
 Instructions for solving problems:
 Following the lab manual step by step
 Answering given questions concisely and precisely
 Practicing and implementing given examples correctly
 Writing code of required programming tasks
 Being focused, positive, interactive and serious during lab session
 Asking good questions or answering instructor questions if any

 Exercises (To be solved in Laboratory):
 Task 1

Write a java class to implement the following methods:


 Sequential (Linear) Search
 Binary Search
Sequential (Linear) Search
Linear search is a very simple search algorithm. In this type of search, a sequential search is
made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.
Algorithm
Step 1 - Start from the leftmost element of arr[] and one by onecompare x
with each element of arr[].
Step 2 - If x matches with an element, return the index.
Step 3 - If x doesn’t match with any of elements, return -1.

 Task 2

Binary Search
Binary Searching involves searching for an element in an array, where the items are arranged in
ascending or descending order. That means the entries in the array are sorted. If you want to
learn how to write a function that does this, keep reading.

Algorithm
Step 1 - We are given an input array that is supposed to be sorted inascending
order.
Step 2 - We take two variables which will act as a pointer i.e, beg,and end.
Step 3 - Beg will be assigned with 0 and the end will be assigned tothe last
index of the array.
Step 4 - Now we will introduce another variable mid which will markthe middle of
the current array. That will be computed as (low+high)/2.
Step 5 - If the element present at the mid index is equal to the elementto be
searched, then just return the mid index.
Step 6 - If the element to be searched is smaller than the element present at
the mid index, move end to mid-1, and all RHS will getdiscarded.
Step 7 - If the element to be searched is greater than the element present at
the mid index, move beg to mid+1, and all LHS will getdiscarded.
 Activities:

Activity 1:

Write a Java program to find a specified element in a given array of elements using Linear Search. (0.5
mark)

Lab Session # 8 (Week # 8)


Sorting Algorithms – Part I
 Objectives / Statement Purpose:
This lab will give you practice with implementation of sorting techniques.
 Activity Outcomes:
This lab teaches you the following topics:
 Implementation of Bubble Sort
 Implementation of Selection Sort
 Implementation of Insertion Sort
 Instructions for solving problems:
 Following the lab manual step by step
 Answering given questions concisely and precisely
 Practicing and implementing given examples correctly
 Writing code of required programming tasks
 Being focused, positive, interactive and serious during lab session
 Asking good questions or answering instructor questions if any

 Exercises (To be solved in Laboratory):


 Task 1

Write a java class to implement the following methods:


 Bubble Sort
 Selection Sort
 Insertion Sort

 Bubble Sort
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-b
algorithm in which each pair of adjacent elements is compared and the elements
swapped if they are not in order.
Algorithm
Step 1 - Repeatedly compare the elements at consecutive locations in agiven list, and do th
following until the elements are in required order
Step 2 - If elements are not in the required order, swap them (changetheir
position)
Step 3 - Otherwise do nothing

 Task 2

 Selection Sort
This sorting algorithm is an in-place comparison-based algorithm in which the list is divided
two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the s
part is empty and the unsorted part is the entire list. The smallest element is selected from
unsorted array and swapped with the leftmost element, and that element becomes a part of
sorted array. This process continues moving unsortedarray boundary by one element to the

Algorithm
Step 1 - Suppose we want to sort an array in ascending order.
Step 2 - Locate the smallest element in the array; swap it with elementat index 0
Step 3 - Then, locate the next smallest element in the array; swap it withelement at index 1.
Step 4 - Continue until all elements are arranged in order
 Insertion Sort
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorte
example, the lower part of an array is maintained to be sorted. An element which is to be inserted in this
sub-list, has to find its appropriate place and then it has to be inserted there.Hence the name, insertion sort

Algorithm
Step 1 - If it is the first element, it is already sorted. return 1;
Step 2 - Pick next element
Step 3 - Compare with all elements in the sorted sub-list
Step 4 - Shift all the elements in the sorted sub-list that is greater thanthe
value to be sorted
 Step 5 - Insert the value
 Step 6 - Repeat until list is sorted
 Activities:

Activity 1:

Write a Java program to sort an array of given integers using the Bubble sorting Algorithm (0.5 mark).

Activity 2:

Write a Java program to sort an array of given integers using Insertion sort Algorithm (0.5 mark).

Activity 3:

write a Java program to sort an array of given integers using Selection Sort Algorithm (0.5 mark).

Lab Session # 9 (Week # 9)

9
Recursion

 Objectives / Statement Purpose:


This lab will give you practice with recursion.
 Activity Outcomes:
This lab teaches you the following topics:
 Simple problem solved by recursion:
o Factorial function
o Fibonacci series
o Binary Search (Recursive)
 Instructions for solving problems:
 Following the lab manual step by step
 Answering given questions concisely and precisely
 Practicing and implementing given examples correctly
 Writing code of required programming tasks
 Being focused, positive, interactive and serious during lab session
 Asking good questions or answering instructor questions if any

 Exercises (To be solved in Laboratory):


 Task 1
Write a java class to implement the following methods:

 Factorial function
 Fibonacci series
 Binary Search (Recursive)
Factorial Function
You have probably seen the factorial function before. It is defined for allintegers greater or equal to ze
Often factorial(N) is written as N! factorial( 0 ) = 1 // Base Case
factorial( N ) = N * factorial( N-1 ) // Recursive Case

For example,
factorial( 5 ) = 5 * factorial( 4 )
= 5 * ( 4 * factorial( 3 ) )
= 5 * ( 4 * (3 * factorial( 2 ) ) )
= 5 * ( 4 * (3 * (2 * factorial( 1 ) ) ) )
= 5 * ( 4 * (3 * (2 * ( 1 * factorial( 0 ) ) ) ) )
= 5 * ( 4 * (3 * (2 * ( 1 * 1 ) ) ) )
= 5 * 4 * 3 * 2 * 1 * 1 = 120
 Fibonacci series
Fibonacci series are the numbers in the following integer sequence:
By definition, the first two numbers in the Fibonacci sequence are 0 and 1,and each
subsequent number is the sum of the previous two.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined bythe recurrence
relation

with seed values

 Activities:

Activity 1:

1.Write a java program to compute the greatest common divisor of two integers, where it
can be written recursively by: (0.5 mark).
Activity 2:

You might also like