You are on page 1of 40

1.

Write a PHP program to display “Hello World” and “Welcome to PHP World”
Message on Screen using echo and print statements.
Practical-1.php
<html>
<head>
<title>Practical-1</title>
</head>
<?php
echo "<b>Hello</b> <i>World</i>"."<br>";
Print "Welcome to PHP World";
?>
<body>
</body>
</html>
Output:
Hello World
Note: The echo() function outputs one or more strings.
Note: The echo() function is not actually a function, so you are not required to use
parentheses with it. However, if you want to pass more than one parameter to echo(), using
parentheses will generate a parse error.
Tip: The echo() function is slightly faster than print().
2. Write a PHP program to display the today’s date and current time.
Practical-2.php
<?php
print strftime('%c');
echo "<br />";
print strftime('%d/%m/%Y');
echo "<br />";
print strftime('%A, %d %B - %Y');
echo "<br />";
echo "<b>Current Day, Date and Time is:</b> " . date("D M d, Y G:iA");
date_default_timezone_set('Asia/Kolkata')."<br />";
$currentTime = date( 'd-m-Y h:i:s A', time () )."<br />";
echo "Asia Time is ".$currentTime."<br />";
date_default_timezone_set('America/New_York')."<br />";
$currentTime = date( 'd-m-Y h:i:s A', time () )."<br />";
echo "America/New_York Time is ".$currentTime;
?>

Output:
Tue Jun 8 16:25:30 2021
08/06/2021
Tuesday, 08 June - 2021
Current Day, Date and Time is: Tue Jun 08, 2021 16:25PM
Asia Time is 08-06-2021 07:55:30 PM
America/New_York Time is 08-06-2021 10:25:30 AM
Note: date_default_timezone_set() this function is used to set the time zone of your own
Note: The strftime() function formats a local time and/or date according to locale settings.
Syntax: strftime(format, timestamp)
Parameter Values
Parameter Description
format Required. Specifies how to return the result:
 %a - abbreviated weekday name
 %A - full weekday name
 %b - abbreviated month name
 %B - full month name
 %c - preferred date and time representation
 %C - century number (the year divided by 100, range 00 to 99)
 %d - day of the month (01 to 31)
 %e - day of the month (1 to 31)
 %g - like %G, but without the century
 %G - 4-digit year corresponding to the ISO week number (see %V).
 %H - hour, using a 24-hour clock (00 to 23)
 %I - hour, using a 12-hour clock (01 to 12)
 %j - day of the year (001 to 366)
 %m - month (01 to 12)
 %M - minute
 %n - newline character
 %p - either am or pm according to the given time value
 %r - time in a.m. and p.m. notation
 %R - time in 24 hour notation
 %S - second
 %t - tab character
 %T - current time, equal to %H:%M:%S
 %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
 %U - week number of the current year, starting with the first Sunday as the first day of the first week
 %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week
that has at least 4 days in the current year, and with Monday as the first day of the week
 %W - week number of the current year, starting with the first Monday as the first day of the first week
 %w - day of the week as a decimal, Sunday=0
 %x - preferred date representation without the time
 %X - preferred time representation without the date
 %y - year without a century (range 00 to 99)
 %Y - year including the century
 %Z or %z - time zone or name or abbreviation
 %% - a literal % character
timestamp Optional. Specifies a Unix timestamp that represents the date and/or time to be formatted.
Default is the current local time (time())
Write a PHP program to calculate sum of given number using function.
Practical-3.php
<?php
$val1=10;
$val2=10;
function sum($val1,$val2)
{
$total=$val1+$val2;
return $total;
}
echo "<b>Sum using Function : </b>" . sum($val1,$val2)."<br>";
echo "<b>Sum using without Function : </b>" ;
$sum=$val1 + $val2;
echo "<br />";
echo "<b>Sum is :</b> $sum";
?>
Output:
Sum using Function : 20
Sum using without Function :
Sum is : 20
Note:
Function:
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
• Information can be passed to functions through arguments. An argument is just like a
variable.
• Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
• PHP Functions returning value. A function can return a value using the return statement in
conjunction with a value or object. Return stops the execution of the function and sends the
value back to the calling code
$_REQUEST: $_REQUEST is a super global variable which is widely used to collect data
after
submitting html forms
4. Write a PHP Program that will use the concept form
What is Form?
• When you login into a website or into your mail box, you are interacting with a form.
• Forms are used to get input from the user and submit it to the web server for processing.
The diagram below illustrates the form handling process.

