0% found this document useful (0 votes)
4 views38 pages

Ac Lab Manual Edit-1

The document outlines the lab record for M.Tech students in the Computer Science and Engineering department, detailing various experiments related to advanced computing. It includes practical work on Raspberry Pi, Arduino, Zigbee Protocol, data analytics using Apache Spark, and IoT architecture. Each experiment provides a description, objectives, and procedures for implementation, emphasizing hands-on learning in computing and programming.

Uploaded by

yaminimygapule
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views38 pages

Ac Lab Manual Edit-1

The document outlines the lab record for M.Tech students in the Computer Science and Engineering department, detailing various experiments related to advanced computing. It includes practical work on Raspberry Pi, Arduino, Zigbee Protocol, data analytics using Apache Spark, and IoT architecture. Each experiment provides a description, objectives, and procedures for implementation, emphasizing hands-on learning in computing and programming.

Uploaded by

yaminimygapule
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 38

DEPARTMENT OF

COMPUTER SCIENCE AND


ENGINEERING

ADVANCED COMPUTING
Lab record
M.Tech(I YEAR–I SEM) (2024-25)
CERTIFICATE

Department of:.......................................................................................................

Certified that this is the bonafide record of practical work done by

Mr./Miss.....................................................................Reg.No.................................Of

M.Tech......................Years………………………….Semester for Academic year

20……….to 20………. in the....................................................................Laboratory

Date: Staff Incharge HOD

Internal Examiner External Examiner


Page
S.No Name of the Experiment Date Signature
no
Start Raspberry Pi and try various Linux commands in
command terminal window: ls, cd, touch, mv, rm, man,
1
mkdir, rmdir, tar, gzip, cat, more, less, ps, sudo, cron,
chown, chgrp, ping etc
Study and Install IDE of Arduino and different types of
2 Arduino.

Study and Implement of Zigbee Protocol using


3
Arduino/Raspberry Pi
Write a map reduce program that mines weather data.
Weather sensors collecting data every hour at many
locations across the globe gather a large volume of log
4
data, which is a good candidate for analysis with Map
Reduce, since it is semi structured and record-oriented.

Data analytics using Apache Spark on Amazon food


dataset, find all the pairs of items frequently reviewed
together. Write a single Spark application that
 Transposes the original Amazon food
dataset, obtaining a PairRDD of the
type→ 
5  Counts the frequencies of all the pairs of
products reviewed together.
 Writes on the output folder all the pairs of
products that appear more than once and their
frequencies. The pairs of products must be
sorted by frequency.

Write a program to Implement Bankers algorithm for


6
Dead Lock Avoidance.
Write a program to Producer-consumer problem Using
7
semaphores.
Write a program of bit stuffing used by Data Link
8
Layer.
Write a program to configure a Network using Distance
9 Vector Routing protocol.

Write a program to perform the function oriented diagram:


10 DFD and Structured chart.

11 Write a program to draw the structural view diagram:


ii
Class diagram, object diagram.

Write C programs for implementing the Demorgan’s law


12

