Dsa Lab Manual Actual
Dsa Lab Manual Actual
ALGORITHMS
Lab 01
Programming with C++
Objective:
In this lab, students will get familiar with the C++ language, with the help of simple programs that will
provide handson training to learn the syntax of the language. Beside learning the basics of C++ like control
statements, functions, arrays, etc., you will also learn the concept of Array
Activity Outcomes:
Instructor Note:
As a pre-lab activity, read fundamental concepts from the text book “C++ How to Program,
Deitel, P. & Deitel, H., Prentice Hall, 2019”.”.
1) Useful Concepts
C++, as we all know is an extension to C language and was developed by Bjarne stroustrup at bell labs.
C++ is an intermediate level language, as it comprises a confirmation of both high level and low level
language features.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW
runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can
specify these tools on the command line by their simple names.
When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other
GNU tools from the Windows command line.
Activity 1:
Simple Program to print welcome on screen. It also uses Single Line, Multi Line comments and basic
Output in C++.
Solution:
// Our First Program
/* Multiple line
* comment
*/
#include<iostream>
int main()
{
cout<<"Welcome to CS211 DSA Lab";
return 0;
}
Output
Welcome to CS211 DSA Lab
Activity 2:
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
#include <iostream>
using namespace std;
int main () {
float a=5.5; // initial value: 5
int b(3); // initial value: 3
int c{2}; // initial value: 2
float result; // initial value undetermined
a = a + b;
result = a – c
cout << “Result is “<< result;
return 0;
}
Output
Result is 6.5
Activity 3:
Input values using cin statement.
#include <iostream>
using namespace std;
int main () {
int a, b, c, result; // multiple variable declaration
cout << ”Enter value for variable a ?” ;
cin >> a;
cout << ”Enter value for variable b ?” ;
cin >> b;
cout << ”Enter value for variable c ?” ;
cin >> c;
result = a + b + c ;
cout << “Result is “<< result;
return 0;
}
Output
Enter value for variable a ? 5
Result is 12
Activity 4:
Using Arithematic Operators
#include <iostream>
using namespace std;
int main () {
int a, b, c, result; // multiple variable declaration
a = 40;
b = 23;
c = 15;
result = (a - b + c) / 4 ;
cout << “Result is “<< result;
return 0;
}
Output
Result is 8
Activity 5:
𝒃𝟐 𝟒𝒂𝒄
Using Arithematic Operator; how do we write
𝟐𝒂
#include <iostream>
using namespace std;
int main () {
int a, b, c, result; // multiple variable declaration
a = 10;
b = 25;
c = 5;
result = (b*b – 4*a*c) / (2*a) ; // there is no power operator
cout << “Result is “<< result;
return 0;
}
Output
Result is 21.25
Activity 6:
Using Arithematic (increment / decrement) Operator;
#include <iostream>
using namespace std;
int main () {
int a, b, c, d;
a = 10;
b = 15;
c = a++;
d = ++a;
e = b--;
f = --b;
cout << “\n a is “<< a
<< “\n b is “<< b
<< “\n c is “<< c
<< “\n d is “<< d
<< “\n e is “<< e
<< “\n f is “<< f << endl;
return 0;
}
Output
a is 12
b is 13
c is 10
d is 12
e is 15
f is 13
Activity 7:
Using Conditional Operator;
#include <iostream>
using namespace std;
int main () {
int a, b, c;
a = 10;
b = 25;
c = (a>b) ? a : b;
cout << “Large number is “<< c;
return 0;
}
Output
Large number is 25
Activity 8:
Determining a number is even or odd using if statement;
#include <iostream>
using namespace std;
int main () {
int a;
cout << “Enter any integer “ ;
cin >> a;
if (a%2==0)
cout << a << “ is an even number”;
else
cout << a << “ is an odd number”;
return 0;
}
Output
Enter any integer 46
46 is an even number
Activity 9:
Write a program to compute need based scholarship for a student if GPA and parent’s income is
provided according to the following table.
Parents’s Income GPA 4.0 3.0 ~ 3.9 2.5 ~ 3.0 Below 2.5
Below Rs 100,000 FULL HALF QUARTER N/A
100,000 to 150,000 HALF QUARTER N/A N/A
150,000 to 200,000 QUARTER N/A N/A N/A
Above 200,000 N/A N/A N/A N/A
Note: Use nested if statement to find out scholarship type.
#include <iostream>
using namespace std;
int main() {
long income;
float gpa;
// Input income and gpa
cout << "Enter your parent\’s income: ";
cin >> income;
cout << "Enter your gpa : ";
cin >> gpa;
// Nested if statements to determine scholarship type
if (gpa == 4.0)
if (income <= 100000)
cout << "You qualified for full scholarship";
else if (income > 100000 && income <= 150000)
cout << "You qualified for half scholarship";
else if (income > 150000 && income <= 200000)
cout << "You qualified for half scholarship";
else
cout << "not qualified for any scholarship";
else if (gpa < 4.0 && gpa >= 3.0)
if (income <= 100000)
cout << "You qualified for half scholarship";
else if (income > 100000 && income <= 150000)
cout << "You qualified for quarter scholarship";
else
cout << "not qualified for any scholarship";
else if (gpa < 3.0 && gpa >= 2.5)
if (income <= 100000)
cout << "You qualified for quarter scholarship";
else
cout << "not qualified for any scholarship";
else
cout << "not qualified for any scholarship";
}
Activity 10:
Write a program to read in a value from 1 to 4, and use switch statement to check and displays
according to the following table.
Input Display
1 Hello
2 Goodbye
3 Welcome
4 Exit
#include <iostream>
using namespace std;
int main() {
int choice;
cout << "Menu:\n";
cout << "1. Print Hello\n";
cout << "2. Print Goodbye\n";
cout << "3. Print Welcome\n";
cout << "4. Exit\n";
cout << "Enter your choice (1-4): ";
cin >> choice;
switch (choice) {
case 1:
cout << "Hello!\n"; break;
case 2:
cout << "Goodbye!\n"; break;
case 3:
cout << "Welcome!\n"; break;
case 4:
cout << "Exiting program...\n"; break;
default:
cout << "Invalid choice. Please enter a number
between 1 and 4.\n"; break;
}
return 0;
}
Activity 11:
Write a program to sum first 10 numbers starting from 1, using for loop;
#include <iostream>
using namespace std;
int main() {
int sum = 0;
// For loop to sum numbers from 1 to 10
for (int i = 1; i <= 10; ++i) {
sum += i;
}
cout << "Sum of numbers from 1 to 10 is: " << sum << endl;
return 0;
}
Activity 12:
Using while loop statement, write a program to display the following sequence’s first 20 terms;
1, 5, 9, …
#include <iostream>
using namespace std;
int main() {
int t, a=1, d=4,c=1;
do {
cout << t <<”, “;
t = a + d*c;
c++;
} while (c<20)
return 0;
}
Activity 13:
Write a program that will add two numbers in a function and call that function in main.
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}
5) Graded Lab Tasks
Note: The instructor can design graded lab activities according to the level of difficulty and
complexity of the solved lab activities. The lab tasks assigned by the instructor should be
evaluated in the same lab.
Lab Task 1
Write a function that takes an integer and then returns the number with the digits reversed. For example,
if the input is 12345, the output should be 54321.
Lab Task 2
Write a function that takes two integers as input and returns the largest from these two input numbers.
…
…
…
}
Lab Task 3
Write a function which takes an integer argument value and displays the weekday corresponding to that
number. E.g. 1 for Monday, 2 for Tuesday,… 7 for Sunday, on any other number it should print wrong
input is provided.
Input: 3
Output: Wednesday
Lab Task 4
Use for loop to print this diamond shape.
*
**
***
****
*****
****
***
**
*
Lab Task 5
Marks of a student in five different subjects are given as following
[90,60,80,50,60]
Write a program to calculate average, and overall grade according to this criteria:
Marks Grade.
85% and above A
70% to 84% B
60% to 69% C
50% to 59% D
Below 50% F
Note: use user-defined functions,
Lab 2
Static List
Objective:
In this lab, students will learn how to create, manuplate and display one dimension arrays. How arrays can
be passed to functions and how arrays can be returned. They will also get familiarize with structures &
arrays of structures. Student will also do hands-on practice to make ArrayList using integer array and static
linked list.
Activity Outcomes:
Instructor Note:
As a pre-lab activity, read fundamental concepts from the text book “C++ How to Program,
Deitel, P. & Deitel, H., Prentice Hall, 2019”.”.
6) Useful Concepts
In C++, an array is a collection of elements of the same type placed in contiguous memory locations.
Arrays provide a way to store multiple values in a single variable, which can be accessed using indices.
Here’s a detailed overview of arrays in C++:
To declare an array, you specify the type of its elements and the number of elements it can hold. For
example:
If you don't specify the size, it is inferred from the number of initializers:
Accessing Elements:
Array elements are accessed using an index, with indices starting from 0. For example:
You can determine the size of an array using the `sizeof` operator. For example:
Characteristics of Arrays
1. Fixed Size:
The size of an array is fixed at compile time. This means once you declare an array, its size
cannot be changed during runtime.
2. Contiguous Memory:
Arrays allocate memory for all their elements in a contiguous block, which allows for efficient
access and iteration.
3. Zero-Based Indexing:
Array indices start at 0. For an array of size `n`, valid indices range from `0` to `n-1`.
4. Multidimensional Arrays:
C++ supports multidimensional arrays, such as two-dimensional arrays (matrices). For example:
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
// Initialization
Solution:
// Our First Program
/* Multiple line
* comment */
#include<iostream>
int main() {
int A[5]={3,4,6,7,8};
for (int i=0; i<5;i++)
cout<<A[i] << “,”;
return 0;
}
Output
3, 4, 6, 7, 8
Activity 2:
Write a function to display contents of an array.
#include <iostream>
using namespace std;
void display(int A[], int size) {
for (int i=0;i<size;i++) cout << A[i];
}
int main () {
int A[5]={3,4,6,7,8};
display(A,5);
return 0;
}
Output
3, 4, 6, 7, 8
Activity 3:
Write a function which will exchange two elements of an array.
#include <iostream>
using namespace std;
void swap(int A[], int i,int j) // A[i] A[j]
{
int t=A[i];
A[i]=A[j];
A[j]=t;
}
void display(int A[], int size) {
for (int i=0;i<size;i++) cout << A[i];
}
int main () {
int A[5]={3,4,6,7,8};
display(A,5);
swap(A,2,4);
display(A,5);
return 0;
}
Output
3, 4, 6, 7, 8
3, 4, 8, 7, 6
Activity 4:
Creating an arraylist using simple integer array, and write functions to insert and display elements.
#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
int A[MAX_SIZE];
int position=0; // where the first value be inserted
Output
3, 4, 6, 7, 8
Activity 5:
Write a function to delete an element from ArrayList.
#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
int position=0; // where the first value to be inserted
void insert(int A[], int value) {
if (position<MAX_SIZE)
A[position++] = value;
}
void remove(int A[], index i) // remove the value from i index
{
if (i<position) {
for (int j=i; j<position;j++)
A[j]=A[j+1];
position--;
}
}
Output
33, 44, 56, 78
Activity 6:
Suppose we have two ArrayLists let say A and B, how do we can create two lists using above code.
The answer is to create two arrays, two MAX_SIZE variables and two position variables, such as
In above example, we created an array to store values, a maximum variable which stores how many
values can be stored, and the third variable position to keep track of the position in array where next
value will be inserted.
To group these items together we need to use either classes or structures; As per our course
requirement we will use the structures to group things together.
To define composite types we use structures, one of the common examples of composite types is date,
where three integers make up a date structure;
#include <iostream>
using namespace std;
Output:
3, 5
6, 8
Activity 7:
In previous two activites we used remove function, which removes the content of ith position value
with the next (i+1)th value, and respectively all the value upto last element are shifted one step
backward.
This approach is considered slow – ie. If we remove first element from list we need to shift rest of the
list. To tackle this issue and to make list more effienct we can simple mark that element as any –ve
number so that can be considered as deleted.
#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
struct ArrayList
{
int Element[MAX_SIZE];
int position=0;
};
#include <iostream>
using namespace std;
const int MAX_SIZE = 10; // Maximum number of nodes in the
linked list
struct Node {
int data; // Data for the node
int next; // Index of the next node in the array
};
list[newNode].data = data;
list[newNode].next = -1; // Initially, it does not point
to any other node
if (size == 0) {
// Adding the first node
list[newNode].next = -1;
} else {
// Add at the end of the list
int current = 0;
while (list[current].next != -1) {
current = list[current].next;
}
list[current].next = newNode;
}
++size;
}
int main() {
initList();
addNode(10);
addNode(20);
addNode(30);
return 0;
}
Output
10 -> 20 -> 30 -> NULL
Lab Task 1
use a simple array to store the marks of 10 students from quiz 1 of data structure course, the obtained
marks are considered out of 15. Write function to compute average marks for the entire class.
Lab Task 2
Write a program using float ArrayList to store temperature of a week, and write functions to find week
maximum temprature.
Lab Task 3
By using the concept of static linked list, write functions for the following operations.
1) Insert a value at end of list
2) Remove First value from list
3) Remove last value from list
4) Display List in Reverse
5) Remove a value from a given index.
Lab 03
Dynamic Singly Linked List
Objective:
In this lab, students will learn how to use pointers, implement linked list, implement doubly linked list and
related algorithms such as insertion, deletion and traversals.
Activity Outcomes:
int a =10;
int *b = &a;
cout << b << *b
Activity 1:
Program to define a pointer and use in display the address and contents of an integer variable.
Solution:
#include<iostream>
Activity 2:
Use Structure to define a node of integer value.
A node strcuture
50
int data next
#include <iostream>
using namespace std;
int main () {
struct node { //definition of node structure
int data;
node* next;
};
node first; // a single variable of node type;
first.data=50;
first.next=NULL;
cout << “value stored in node is “<< first.data;
return 0;
}
Output
value stored in node is 50
Activity 3:
Creating two nodes and connecting together.
#include <iostream>
using namespace std;
int main () {
struct node { //definition of node structure
int data;
node* next;
};
node first, second; // a two variables of node type;
first.data=50;
second.data=60;
first.next=&second; //linked the first node to the second
cout << “value of first and second node “<< first.data
<< “, “ << first.next->data;
return 0;
}
Output
Value of first and second node 50, 60
Activity 4:
Create a linked list of three nodes, and traverse through a loop.
#include <iostream>
using namespace std;
struct node { //definition of node structure
int data;
node* next;
};
int main () {
node first, second, third;
first.data = 50; // set values of nodes
second.data = 60;
third.data = 70;
first.next = &second; // first node linked to second
second.next = &third; // similarly second node linked to third
third.next = NULL; // third node is not connected to any node
node *current=&first; // for purpose of loop we initialized
// loop variable current with first node
while (current!=NULL) {
cout << current->data ;
current = current->next;
}
return 0;
}
Output
Result is 50 60 70
Activity 5:
Create a function that add a new node at start of a linked list, and write a function to display the list.
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
Output
50 60 70
Activity 7:
Assume we have a list of values 50,60,70,80,90,100; we can get a value that is the first value in the list,
for this purpose we write a function getFirst that will return an integer from a given list.
Activity 8:
Write a function to get last value of a list;
NOTE: the following code is added to the Activitiy 6’s code.
Activity 9:
Write a function named exists that will search for a number in a list, and return true if it’s in the list.
bool exists(int n, node *head)
{
if (head==NULL)
return false; // in case list is empty
node *current = head;
while (current != NULL)
{
if (current->data == n)
return true;
current=current->next;
}
return false;
}
Activity 10:
Write a function named search that will find address of a node for a given number in a list.
Activity 13:
Write a function that will find a given value in list and then removes it from list.
Activity 14:
Write a function that will display a list using recursion.
Activity 15:
Write a function that will display a list in reverse order using recursion.
#include <iostream>
using namespace std;
struct node { //definition of node structure
int data;
node* next;
};
void insert_at_start(int v, node *head, node *tail);
void insert_at_end(int v, node *tail); // function prototype
void display(node *head); // this will display linked list
int main () {
node *head=NULL;// there is no node at the beginning
node *tail=NULL;
insert_at_end(50,head);
insert_at_end(60, head);
insert_at_start(70, head);
display(head);
return 0;
}
void insert_at_start(int v, node *head, node *tail)
{
node *newNode = new node;
newNode->data = v;
newNode->next = head;
head = newNode;
if (head->next==NULL) // if it’s the first node
tail = newNode; // or tail = head as well
}
void insert_at_end(int v, node *head, node *tail)
{
node *newNode = new node;
if (head = NULL) // list is empty
{ head = newNode;
tail = newNode;
}
else
{ tail->next= newNode;
tail = newNode;
}
}
Lab Task 2
Write a recursive function that finds sum of values of all nodes in a singly linked list.
Lab Task 3
If two lists are given, write a method which will merge two lists in to a new list.
e.g. list a = {1,3,7,5}
list b = {6,10,8,2,4}
c = union(a,b)
Lab Task 4
If two lists are given, and both contains integer values in ascending order, write a function which will
combine two lists, in a new list, while maintaining the order of values.
list b = {2,4,6,8,10}
list c = {1,2,3,4,5,6,7,8,10}
c = merge(a,b)
Lab Task 5
If a lists is given that contains integer values, write a function which will remove all prime numbers from
the list.
list b = {2,4,6,8,10}
list c = {1,2,3,4,5,6,7,8,10}
c = merge(a,b)