A form is an HTML tag that contains graphical user interface items such as input box, check
boxes radio buttons etc.
The form is defined using the <form>...</form> tags and GUI items are defined using form
elements such as input.

GET vs POST Methods


POST GET
Values not visible in the URL Values visible in the URL
Has limitation on the length of the values
Has not limitation of the length of the usually 255 characters. This is because the
values since they are submitted via the values are displayed in the URL. Note the
body of HTTP upper limit of the characters is dependent on
the browser.
Has lower performance compared to
Has high performance compared to POST
Php_GET method due to time spent
method dues to the simple nature of appending
encapsulation the Php_POST values in the
the values in the URL.
HTTP body
Supports many different data types such as Supports only string data types because the
string, numeric, binary etc. values are displayed in the URL
Results can be book marked due to the
Results cannot be book marked
visibility of the values in the URL
4. Write a PHP Program that will use the concept form.
Practical-4.php
<html>
<head>
<title>LAB-4 Form Concept</title>
</head>
<body>
<form name="frmdemo" action="lab4a.php" method="post" >
<fieldset>
<legend>Enter Your Details</legend>
<table width="250px" border="2" align="center">
<tr>
<td align="right">Name</td>
<td><input type="text" name="txtname"></td>
</tr>
<tr>
<td align="right">Contact No</td>
<td><input type="text" name="txtcno"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="Submit">
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
OUTPUT:

lab4a.php
<?php
if(isset($_REQUEST['submit']))
{
$name=$_REQUEST['txtname'];
$cno=$_REQUEST['txtcno'];
echo "<b>Your Name is: </b>" . $name . "<br>";
echo "<b>Contact No: </b>" . $cno;
}
else
{
echo "Go Back and Press Submit button";
}
?>
OUTPUT:
Your Name is: sampath
Contact No: 9989003313
Write a PHP program to prepare student Mark sheet using Switch
statement.
LAB-5.php
<html>
<head>
<title>LAB-5 Marksheet</title>
</head>
<body>
<form name="frmdemo" action=" lab5a.php" method="post" >
<fieldset>
<legend align="center">Enter Your Name with Marks
Detail</legend>
<table width="250px" border="2" align="center">
<tr>
<td align="right">Name</td>
<td><input type="text" name="txtname"></td>
</tr>
<tr>
<td align="right">Subject-1</td>
<td><input type="text" name="txtsub1"></td>
</tr>
<tr>
<td align="right">Subject-2</td>
<td><input type="text" name="txtsub2"></td>
</tr>
<tr>
<td align="right">Subject-3</td>
<td><input type="text" name="txtsub3"></td>
</tr>
<tr>
<td align="right">Subject-4</td>
<td><input type="text" name="txtsub4"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Output:

lab5a.php
<?php
if(isset($_REQUEST['submit']))
{
$name=$_REQUEST['txtname'];
$sub1=$_REQUEST['txtsub1'];
$sub2=$_REQUEST['txtsub2'];
$sub3=$_REQUEST['txtsub3'];
$sub4=$_REQUEST['txtsub4'];
echo "<b>Your Name is: </b>" . $name . "<br>";
echo "<b>Your Marks Detail: </b> <br>";
echo "Subject-1: " . $sub1 . "<br>";
echo "Subject-2: " .$sub2 . "<br>";
echo "Subject-3: " . $sub3 . "<br>";
echo "Subject-4: " . $sub4 . "<br>";
$total=$sub1+$sub2+$sub3+$sub4;
echo "Total Marks: " .$total . "<br>";
$per=$total/4;
echo "Percentage: " . $per . "%<br>";
switch($per)
{
case $per<35:
echo "Grade: F" . "<br>";
break;
case $per>=35 && $per<=50: echo
"Grade: D" .
"<br>"; break;
case $per>50 && $per<=60:
echo "Grade: C" . "<br>";
break;
case $per>60 && $per<=70:
echo "Grade: B" . "<br>";
break;
case $per>70 && $per<100:
echo "Grade: A" . "<br>";
break;
default:
echo "Invalid.... or out of limit";
break;
}
}
else
{
echo "Go Back and Press Submit button";
}
?>
output:
Your Name is: sampath kumar
Your Marks Detail:
Subject-1: 95
Subject-2: 90
Subject-3: 78
Subject-4: 85
Total Marks: 348
Percentage: 87%
Grade: A
Write a PHP program to generate the multiplication of matrix.
Practical-6.php
<?php
$p = array();
$p[] = array(3,3,3);
$p[] = array(3,3,3);
$p[] = array(3,3,3);
$q = array();
$q[] = array(3,3,3);
$q[] = array(3,3,3);
$q[] = array(3,3,3);
echo "Matrix 1 is <br/>";
echomatrix(3, $p); //fn call for display enterd matrix
echo "<br/>";
echo "Matrix 2 is <br/>";
echomatrix(3, $q); //fn call for display enterd matrix
echo "<br/>";
$r = matrixMultiply(3, $p, $q); //fn call for matrix multiplication
echo "Result of Matrix Multiplication is <br/>";
echomatrix(3, $r);
function echoMatrix($N, $r) //fn for display enterd matrix
{
for($i=0; $i<$N; $i++)
{
for($j=0; $j<=$N; $j++)
{
if ($j==$N)
{
echo "<br>";
}
else
{
echo $r[$i][$j];
}
if ($j<($N-1))
{
echo " ";
}
}
}
}
function matrixMultiply($N, $p, $q) //fn for matrix multiplication
{
$r = array();
for($i=0; $i<$N; $i++)
{
$t = array();
for($j=0; $j<$N; $j++)
{
$t[] = 0;
}
$r[] = $t;
}
for($i=0; $i<$N; $i++)
{
for($j=0; $j<$N; $j++)
{
$t = 0;
for($k=0; $k<$N; $k++)
{
$t += $p[$i][$k] * $q[$k][$j];
}
$r[$i][$j] = $t;
}
}
return $r;
}
?>
Output:
Matrix 1 is
333
333
333

Matrix 2 is
333
333
333

Result of Matrix Multiplication is


27 27 27
27 27 27
27 27 27
7. Write a PHP application to add new Rows in a Table.
1. Open Xampp control panel (StartAll ProgramsXampp control panel).
2. After opening Xampp control panel, select Start button behind the Apache and Start button
behind the MYSQL.
3. Select Admin button as shown in fig.

4. Click on User Accounts tab. Click on Add User Account button

Click on user
accounts tab

Click on
add user
account
Password as srdc@1234
After typing user name password host name click on go button in the bottom corner of
the page.

Click on databases
tab
You get this page give database name as “srdc” and type as “collation” click on create

After click on create database you get above screen


Create table name as “srdcstudent” with 6 columns as shown below
8. Give the filled name and its values as follows

9. After typing the information, select save button.


Now minimize and then type the program in notepad and save it as
srdconnect1.html
<!DOCTYPE html>
<html>
<head>
<title>student information</title>
</head>
<body>
<form method="post" action="stdconnect1.php">
Student ID : <input type="text" name="stdid"><br><br>
Student First Name : <input type="text" name="stdfname"><br><br>
Student Last Name : <input type="text" name="stdlname"><br><br>
Address : <input type="text" name="address"><br><br>
Contact Number : <input type="tel" id="phone" name="contactnumber"><br><br>
Email ID : <input type="email" id="email" name="emailid"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

After Successful Submission of Your Data through Form You Got the
Message Like