iii
Experiment 1: Start Raspberry Pi and try various Linux commands in
command terminal window: ls, cd, touch, mv, rm, man, mkdir, rmdir, tar,
gzip, cat, more, less, ps, sudo, cron, chown, chgrp, ping etc.
Raspberry Pi
The Raspberry Pi is a low cost,credit-card sized computer that plugs intp
a computer monitor or TV, and uses a standard keyboard and mouse.
It is a capable little device that enables people of all ages to explore
computing and to learn how to program in languages like Scratch and
Python made by the Raspberry Pi foundation a UK charity that aims to
educate people in computing and create easier access to computing
education.
Linux commands are a type of Unix command or shell procedure. They are the basic tools
used to interact with Linux on an individual level. Linux commands are used to perform a
variety of tasks, including displaying information about files and directories.
The commands are executed on the Linux terminal. The terminal is a command-line interface
to interact with the system, which is similar to the command prompt in the Windows
OS. Commands in Linux are case-sensitive.
ls Command: The ls command is used to display a list of content of a directory.
Syntax: ls
cd Command: The cd command is used to change the current directory.
Syntax: cd <directory name>
touch Command: The touch command is used to create empty files. We can create multiple
empty files by executing it once.
Syntax: touch <file name>
mv Command: The mv command is used to move a file or a directory form one location to
another location.
Syntax: mv <file name> <directory path>
rm Command: The rm command is used to remove a file.
Syntax: rm <file name>
man command: Accesses manual pages for all Linux commands.
Syntax: man<command name>
mkdir Command: The mkdir command is used to create a new directory under any
directory.
Syntax: mkdir <directory name>
rmdir Command: The rmdir command is used to delete a directory.
Syntax: rmdir <directory name>
tar command: Tar command is used to archive the files.
Syntax: Tar[option][archive-file][directory or file to be archieved]
gzip command: gzip command is used to compress the files
Syntax: gzip file.txt
cat command: The cat command is a multi-purpose utility in the Linux system. It can be
used to create a file, display content of the file, copy the content of one file to another file,
and more.
Syntax: cat [OPTION]... [FILE]..
more command: More command is used to View file contents page by page
Syntax: more largefile.txt
less command: less command is used to View file contents with navigation
Syntax: less largefile.txt
ps command: To display the current processes running
Syntax: ps
Sudo command: To run a command as root (administrator)
Syntax: sudo command
cron command: To edit the crontab (schedule tasks)
Syntax: crontab –e
chown command: To change the owner of a file
Syntax: sudo chown username:groupname file.txt
chgrp command: To change the group of a file
Syntax: sudo chgrp groupname file.txt
Ping command: To check if a host is reachable
Syntax: ping google.com
Experiment 2:
Aim: Study and Install IDE of Arduino and different types of Arduino.
Apparatus: Arduino UNO, USB cables, Power adapter.
Procedure: After learning about the main parts of the Arduino UNO board, we are ready to
learn how to set up the Arduino IDE. Once we learn this, we will be ready to upload our
program on the Arduino board.

Step 1 − First you must have your Arduino board (you can choose your favourite board) and
a USB cable. In case you use Arduino UNO, Arduino Duemilanove, Nano, Arduino Mega
2560, or Diecimila, you will need a standard USB cable (A plug to B plug), the kind you
would connect to a USB printer
In case you use Arduino Nano, you will need an A to Mini-B cable instead
Step 2 − Download Arduino IDE Software. You can get different versions of Arduino IDE
from the Download page on the Arduino Official website. Website. You must select your
software, which is compatible with your operating system (Windows, (Windows, IOS, or
Linux). After your file download is complete, unzip the file
Step 3 − Power up your board. The Arduino Uno, Mega, Duemilanove and Arduino Nano
automatically draw power from either, the USB connection to the computer or an external
power supply. If you are using an Arduino Diecimila, you have to make sure that the board is
configured to draw power from the USB connection. The power source is selected with a
jumper, a small piece of plastic that fits onto two of the three pins between the USB and
power jacks. Check that it is on the two pins closest to the USB port. Connect the Arduino
board to your computer using the USB cable. The green power LED (labelled (labelled PWR)
should glow.
Step 4 − Launch Arduino IDE. After your Arduino IDE software is downloaded,
downloaded, you need to unzip the folder. Inside the folder, you can find the application icon
with an infinity label (application.exe). Double-click the icon to start the IDE.

Step 5 − Open your first project. Once the software starts, you have two options − Create a
new project. Open an existing project example. To create a new project, select File → New.
Here, we are selecting just one of the examples with the name Blink. It turns the LED on and
off with some time delay. You can select any other example from the list.
Step 6 − Select your Arduino board. To avoid any error while uploading your program to the
board, you must select the correct Arduino board name, which matches with the board
connected to your computer. Go to Tools → Board and select your board.
Here, we have selected Arduino Uno board according to our tutorial, tutorial, but you must
select the name matching the board that you are using.
Step 7 − Select your serial port. Select the serial device of the Arduino board. Go to Tools →
Serial Port menu. This is likely to be COM3 or higher (COM1 and COM2 are usually
reserved for hardware serial ports). ports). To find out, you can disconnect your Arduino
board and re-open the menu, the entry that disappears should be of the Arduino board.
Reconnect the board and select that serial port.
Step 8 − Upload the program to your board. Before explaining how we can upload our
program to the board, we must demonstrate the function of each symbol appearing in the
Arduino IDE toolbar.
Now, simply click the "Upload" "Upload" button in the environment. Wait a few seconds;
seconds; you will see the RX and TX LEDs on the board, flashing. If the upload is successful,
successful, the message. "Done uploading" uploading" will appear in the status bar.
Architecture of Internet of Things (IoT)
Internet of Things (IoT) technology has a wide range of applications and the use of the
Internet of Things is growing so faster. Internet of Things (IoT) is the networking of physical
objects that contain electronics embedded within their architecture to communicate and sense
interactions amongst each other or to the external environment. In this article, we are going to
discuss the architecture of the Internet of Things.
The architecture of IoT is divided into 4 different layers i.e. Sensing Layer, Network Layer,
Data processing Layer, and Application Layer.

● Sensing Layer − The first stage of IoT includes sensors, devices, actuators etc. which
collect data from the physical environment, processes it and then sends it over the
network.
● Network Layer − The second stage of the IoT consists of Network Gateways and
Data Acquisition Systems. DAS converts the analogue data (collected from Sensors)
into Digital Data. It also performs malware detection and data management.
● Data Processing Layer − The third stage of IoT is the most important stage. Here,
data is pre-processed on its variety and separated accordingly. After this, it is sent to
Data Centres. Here Edge IT comes into use.
● Application Layer − The fourth stage of IoT consists of Cloud/Data Centres where
data is managed and used by applications like agriculture, defence, health care etc.
Types of Sensors in IoT
Sensors are used for sensing things and devices etc.
A device that provides a usable output in response to a specified measurement.
The sensor attains a physical parameter and converts it into a signal suitable for processing
(e.g. electrical, mechanical, optical) the characteristics of any device or material to detect the
presence of a particular physical quantity.

There are many types of sensors used in the Internet of Things (IoT), including:
● Temperature sensors
Measure the temperature of an object, surface, or environment, and convert it to an electrical
signal. They can be used to track the temperature of equipment to detect overheating.
● Humidity sensors
Measure the amount of water vapour in the air or other gases. They are often used in HVAC
systems, hospitals, and weather stations.
● Pressure sensors
Measure variations in pressure in gases and liquids, and send an alert when the pressure
reaches a certain threshold. They are used for leak detection, water systems, vehicles, and
aircraft.
● Water quality sensors
Monitor the quality of water, and are often used in water distribution systems.
● Chemical and gas sensors
Monitor air quality for the presence of toxic or hazardous gas. They are typically used in
industrial and manufacturing settings.
● Proximity sensors
Detect the presence or absence of objects in an environment. They use ultrasonic, infrared,
inductive, and capacitive means.
● Infrared sensors
Detect or emit infrared radiation to sense characteristics and changes in the surrounding area.
Experiment 3:
Aim: Implementation of Zigbee Protocol using Arduino/Raspberry Pi
Apparatus: Arduino/ Raspberry Pi, Zigbee Module, Connecting Wires, USB cable, Power
Adapter.
Description: ZigBee
ZigBee is a wireless technology which provides connection between the devices. It is the
only open global standard to fulfil the needs of low cost, low power wireless network used
for device monitoring and control. The ZigBee standard is based on IEEE 802.15.4. It
operates in ISM (Industrial, Scientific, and Medical) radio bands which include 2.4 GHz, 784
MHz, 868MHz and 915 MHz. Data rate varies from 20 Kb/s to 250 Kb/s. It supports all
network topologies such as star, tree and mesh topology. Its transmission distance is limited
to 10 to 100 meters line of sight. It depends on power output and environmental factors. It
can use long distance communication using intermediate devices. The data is passed through
the mesh network of intermediate devices and it reaches the distant devices. The devices are
secured by 128 bit symmetric encryption keys. So the networking is secure. ZigBee also
provides long battery life, so it can last for several years. It can be used in several
applications such as wireless light switches, smart grid, medical devices etc. It is simpler and
less expensive than Bluetooth, Wi-Fi etc. XBee and other XBee enabled devices provide
connection to several other devices.

Arduino
It is a simple microcontroller board. It is an open source computing platform and has an
environment for developing software for the Arduino board. It can be used to make
computers. It is used to create interactive projects. It takes input from sensors or switches and
controls the outputs. Arduino boards are inexpensive compared to other microcontroller
based devices. It can stand-alone or can communicate with the software of the
computer. Arduino software can run on Windows, Linux and Macintosh OSX. It provides an
Integrated Development Environment (IDE) which is written on Java for programming
microcontrollers. It supports C, C++ programming languages. So anyone who knows the
basic programming C can easily access Arduino IDE. It is very simple. Arduino has built-in
functions. It can access serial port. It does not need to access the register details. It can simply
call the functions and easily perform the functions. So the coding and debugging are fast and
efficient. Arduino IDE displays the data which is into and out of the serial port.

Interfacing ZigBee with Arduino


It is very easy to interface the ZigBee with Arduino. Before interfacing, the user must know
about the series. Series one is better for beginners. It can communicate with communication
devices, sensors etc. If two ZigBee modules are of same types, then they can communicate
with each other. To achieve communication between two ZigBee, first one ZigBee is
connected to Arduino and the other ZigBee is connected to sensor, microcontroller or
computer. There is no need of additional electronics to connect the ZigBee with Arduino.
After that, configuration is set on two modules. The below figure shows the interfacing of
ZigBee with Arduino. The supply voltage of module is regulated to 5V and 3.3V. The VCC
of ZigBee module is connected to 3.3V of Arduino and GND of ZigBee is connected to the
GND of Arduino. The figure shows that the transmitter and receiver pin of ZigBee is
connected to the transmitter and receiver pin of Arduino. Using Arduino board, the ZigBee
module can be connected with the microcontroller.
Configuration of ZigBee
To configure the ZigBee,

● First the ZigBee module must be connected to the computer using its serial adapter.
● For windows, puTTy or virtual terminal must be downloaded.
● The serial port of computer is set to 9600 baud rate, 8 data bits, 1 stop bit and no parity.
● Then click on the LOCAL ECHO BOX and click OK.
● The time session must be saved. Then click the CONNECT button of virtual terminal.
● After connection with ZigBee, the name of session is given.
● After these steps; the connection is occurred with the ZigBee module.
● To configure the ZigBee module, AT commands can also be used.

The procedures given above can be used to configure other ZigBee modules if required.
Connect the other ZigBee module with the serial port of the computer. Then repeat the
procedure above. After that; two ZigBee modules can communicate with each other.
Program:
Steps to Interface ZigBee with Arduino
Step 1:- Run the X-Ctu software to configure the ZigBee module.
Step 2:- The ZigBee modules can communicate via Arduino boards using the code. A simple
code for sending serial data is given below.
Step 3: Code

Serial.begin(9600); //baudrate is setup to 9600

Void loop() //The function operates repeatedly until the poweroff.

While(serial.available())

Serial.write(serial.read()); //Check whether data is available or not. If data is available, then


data is read.

The above code helps the ZigBee module to work according to the instructions sent by
Arduino. In the same way the ZigBee modules can receive instructions from other ZigBee
module also. For this case, the instructions or data is received from one ZigBee and this data
is sent through the serial pins of the Arduino. For that, one of the ZigBee must be connected
with the Arduino, and then the code which is given above is loaded to Arduino. After
uploading the code to the Arduino board, the Arduino board can be connected with the other
ZigBee module. After these all steps, the ZigBee modules can communicate with each other.
Experiment 4: Write a map reduce program that mines weather data. Weather sensors
collecting data every hour at many locations across the globe gather a large volume of log
data, which is a good candidate for analysis with Map Reduce, since it is semi structured and
record-oriented.
AIM:To implement mines the weather data using mapreduce
DESCRIPTION:
Sensors senses weather data in big text format containing station ID, year, date, time,
temperature, quality etc. from each sensor and store it in single line. Suppose thousands of
data sensors are their, then we have thousands of records with no particular order. We require
only year and maximum temperature of particular quality in that year.
For example:
Input string from sensor:
0029029070999991902010720004+64333+023450FM-12+
000599999V0202501N027819999999N0000001N9-00331+
99999098351ADDGF102991999999999999999999
Here: 1902 is year
0033 is temperature
1 is measurement quality (Range between 0 or 1 or 4 or 5 or 9)
Here each mapper takes input key as &quot;byte offset of line&quot; and value as &quot;one
weather sensor
Read i.e.one line&quot:. And parse each line and produce intermediate key is
&quot:year&quot: and intermediate value as &quot:temperature of certain measurement
qualities&quot: for that year.

PROGRAM
Driver code:
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
public class Weather {
public static void main(String[] args) {
JobConf conf=new JobConf();
Job job;
try {
job = new Job(conf,&quot;WeatherDataExtraction&quot;);
job.setJobName(&quot;WeatherDataExtraction&quot;);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job,new
Path(&quot;E:\\Nitin\\Programming\\DATA\\01001.dat\\01001.dat&quot;));
FileOutputFormat.setOutputPath(conf,new Path(&quot;E:\\Nitin\\output20.txt&quot;));
try {
job.waitForCompletion(true);
} catch (ClassNotFoundException | IOException | InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mapper Class:
Mapper Class
class MaxTemperatureMapper
extends Mapper {
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
String year = line.substring(15, 19);
intairTemperature;
if (line.charAt(87) == &#39;+&#39;) {
airTemperature = Integer.parseInt(line.substring(88, 92));
} else {
airTemperature = Integer.parseInt(line.substring(87, 92));
}
String quality = line.substring(92, 93);
if (quality.matches(&quot;[01459]&quot;)) {
context.write(new Text(year), new IntWritable(airTemperature));
}
}}
Reducer Class:
import java.io.IOException;
importorg.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class Reduce extends Reducer&lt;Text,IntWritable,Text,IntWritable&gt;{
public void reduce(Text key,Iterable&lt;IntWritable&gt; values,Context context) throws
IOException, InterruptedException
{
Integer max=new Integer(0);
for(IntWritable val:values) {
if (val.get()&gt;max.intValue()) { max=val.get();}
}
context.write(key,new IntWritable(max.intValue()));
}
}
OUT PUT:
1949 111
1955 22
Experiment 5: Data analytics using Apache Spark on Amazon food dataset, find all the pairs
of items frequently reviewed together. Write a single Spark application that
 Transposes the original Amazon food dataset, obtaining a
PairRDD of the type→ 
 Counts the frequencies of all the pairs of products reviewed together.
 Writes on the output folder all the pairs of products that appear more than once
and their frequencies. The pairs of products must be sorted by frequency.
Aim: Data analytics using Apache Spark on Amazon food dataset, find all the pairs of items
frequently reviewed together

To accomplish the task of finding pairs of items frequently reviewed together using Apache
Spark, you'll need to create a Spark application that:

1. Transposes the original Amazon food dataset: You will map the dataset to a
PairRDD of type <user_id> -> <list of product_ids reviewed by user_id>.
2. Counts the frequencies of pairs of products reviewed together: You will generate
all possible pairs of products from each user's review list, and count how often each
pair appears.
3. Writes the output of all pairs of products that appear more than once and their
frequencies: You will filter out pairs that appear only once and sort the pairs by
frequency.

Program:

#install java
!apt-get install openjdk-8-jdk –y
#set environment variables for Java and Spark
import os
os.environ[“JAVA_HOME”] = “/usr/lib/jvm/java-8-openjdk-amd64”

# Install Spark
!wget -q
http://apache.mirror.digitalpacific.com.au/spark/spark-3.3.2/spark-3.3.2-bin-hadoop3.2.tgz
!tar xvf spark-3.3.2-bin-hadoop3.2.tgz
!ls -1 /content/spark-3.3.2-bin-hadoop3.2

#Install findspark to connect Spark with Python


!pip install -q findspark
import findspark
findspark.init( )

# Import required libraries from PySpark


from pyspark.sql import SparkSession
from pyspark.sql.functions import col, collect_list
from itertools import combinations

#Initialize a Spark session


spark = SparkSession.builder.master
(“local[2]”.appName(“AmazonFoodDataset”).getOrCreate()
from google.colab import files
uploaded =files.upload( )

# Load the dataset (replace ‘your_dataset.csv’ with the actual filename)


df = spark.read.option(“header”, “true”).csv(‘amazon food dataset.csv’)

# Show the schema and some sample data


df.printSchema( )
df.show(5)

output:

# Group by user_id and collect the list of product_ids reviewed by each user
rdd = df.groupBy(“UserId”).agg(collect_list(“ProductId”).alias(“product_ids”)) .rdd

# Show the RDD sample


rdd.take(2)

output:
[Row(UserId='A104Y49ZQ4CYJ2', product_ids=['B0064KO0BU']),
Row(UserId='A108P30XVUFKXY', product_ids=['B001EO5QW8'])]

# Function to generate pairs of products from a list


def generate_pairs(product_list):
return combinations(sorted(product_list), 2)

# Create a PairRDD of (product_pair, 1) for each user


pairs_rdd = rdd.flatMap(lambda x: [(pair, 1) for pair in generate_pairs(x['product_ids'])])

# Count the occurrences of each product pair


pair_counts = pairs_rdd.reduceByKey(lambda a, b: a + b)

# Filter pairs that have a count greater than 1


filtered_pairs = pair_counts.filter(lambda x: x[1] > 1)

# Sort the pairs by frequency in descending order


sorted_pairs = filtered_pairs.sortBy(lambda x: x[1], ascending=False)

# Show top 10 pairs


sorted_pairs.take(10)
output:

[(('B000G6RYNE', 'B000G6RYNE'), 8)]


Experiment 6: Write a program to Implement Bankers algorithm for Dead Lock Avoidance.
AIM : Program for Dead Lock Avoidanceusing Bankers algorithm.
DESCRIPTION : The banker’s algorithm is a resource allocation and deadlock
avoidance algorithm that tests for safety by simulating the allocation for predetermined
maximum possible amounts of all resources, then makes an “s-state” check to test for
possible activities, before deciding whether allocation should be allowed to continue.
Program:
#include<stdio.h>
struct file
{
int all[10];
int max[10];
int need[10];
int flag;
};
void main()
{
struct file f[10];
int fl;
int i, j, k, p, b, n, r, g, cnt=0, id, newr;
int avail[10],seq[10];
printf("Enter number of processes -- ");
scanf("%d",&n);
printf("Enter number of resources -- ");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("Enter details for P%d",i);
printf("\nEnter allocation\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("Enter Max\t\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("\nEnter Available Resources\t -- \t");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
printf("\nEnter New Request Details -- ");
printf("\nEnter pid \t -- \t");
scanf("%d",&id);
printf("Enter Request for Resources \t -- \t");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i] += newr;
avail[i]=avail[i] - newr;
}
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
b=b+1;
else
b=b-1;
}
if(b==r)
{
printf("\nP%d is visited",j);
seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<r;k++)
printf("%3d",avail[k]);
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("\n REQUEST NOT GRANTED -- DEADLOCK OCCURRED");
printf("\n SYSTEM IS IN UNSAFE STATE");
goto y;
}
}
printf("\nSYSTEM IS IN SAFE STATE");
printf("\nThe Safe Sequence is -- (");
for(i=0;i<fl;i++)
printf("P%d ",seq[i]);
printf(")");
y: printf("\nProcess\t\tAllocation\t\tMax\t\t\tNeed\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
printf("%6d",f[i].all[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].max[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].need[j]);
printf("\n");
}

}
OUTPUT:
Experiment 7: Write a program to Producer-consumer problem Using semaphores.
AIM :Program to producer-consumer problem using semaphores.