srdconnect1.php
<?php
$stdid = filter_input(INPUT_POST, 'stdid');
$stdfname = filter_input(INPUT_POST, 'stdfname');
$stdlname = filter_input(INPUT_POST, 'stdlname');
$address = filter_input(INPUT_POST, 'address');
$contactnumber = filter_input(INPUT_POST, 'contactnumber');
$emailid = filter_input(INPUT_POST, 'emailid');
if (!empty($stdid)){
if (!empty($stdfname)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "srdc";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error())
{
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
else{
$sql = "INSERT INTO srdcstudent
(stdid, stdfname,stdlname,address,contactnumber,emailid)
values
('$stdid','$stdfname','$stdlname','$address','$contactnumber','$emailid')";
if ($conn->query($sql))
{
echo "New record is inserted sucessfully";
}
else{
echo "Error: ". $sql ." ". $conn->error;
}
$conn->close();
}
}
else{
echo "Password should not be empty";
die();
}
}
else{
echo "Username should not be empty";
die();
}
?>
8. Write a PHP application to modify the Rows
1. Open Xampp control panel (StartAll ProgramsXampp control panel).
2. After opening Xampp control panel, select Start button behind the Apache and Start button
behind the MYSQL.
3. Select Admin button as shown in fig.

4. Click on User Accounts tab. Click on Add User Account button

Click on
user
accounts
tab

Click on
add user
account
Password as srdc@1234
After typing user name password host name click on go button in the bottom corner of
the page.

Click on databases
tab
You get this page give database name as “srdc” and type as “collation” click on create

After click on create database you get above screen


Create table name as “srdcstudent” with 6 columns as shown below

8. Give the filled name and its values as follows

9. After typing the information, select save button.


And insert any 2 or 3 records and updation is done based on stdid
Now minimize and then type the program in notepad and save it as
srdconnect2.html
<?php
$stdid = filter_input(INPUT_POST, 'stdid');
$stdfname = filter_input(INPUT_POST, 'stdfname');
$stdlname = filter_input(INPUT_POST, 'stdlname');
$address = filter_input(INPUT_POST, 'address');
$contactnumber = filter_input(INPUT_POST, 'contactnumber');
$emailid = filter_input(INPUT_POST, 'emailid');
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "srdc";

// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
// Check connection
if (mysqli_connect_error())
{
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
else
{
$sql = "UPDATE srdcstudent SET stdfname='Kopparapu' WHERE stdid=1001";
if ($conn->query($sql) === TRUE)
{
echo "Record updated successfully";
}
else
{
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
9. Write a PHP application to delete the Rows from a Table.
The above program 1 to 9 steps follow and create a table and insert
2 to 3 records then only the deletion is possible
Srdconnect3.php
<?php
$stdid = filter_input(INPUT_POST, 'stdid');
$stdfname = filter_input(INPUT_POST, 'stdfname');
$stdlname = filter_input(INPUT_POST, 'stdlname');
$address = filter_input(INPUT_POST, 'address');
$contactnumber = filter_input(INPUT_POST, 'contactnumber');
$emailid = filter_input(INPUT_POST, 'emailid');
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "srdc";

// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
// Check connection
if (mysqli_connect_error())
{
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
else
{
$sql = "DELETE FROM srdcstudent WHERE stdid=1806046";
if ($conn->query($sql) === TRUE)
{
echo "Record deleted successfully";
} else
{
echo "Error deleting record: " . $conn->error;
}
}
$conn->close();
?>
10. Write a PHP application to fetch the Rows in a Table
The above 8 program 1 to 9 steps follow and create a table and
insert 2 to 3 records then only fetching of the records is possible
Srdconnect4.php
<?php
$stdid = filter_input(INPUT_POST, 'stdid');
$stdfname = filter_input(INPUT_POST, 'stdfname');
$stdlname = filter_input(INPUT_POST, 'stdlname');
$address = filter_input(INPUT_POST, 'address');
$contactnumber = filter_input(INPUT_POST, 'contactnumber');
$emailid = filter_input(INPUT_POST, 'emailid');
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "srdc";

// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
// Check connection
if (mysqli_connect_error())
{
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
else
{
$sql = "SELECT stdid, stdfname, stdlname,address,contactnumber,emailid FROM
srdcstudent";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["stdid"]."<br>".
"First Name: " . $row["stdfname"]."<br>".
"Last Name" .$row["stdlname"]."<br>".
"Address".$row["address"]."<br>".
"Contact Number".$row["contactnumber"]."<br>".
"Email ID".$row["emailid"]."<br>";
}
} else
{
echo "0 results";
}
}
$conn->close();
?>
Prog11: Create a MYSQL database through php code
dbcreate.php
<html>
<head>
<title> Crate a Database</Title>
</head>
<body>
<?php
//create connection
$con=mysqli_connect("localhost","root","");
//check connection
if(mysqli_connect_errno())
{
echo "Failed to Connect to MySQL".mysqli_connect_errno();
}
else
{
echo "Database Connection Successfully Build";
}
//create a database
$sq1="create database srdcmpcs";
if(mysqli_query($con,$sq1))
{
echo "<br>database srdcmpcs created successfully";
}
else
{
echo "Error Creating database:".mysqli_connect_errno($con);
}
//close connection
mysqli_close($con);
?>
</body>
</html>
Output:

And the srdcmpcs database is observed in phpmyadmin


Prog11: Create a table in MYSQL through php code
tblcreate.php
<html>
<head>
<title> Crate a table in MYSQL Database srdcmpcs </Title>
</head>
<body>
<?php
//create connection
$con=mysqli_connect("localhost","root","", "srdcmpcs");
//check connection
if(mysqli_connect_errno())
{
echo "Failed to Connect to MySQL".mysqli_connect_errno();
}
else
{
echo "Database Connection Successfully Build";
}
//create a Table
$sq1="create table srdcstudentmpcs (FirstName char(30),LastName char(30),Age int)";
//Execute Query
if(mysqli_query($con,$sq1))
{
echo "<br>Table srdcstudentmpcs created successfully";
}
else
{
echo "Error Creating Table:".mysqli_connect_errno($con);
}
//close connection
mysqli_close($con);
?>
</body>
</html>
Output:
Prog12: Insert a record into the table in MYSQL through php code
<html>
<head>
<title> Insert the Values in to table in MYSQL Database srdcmpcs </Title>
</head>
<body>
<?php
//create connection
$con=mysqli_connect("localhost","root","", "srdcmpcs");
//check connection
if(mysqli_connect_errno())
{
echo "Failed to Connect to MySQL".mysqli_connect_errno();
}
else
{
echo "Database Connection Successfully Build"."<br>";
}
//create a Table
mysqli_query
($con,"insert into srdcstudentmpcs
(FirstName,LastName,Age)
values
('Sampath Kumar','Karanam nandu',35)");
echo "Record Successfully Inserted";
mysqli_close($con);
?>
</body>
</html>
OUPUT:
Prog12: Fetch all the records from the table in MYSQL through php code
<html>
<head>
<title> Fetch all the Records From table in MYSQL Database srdcmpcs </Title>
</head>
<body>
<?php
//create connection
$con=mysqli_connect("localhost","root","","srdcmpcs");
//check connection
if(mysqli_connect_errno())
{
echo "Failed to Connect to MySQL".mysqli_connect_errno();
}
else
{
echo "Database Connection Successfully Build"."<br>";
}
$sql = "SELECT * FROM srdcstudentmpcs";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "FirstName: " . $row["FirstName"]."<br>".
"LastName: " . $row["LastName"]."<br>".
"age".$row["Age"]."<br>";
}
}
mysqli_close($con);
?>
</body>
</html>
Output:
OS LAB PROGRAMS
FCFS (First Come First Serve) Scheduling Algorithm
#include<stdio.h>
main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Enter total number of processes(maximum 20):");
scanf("%d",&n);
printf("\nEnter Process Burst Time\n");
for(i=0;i<n;i++)
{
printf("P[%d]:",i+1);
scanf("%d",&bt[i]);
}
wt[0]=0; //waiting time for first process is 0
//calculating waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<I;j++)
wt[i]+=bt[j];
}
printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time");
//calculating turnaround time
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
avwt+=wt[i];
avtat+=tat[i];
printf("\nP[%d]\t\t%d\t\t%d\t\t%d",i+1,bt[i],wt[i],tat[i]);
}
avwt/=i;
avtat/=i;
printf("\n\nAverage Waiting Time:%d",avwt);
printf("\nAverage Turnaround Time:%d",avtat);
return 0;
}
}
OUTPUT:
SJF (Shortest Job First algorithm)
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int et[20],at[10],n,i,j,temp,st[10],ft[10],wt[10],ta[10];
inttotwt=0,totta=0;
floatawt,ata;
charpn[10][10],t[10];
//clrscr();
printf("Enter the number of process:");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("Enter process name, arrival time& execution time:");
//flushall();
scanf("%s%d%d",pn[i],&at[i],&et[i]);
}
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(et[i]<et[j])
{
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}
}
for(i=0; i<n; i++)
{
if(i==0)
st[i]=at[i];
else
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime");
for(i=0; i<n; i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverageturnaroundtime is:%f",ata);
getch();
}
OUTPUT:
Enter the number of process:3
Enter process name, arrival time&amp; execution time:2 5 7
Enter process name, arrival time&amp; execution time:3 6 14
Enter process name, arrival time&amp; execution time:4 7 12

Pnamearrivaltimeexecutiontimewaitingtimetatime
2 5 7 0 7
4 7 12 5 17
3 6 14 18 32
Average waiting time is:7.666667
Average turnaroundtime is:18.666666
OR

#include<stdio.h>
void main()
{
intbt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
floatavg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}
//sorting burst time in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0; //waiting time for first process will be zero
//calculate waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}
avg_wt=(float)total/n; //average waiting time
total=0;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=(float)total/n; //average turnaround time
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}
OUTPUT:
PRIORITY SCHEDULING
#include<stdio.h>
#include<conio.h>
void main()
{
int x,n,p[10],pp[10],pt[10],w[10],t[10],awt,atat,i,j;
clrscr();
printf("Enter the number of process : ");
scanf("%d",&n);
printf("\n Enter process : time priorities \n");
for(i=0;i<n;i++)
{
printf("\nProcess no %d : ",i+1);
scanf("%d %d",&pt[i],&pp[i]);
p[i]=i+1;
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(pp[i]<pp[j])
{
x=pp[i];
pp[i]=pp[j];
pp[j]=x;
x=pt[i];
pt[i]=pt[j];
pt[j]=x;
x=p[i];
p[i]=p[j];
p[j]=x;
}
}
}
w[0]=0;
awt=0;
t[0]=pt[0];
atat=t[0];
for(i=1;i<n;i++)
{
w[i]=t[i-1];
awt+=w[i];
t[i]=w[i]+pt[i];
atat+=t[i];
}
printf("\n\n Job \t Burst Time \t Wait Time \t Turn Around Time Priority \n");
for(i=0;i<n;i++)
printf("\n %d \t\t %d \t\t %d \t\t %d \t\t %d \n",p[i],pt[i],w[i],t[i],pp[i]);
awt/=n;
atat/=n;
printf("\n Average Wait Time : %d \n",awt);
printf("\n Average Turn Around Time : %d \n",atat);
getch();
}
OUTPUT:
Enter the number of process:3
Enter process name,arrivaltime,execution time &amp; priority:1 2 1 3
Enter process name,arrivaltime,execution time &amp; priority:3 5 4 1
Enter process name,arrivaltime,execution time &amp; priority:3 4 6 2