DESCRIPTION :The producer-consumer problem is a synchronization problem .there is a


fixed sized buffer and the producer produces the items and enters them into the buffer.the
consumer removes the items from the buffer and consumes them.

PROGRAM :
#include<stdio.h>
#include<stdlib.h>
Int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1: if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full!!");
break;
case 2: if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}

return 0;
}
int wait(int s)
{
return (--s);
}

int signal(int s)
{
return(++s);
}

void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}

OUTPUT :
Experiment 8: Write a program of bit stuffing used by Data Link Layer.
AIM :Program of bit stuffing used by Data link layer.
DESCRIPTION :Bit stuffing is the insertion of one or more bits into a transmission unit as a
way to provide signaling information to a receiver. The receiver knows how to detect and
remove or disregard the stuffed bits.
PROGRAM :
#include<stdio.h>
#include<string.h>
void main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame size (Example: 8):");
scanf("%d",&n);
printf("Enter the frame in the form of 0 and 1 :");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
i=0;
count=1;
j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1; a[k]==1 && k<n && count<5; k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}
}
else
{
b[j]=a[i];
}
i++;
j++;
}
printf("After Bit Stuffing :");
for(i=0; i<j; i++)
printf("%d",b[i]);
}

OUTPUT
Experiment 9: Write a program to configure a Network using Distance Vector Routing
protocol.

AIM :Program to configure a Network using Distance vector routing Protocol.

DESCRIPTION :Each router maintains a Distance Vector table containing the distance
between itself and ALL possible destination nodes. Distances,based on a chosen metric, are
computed using information from the neighbors’ distance vectors.

PROGRAM :
#include<stdio.h>
struct node
{
Unsigne ddist[20];
Unsigned from[20];
}rt[10];
int main()
{
Int costmat[20][20];
Int nodes,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&nodes);//Enter the nodes
printf("\nEnter the cost matrix :\n");
for(i=0;i<nodes;i++)
{
for(j=0;j<nodes;j++)
{
scanf("%d",&costmat[i][j]);
costmat[i][i]=0;
rt[i].dist[j]=costmat[i][j];
rt[i].from[j]=j;
}
}
do
{
count=0;
for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<nodes;i++)
{
printf("\n\n For router %d\n",i+1);
for(j=0;j<nodes;j++)
{
printf("\t\nnode %d via %d Distance %d ",j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
}
OUTPUT :
Experiment 10: Write a program to perform the function oriented diagram: DFD and
Structured chart.

AIM:Program to perform the function oriented diagram: DFD and Structured Chart.
DESCRIPTION :A data flow diagram (DFD) is a graphical representation of the "flow" of
data through an information system modelling its process aspects. Often they are a
preliminary step used to create an overview of the system which can later be elaborated.
DIAGRAM :
STRUCTURED CHART :
A Structure Chart (SC) in software engineering and organizational theory is a chart which
shows the breakdown of a system to its lowest manageable levels.They are used in structured
programming to arrange program modules into a tree. Each module is represented by a box,
which contains the module's name. The tree structure visualizes the relationships between
modules.
Program:

class DataStore:

def __init__(self, name):

self.name = name

self.data = []

def add_data(self, data):

self.data.append(data)

print(f"Data added to {self.name}: {data}")

class Process:

def __init__(self, name, input_store, output_store):

self.name = name
self.input_store = input_store

self.output_store = output_store

def execute(self, data):

if data in self.input_store.data:

print(f"Processing {data} in {self.name}")

self.input_store.data.remove(data)

self.output_store.add_data(data)

else:

print(f"{data} not found in {self.input_store.name}")

class DataFlowDiagram:

def __init__(self):

self.data_stores = []

self.processes = []

def add_data_store(self, data_store):

self.data_stores.append(data_store)

def add_process(self, process):

self.processes.append(process)

def display(self):

print("Data Flow Diagram:")

for process in self.processes:

print(f"Process: {process.name}")

print(f"Input Store: {process.input_store.name}")

print(f"Output Store: {process.output_store.name}")

class StructuredChart:
def __init__(self):

self.modules = {}

def add_module(self, module_name, submodules):

self.modules[module_name] = submodules

def display(self):

print("Structured Chart:")

for module_name, submodules in self.modules.items():

print(f"Module: {module_name}")

print(f"Submodules: {', '.join(submodules)}")

def main():

# Create Data Stores

books = DataStore("Books")

issued_books = DataStore("Issued Books")

# Add some initial data

books.add_data("Book1")

books.add_data("Book2")

# Create Processes

issue_book_process = Process("Issue Book", books, issued_books)

# Create DFD

dfd = DataFlowDiagram()

dfd.add_data_store(books)

dfd.add_data_store(issued_books)

dfd.add_process(issue_book_process)

# Display DFD

dfd.display()

# Execute a process
issue_book_process.execute("Book1")

# Create Structured Chart

sc = StructuredChart()

sc.add_module("Library Management", ["Issue Book", "Return Book", "Add Book"])

# Display Structured Chart

sc.display()

if __name__ == "__main__":

main()

OUTPUT:
Experiment 11

Aim:Write a program to perform the system analysis: Requirement analysis, SRS.

Description: Creating a program for system analysis involves gathering and analyzing
requirements, then generating a Software Requirements Specification (SRS). Here's a simple
Python program to perform requirement analysis and generate an SRS:

Program Overview

The program will:

1. Collect requirements from the user.


2. Analyze the requirements based on priority.

3. Generate an SRS document.

Program:

class Requirement:

def __init__(self, req_id, description, priority, status):

self.req_id = req_id

self.description = description

self.priority = priority

self.status = status

def display(self):

print(f"ID: {self.req_id}, Description: {self.description}, Priority: {self.priority}, Status:


{self.status}")

class SRS:

def __init__(self, title, introduction):

self.title = title

self.introduction = introduction

self.requirements = []

def add_requirement(self, requirement):

self.requirements.append(requirement)
def display_srs(self):

print(f"Title: {self.title}")

print(f"Introduction: {self.introduction}")

print("\nRequirements:")

for req in self.requirements:

req.display()

def main():

# Sample SRS

srs = SRS("Sample Project SRS", "This document outlines the requirements for the Sample
Project.")

# Adding some requirements

srs.add_requirement(Requirement(1, "User authentication system", "High", "Pending"))

srs.add_requirement(Requirement(2, "Data encryption for sensitive information",


"Medium", "Pending"))

srs.add_requirement(Requirement(3, "User-friendly interface", "High", "Pending"))

srs.add_requirement(Requirement(4, "Detailed user activity logs", "Low", "Pending"))

# Display the SRS document

srs.display_srs()

if __name__ == "__main__":

main()

Output:
Experiment 12: Write C programs for implementing the Demorgan’s law.

AIM: C program for implementing the Demorgan’s Law.

Description :The compliment of the union of two sets is the intersection of their

complements and the complement of the intersection of two sets is the union of their

complements.

Program :

#include <stdio.h>

// Function to demonstrate De Morgan's Laws


void deMorganLaws() {
int A, B;

// Take input from the user


printf("Enter value for A (0 for false, 1 for true): ");
scanf("%d", &A);
printf("Enter value for B (0 for false, 1 for true): ");
scanf("%d", &B);

// First Law: NOT (A AND B) == (NOT A) OR (NOT B)


int left1 = !(A && B); // NOT (A AND B)
int right1 = (!A || !B); // (NOT A) OR (NOT B)

// Second Law: NOT (A OR B) == (NOT A) AND (NOT B)


int left2 = !(A || B); // NOT (A OR B)
int right2 = (!A && !B); // (NOT A) AND (NOT B)

// Display the results


printf("\nDe Morgan's Law Verification:\n");
printf("1. NOT (A AND B) == (NOT A) OR (NOT B): %s\n", (left1 == right1) ? "True" :
"False");
printf(" Calculated: %d == %d\n", left1, right1);

printf("2. NOT (A OR B) == (NOT A) AND (NOT B): %s\n", (left2 == right2) ? "True" :
"False");
printf(" Calculated: %d == %d\n", left2, right2);
}

int main() {
// Call the function to demonstrate De Morgan's Laws
deMorganLaws();
return 0;
}
OUTPUT :

You might also like