Pname arrivaltime executiontime priority waitingtime tatime


3 5 4 1 0 4
3 4 6 2 5 11
1 2 1 3 13 14
Average waiting time is:6.000000
Average turnaroundtime is:9.666667
ROUND ROBIN SCHEDULING
#include<stdio.h>
int main()
{
int count,j,n,time,remain,flag=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=time_quantum;
time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count]);
wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count];
flag=0;
}
if(count==n-1)
count=0;
else if(at[count+1]<=time)
count++;
else
count=0;
}
printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);
printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);
return 0;
}
OUTPUT:
FIFO (First In, First Out)
#include<stdio.h>
int main()
{
int i, j, n, a[50], frame[10], no, k, avail, count=0;
printf ( "\n ENTER THE NUMBER OF PAGES:\n");
scanf ( "%d",&n);
printf ("\n ENTER THE PAGE NUMBER :\n");
for (i=1;i<=n;i++)
scanf ("%d", &a[i]);
printf (" \n ENTER THE NUMBER OF FRAMES :");
scanf ( "%d",&no);
for(i=0;i<no;i++)
frame[ i ]= -1;
j=0;
printf ("\t ref string\t page frames\n");
for( i=1; i<=n; i++)
{
Printf ( "%d \t\t", a[i]);
avail=0;
for(k=0;k<no; k++)
if (frame[k]= = a[ I ])
avail=1;
if (avail==0)
{
frame[ j ]= a[ I ];
j = ( j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d \t",frame[k]);
}
Printf ("\n");
}
Printf ("Page Fault Is %d", count);
return 0;
}
OUTPUT:

ENTER THE NUMBER OF PAGES: 20


ENTER THE PAGE NUMBER : 70120304230321201701
ENTER THE NUMBER OF FRAMES :3
ref string page frames
7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
0
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
3
2
1 0 1 3
2 0 1 2
0
1
7 7 1 2
0 7 0 2
1 7 0 1
Page Fault Is 15
LRU (Least Recently Used Page Replacement Algorithm)
#include<stdio.h>
main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);
}
printf("\n");
}
}
}
printf("\nThe no of page faults is %d",c);
}
OUTPUT:
Enter no of pages:10
Enter the reference string:7 5 9 4 3 7 9 6 2 1
Enter no of frames:3
7
7 5
7 5 9
4 5 9
4 3 9
4 3 7
9 3 7
9 6 7
9 6 2
1 6 2
The no of page faults is 10
OPR (Optimal Page Replacement Algorithm
)
#include<stdio.h>
int main()
{
int n,pg[30],fr[10];
int count[10],i,j,k,fault,f,flag,temp,current,c,dist,max,m,cnt,p,x;
fault=0;
dist=0;
k=0;
printf("Enter the total no pages:\t");
scanf("%d",&n);
printf("Enter the sequence:");
for(i=0;i<n;i++)
scanf("%d",&pg[i]);
printf("\nEnter frame size:");
scanf("%d",&f);

for(i=0;i<f;i++)
{
count[i]=0;
fr[i]=-1;
}
for(i=0;i<n;i++)
{
flag=0;
temp=pg[i];
for(j=0;j<f;j++)
{
if(temp==fr[j])
{
flag=1;
break;
}
}
if((flag==0)&&(k<f))
{
fault++;
fr[k]=temp;
k++;
}
else if((flag==0)&&(k==f))
{
fault++;
for(cnt=0;cnt<f;cnt++)
{
current=fr[cnt];
for(c=i;c<n;c++)
{
if(current!=pg[c])
count[cnt]++;
else
break;
}
}
max=0;
for(m=0;m<f;m++)
{
if(count[m]>max)
{
max=count[m];
p=m;
}
}
fr[p]=temp;
}
printf("\npage %d frame\t",pg[i]);
for(x=0;x<f;x++)
{
printf("%d\t",fr[x]);
}
}
printf("\nTotal number of faults=%d",fault);
return 0;
}
output
Enter frame size:3
Enter number of pages:12
Enter page[1]:1
Enter page[2]:2
Enter page[3]:3
Enter page[4]:4
Enter page[5]:1
Enter page[6]:2
Enter page[7]:5
Enter page[8]:1
Enter page[9]:2
Enter page[10]:3
Enter page[11]:4
Enter page[12]:5

page | Frame content


--------------------------------------
1 | 1 -1 -1
2 | 1 2 -1
3 | 1 2 3
4 | 1 2 4
1 | 1 2 4
2 | 1 2 4
5 | 1 2 5
1 | 1 2 5
2 | 1 2 5
3 | 3 2 5
4 | 4 2 5
5 | 4 2 5
--------------------------------------
total page fault:7

You might also like