Sunday, July 9, 2017

4. Build a Rails application to accept book information viz. accession number, title, authors, edition and publisher from a web page and store the information in a database and to search for a book with the title specified by the user and to display the search results with proper headings.

After Installing rails application, you have to start the servers both Apache and MySql when you open exe file of rails application, the servers are automatically started

Open a ruby console window

C :\Rails\rails_apps>

Type the following command
Creating Books Database
> mysql -u root

This will now show you mysql> prompt

At mysql prompt type the following

>create database book_development;

>use book_development;

>create table books(id int not null auto_increment,accno varchar(40) not null,title varchar(60) not null,author varchar(60) not null,edition varchar(60) not null,publisher varchar(5) not null,primary key(id));

Creating book Project

Now open another console window type the following command

>rails -d mysql book
>cd book

Creating controller, model and view from database

>ruby script/generate scaffold Book accno:string title:string author:string
edition:string publisher:string

Starting rails server
>ruby script/server

Executing in the web browser
http://localhost:3000/books

Creating main (new) controller for searching book
>ruby script/generate controller main

a controller with a name main will be created..
Opening main controller program
>edit app\controllers\main_controller.rb

Create two views welcome and result

class MainController < ApplicationController
def welcome
@num_books = Book.count
end
def result
@titlename = params[:title]
@bookz = Book.find(:all, :conditions => "title = #{@titlename}")
end
end

Create Result view file
>notepad app\views\main\result.rhtml
<html>
<title> Welcome template for books </title>
<body>
<p> Entered book title is <%= @titlename %> </p>
<table border=1>
<tr><th>Book Id</th> <th>Accesion Number</th><th>Book
Title</th><th>Author</th> <th>Edition </th> <th>Publisher</th></tr>
<% @names.each do |bk|
@id = bk.id
@accno = bk.accno
@title = bk.title
@author = bk.author
@edition = bk.edition
@publisher = bk.publisher%>
<tr>
<td> <%= @id %></td>
<td><%= @accno %> </td>
<td><%= @title %></td>
<td> <%= @author %></td>
<td><%= @edition %></td>
<td> <%= @publisher %></td>
</tr>
<% end %>
</table>
</form></body></html>

Create Welcome view file

>notepad app\views\main\welcome.rhtml
<html>
<title> Welcome template for books </title>
<body>
<p> Total number of books = <%= @num_books %> </p>
<form action = "result" >
Enter Searching Element: <input type="text" name="title" />
<input type=submit value="Search" />
</form></body></html>

Starting Rails Server
ruby script/server

Executing in the web browser
http://localhost:3000/main/welcome

3.Write a PHP program to read student data from an XML file and store into the MySQL database. Retrieve and display using SEARCH function.

lab3.xml

<?xml version="1.0" ?>
<student>
<stud>
<name>BBBB</name>
<usn>1234</usn>
</stud>
<stud>
<name>CCCC</name>
<usn>4567</usn>
</stud>
</student>

lab3.html

<html>
<body>
<center>
<table width="50%" border="2"><tr>
<form action="http://localhost/lab3.php">
<tr><th> ENTER NAME TO SEARCH </th></tr><br/>
<td align="center"><br/>Name: <input type="text" name="name"><br /><br/>
submit: <input type="submit"><br/><br/></td>
</form></tr>
</body>
</html>

lab3.php

<?php
$link=mysqli_connect("localhost","root","","test");
if(!$link)
{
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$name=$_GET['name'];
$studs=simplexml_load_file("http://localhost/lab3.xml");
foreach($studs as $stud)
{
$name = $stud->name;
$usn = $stud->usn;
mysqli_query($link,"insert into stud3 values('$name','$usn')");
}
$name=$_GET['name'];
$res=mysqli_query($link,"select * from stud3 where name='$name'");
if(mysqli_num_rows($res)==0)
{
echo "$name doesn't exist in the table";
}
else
{
echo "<table border='1' align=center width=60%>";
echo "<tr><td width=15% align=center>NAME</td><td width=15%
align=center>USN</td></tr>";
while($arr=mysqli_fetch_row($res))
echo "<tr><td>$arr[0]</td><td>$arr[1]</td></tr>";
echo "</table>";
}
?>

2. Create a XHTML form with Name, Address Line 1, Address Line 2, and Email text fields. On submitting, store the values in MySQL table. Retrieve and display the data based on Name.

>create database stud;
>use stud;
>create table info(name varchar(40), add1 varchar(40), add2 varchar(40),
email varchar(50));
>desc info;

lab2.html

<html>
<body>
<center>
<table width="50%" border="2"><tr>
<form action="http://localhost/insert.php">
<tr><th> ENTER AGE INFORMATION </th></tr><br/>
<td align="center"><br/>Name: <input type="text" name="name"><br
/><br/>
add1: <input type="text" name="add1"><br /><br/>
add2: <input type="text" name="add2"><br /><br/>
email: <input type="text" name="email"><br /><br/>
submit: <input type="submit"><br/><br/></td>
</form></tr>
<tr><form action="http://localhost/search.php">
<tr><th> ENTER NAME TO BE SEARCHED AND DISPLAY ITS DETAILS</th></tr><br/>
<td align="center"><br/>Name: <input type="text" name="name"><br
/><br/>
submit: <input type="submit"><br/><br/></td>
</form></tr>
</body>
</html>

insert.php


<?php
$link=mysqli_connect("localhost","root","","stud");
if(!$link)
{
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$name=$_GET['name'];
$add1=$_GET['add1'];
$add2=$_GET['add2'];
$email=$_GET['email'];
echo "hello " .$name;
echo " INSERTED SUCCESSFULLY<br/><br/>";
$query="insert into info values('$name','$add1','$add2','$email')";
mysqli_query($link,$query) or die(mysql_error());
$res=mysqli_query($link,"select * from info");
echo "<table border='1' align=center width=60%>";
echo "<tr><td width=15% align=center>NAME</td><td width=15%
align=center>ADDRESS1</td><td width=15% align=center>ADDRESS2</td><td
width=15% align=center>EMAIL ID</td></tr>";
while($arr=mysqli_fetch_row($res))
echo
"<tr><td>$arr[0]</td><td>$arr[1]</td><td>$arr[2]</td><td>$arr[3]</td></tr>"
;
echo "</table>";
?>



search.php

<?php
$link=mysqli_connect("localhost","root","","stud");
if(!$link)
{
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$name=$_GET['name'];
$res=mysqli_query($link,"select * from info where name='$name'");
if(mysqli_num_rows($res)==0)
{
echo "$name doesn't exist";
}
else
{
echo "<table border='1' align=center width=60%>";
echo "<tr><td width=15% align=center>NAME</td><td width=15%
align=center>ADDRESS1</td><td width=15% align=center>ADDRESS2</td><td
width=15% align=center>EMAIL ID</td></tr>";
while($arr=mysqli_fetch_row($res))
echo
"<tr><td>$arr[0]</td><td>$arr[1]</td><td>$arr[2]</td><td>$arr[3]</td><
/tr>";
echo "</table>";
}
?>

1.Write a Perl program to insert name and age information entered by the user into a table created using MySQL and to display the current contents of this table.

Open the terminal window, you will get terminal prompt. Enter into the
super user with the following username and password. You will get root
prompt.
Username: su
Password:root123
 Change into mysql with the following command
>mysql
>create database web;
>show databases;
>use web;
>create table age_info(nam varchar(40), age int(11));
>desc age_info;
 Open another terminal window
>chmod 777 /var/www/cgi-bin
>chmod 777 /var/www/html

lab1.html

<html>
<body>
<center><br/><br/>
<table width="50%" border="2"><tr>
<form action="http://localhost/cgi-bin/p1.pl" method="post">
<tr><th> ENTER AGE INFORMATION </th></tr>
<h3>
<td align="center"><br/>Enter your name :<input type="text"
name="nam"><br><br/>
Enter your age :<input type="text" name="age"><br><br/><br/>
click here to send :<input type="submit" value="Send"><br><br/></td>
</h3>
</form></tr>
</table>
</center>
</body>
</html>

l1.pl

#!/usr/bin/perl
use strict;
use CGI':standard';
use DBI;
print header();
print start_html(-title=>"database",-bgcolor=>"#F0F8FF",-text=>"green");
my $nam=param('nam');
my $age=param('age');
my $db=DBI->connect('DBI:mysql:web','root',"") or die "cannot
connect:".DBI->errstr();
my $query=$db->prepare("insert into age_info values('$nam','$age')");
$query->execute();
my $query=$db->prepare("select * from age_info");
$query->execute();
print "<center>";
print "<table width=20% border=2>";
print "<tr><b>STUDENT AGE INFORMATION</b></tr><br/>";
print "<tr><td align=center width=15%><b>NAME</b></td> <td align=center
width=5%><b>AGE</b></td></tr><BR/>";
while(($nam,$age)=$query->fetchrow())
{
print "<tr><td>$nam</td><td>$age</td></tr>";
}
print "</center>";
$query->finish();
$db->disconnect();
print end_html;
exit(0);

Steps to be followed

Load the fedora operating system with the username and password.
For example
Username: fedora
Password: fedora
 Open system menu, click on Administration a submenu will open click on
the service entry. It will open service configuration window.
 Enable and start httpd service and mysqld service entries.
 To open the terminal, select Application menu click on system tools it
will open a submenu. Click on Terminal entry it will open terminal
window.
 In the terminal window, you will get terminal prompt. Enter into the
super user with the following username and password. You will get root
prompt.
Username: su
Password:root1234
 Change the file permission mode using chmod 777 command before
execution of program for the following folders,
>chmod 777 /var/www/cgi-bin
>chmod 777 /var/www/html
 Change into mysql with the following command
>mysql
mysql> show databases;
(use any of the databases available or create a new database )
mysql>create database databasename
mysql>use databasename
mysql>show tables
If tables are not available create a new table by the following
query statement
Create table tablename ( attribute datatypes…..)
 Store your html file under var/www/html and perl or PHP file in cgibin
folder.

13. An EJB application that demonstrates persistence (with appropriate business logic).

Step 1: Creation of Project Application
1. File -> New Project -> Java EE -> Enterprise Application -> click next -> Give name for
project (ex: employee -> set Java EE version as Java EE 5 -> Finish.
2. At the end of creation you can see three modules generated.
Step 2: Create database
1. Select services-> Databases ->right click JavaDB ->create database ->right click
jdbc:derby://….. and connect
Step 3: Creation of Entity Bean
1. Right click on projects ejb module -> new -> Entity class -> Give class name and
package -> click next -> Select data source with your database -> Finish.
2. Change AUTO to IDENTITY and add the following code
String name;
int salary;
3. Select the variables -> right click over the selection -> insert code -> Getter and Setter…
-> select all -> Generate. You can see getter and setter method generated.
Step 4: Creation of Session bean for Entity Class
1. Right click on projects ejb module -> new -> Other -> Enterprise Java beans -> Session
bean for entity classes -> click Add all -> click next -> select local.
Step 5: Creating Servlet file
1. Right click on project war module -> new -> servlet -> Give name for servlet and
package -> next -> finish.
2. Inside the class definition -> Right click -> Insert code -> call enterprise bean -> select
your entity class( ex: EmployeeFacade) -> click ok.
3. Inside processRequest method add the following code,
employee dan=new employee();
dan.setName(request.getParameter("name"));
dan.setSalary(Integer.parseInt(request.getParameter("salary")));
empFacade.create(dan);
4. Left click on the error of first line code -> Add import (for your entity class).
Step 6: Creating jsp file
1. Change the code in index.jsp with your code.
2. Your code should produce two label and 2 text boxes and make sure that mapping servlet
with jsp file done correctly.
(<form action="EmployeeServlet">
Name: <input type="text" name="name" value="">
<br>
Salary: <input type="text" name="salary" value="">
<br><br>
<input type="submit" value="submit">
</form>)
Step 7: Executing the project
1. Right click on Application module -> Clean and bulid -> Right click on Application
module -> Deploy.
2. Under services window -> right click on glassfish server -> start the server -> right click
on glassfish server -> view admin console -> Applications -> click on entity bean class
name -> Launch -> click on first link -> Enter data and submit->
3. You can see the data on database by -> right click on your database -> refresh -> expand
your table -> view data.

12. An EJB application that demonstrates MDB (with appropriate business logic).

Services->glassfishserver3.1->right click start->right click view admin console->JMS Resource-
>Click on Connection Factories->New->
Pool Name: jms/queue -> Resource Type: javax.jms.QueueConnectionFactory
Click on Destination Resources -> New ->
JNDI Name: jms/dest -> Resource Type: javax.jms.Queue minimize the window
File -> NewProject -> Java EE -> EnterpriseApplication -> next -> Java EE Version: select Java
EE 5 ->
Check Create EJB module and Web Application module -> finish
In EJB Module
Right click EJB module -> select new message driven bean -> give EJB Name as MyBean and
package name as com -> Select server destinations as jms/dest
Type the following code in the method onMessage()
TextMessage tmsg=null;
tmsg=(TextMessage)message;
System.out.println(tmsg.getText()); /*Left click on error indicator and select surround statement
with try catch*/
In war Module
Select index.jsp file and type the following code inside body tag
<form action="NewServlet">
<table border="1">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Enter message</td>
<td><input type="text" name="msg" value="" /></td>
</tr>
</tbody>
</table>
<input type="submit" value="submit" />
</form>
Right Click on war module -> New -> Servlet -> write servlet name and package name -> finish
In NewServlet before try block of processRequest() method ->right click select insert code -
>Select send JMS message ->Connection factory : jms/queue
Before try block of processRequest type
String str=request.getParameter("msg");
sendJMSMessageToDest(str); /*Left click on error indicator and select surround statement with
try catch*/
clean and build application
deploy EJB module
In glass fish server select Applications click deployed file
Run war file

11. An EJB application that demonstrates Session Bean (with appropriate business logic).

1. Select file -> new project -> java EE -> Enterprise Application -> next -> give project name
and project location -> next -> select glassFishServer -> Select all EJBModule,
WebApplicationModule and finish.
2. It will create ejb,war with project folder.
3. Right click on project-ejb and select new-> session bean -> give EJBName, location,package
and
session type (stateless)& select local interface. It will create java files like projectname.java,
local.java
4. Right click inside projectname.java page -> click insert code -> add business method -> and
define
business methods.
method : add
returnType:int
param1:int -a
param2:int-b (Press OK)
5. change in add method return (a + b)
6. Create a servlet by right clicking the war file and select -> new servlet, give name and location
-> next -> accept the servletname and URL pattern(s) fields and click finish.
7. Right click on the content of servlet session and select insert code then select callEnterprise
Bean -
> Select sessionBean -> click ok.
8. Add the following line in the end of try block
out.println("Addition :" + sessionBeandemo.add(10, 20));
9. Set the relative URL of the project -> right click the project folder -> select properties -> run -
>
select display browser on run relative URL /MyServlet -> OK.
10. Build and run the project

10. Write a JSP program to implement all the attributes of page directive tag.

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes </title>
</head>
<body>
<form action="Directive.jsp">
<h1>Enter the value of n1 and n2: </h1>
Number1: <input type="number" name="n1"/><br/>
Number:2 <input type="number" name="n2"/><br/>
<input type="submit"/>
</form>
</body>
</html>

Directive.jsp

<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page info="composed by DSATM" %>
<%@ page language="java"%>
<%@ page buffer="16kb" %>
<%@ page autoFlush="true" %>
<%@ page isThreadSafe="true" %>
<%@ page errorPage="error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes</title>
</head>
<body bgcolor="orange">
<h2> Usage of Import Attributes </h2>
<h2>Todays Date is: <%=new Date() %></h2>
<h2>To See the use of Error page enter n2 value zero and click submit </h2>
<% int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n2"));
%>
<h2>Value of n1/n2 ==><%=n1/n2 %></h2>
</body>
</html>

error.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes</title>
</head>
<body>
<h2>Value of n2 variable of zero (n/0 is infinity)</h2>
<h3> Sorry an exception occured!</h3><br/>
<h3> The exception is: <%= exception%></h3>
</body>
</html>

9. Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on particular queries(For example update, delete, search etc…).

Student.java

package student;
import java.io.*;
import java.sql.*;
public class Student {
private Connection Database;
private Statement DataRequest;
private ResultSet Results2;
public Student()
{ String url = "jdbc:mysql://localhost:3306/studentdb";
String userID = "root";
String password = "";
try {
Class.forName( "com.mysql.jdbc.Driver");
Database = DriverManager.getConnection(url,userID,password);
}
catch (ClassNotFoundException error){
System.err.println("Unable to load the MySql Driver" + error);
System.exit(1); }
catch (SQLException error){
System.err.println("Cannot connect to the database." + error);
System.exit(2);}
try{
while(true)
{ System.out.println("1. Queries like:: create table/view,alter,drop,update and
delete");
System.out.println("2. Quries like:: Insert");
System.out.println("3. Queries like:: Selection/Calculation/Group
By/OrderBy/Join/Conditional Testing Query");
System.out.println("4. Exit");
InputStreamReader isr = new InputStreamReader(System.in) ;
BufferedReader br = new BufferedReader(isr) ;
System.out.println("Select your choice");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{ case 1:
try {
System.out.println("Enter your query");
String q1 = br.readLine();
DataRequest = Database.createStatement();
DataRequest.execute(q1);
System.out.println("Query Executed successfully");
DataRequest.close();
}
catch(SQLException sqle){System.err.println(sqle);}
break;
case 2:
try {
PreparedStatement pst ;
System.out.println("Enter your query");
String q2 = br.readLine();
pst=Database.prepareStatement(q2);
pst.execute();
System.out.println("Record inserted Successfully.....");
pst.close();
}
catch(SQLException e){System.out.println(e);}
break;
case 3:
try
{
System.out.println("\nEnter the query to be executed\n");
String str=br.readLine();
DataRequest=Database.createStatement();
Results2=DataRequest.executeQuery(str);
DisplayResults(Results2);
DataRequest.close();
}
catch(Exception e){System.err.println(e);}
break;
case 4: System.exit(0);
}
}
}
catch(IOException ioe1){System.err.println(ioe1);}
}
private void DisplayResults (ResultSet Results2) throws SQLException
{
ResultSetMetaData rmd=Results2.getMetaData();
int col=rmd.getColumnCount();
int count=1;
boolean b=Results2.next();
if(!b)
{
System.out.println("No Data Found");
}
else
{
do
{ System.out.print("RECORD " +(count++)+" => ");
for(int i=0;i<col;i++)
System.out.print(Results2.getString(i+1)+"\t");
System.out.println();
}while(Results2.next());
}
}
public static void main(String[] args) {
// TODO code application logic here
final Student sdb = new Student();
}
}

8. Write a JAVA JSP Program to get student information through a HTML and create a JAVA Bean class, populate Bean and display the same information through another JSP.

index.jsp

<html>
<head>
<title> Regisration </title>
</head>
<body bgcolor="pink">
<h1> <pre> <font size="18pt"> Registration Page </font> </pre> <br>
<form action="StudInfo.jsp" method="post">
<pre>
FirstName : <input type="text" name="firstName" length="30" />
SurName : <input type="text" name="surname" length="30" />
USN : <input type="text" name="usn" length="30" />
Course : <input type="text" name="course" length="30" />
Sem : <input type="text" name="sem" length="30" />
Age : <input type="text" name="age" length="30" />
Address : <input type="text" name="address" length="30" />
<input type ="submit" value="submit" /> <input type ="reset" value="reset"/>
</pre>
<form>
</body>
</html>

StudInfo.jsp

<html>
<head>
<title>
Register User
</title>
</head>
<body>
<jsp:useBean id="stud" scope="session" class="com.Student">
<jsp:setProperty name="stud" property="*" />
</jsp:useBean>
<p> your First Name is: <jsp:getProperty name="stud" property="firstName" />.</p>
<p> Your Last Name is :
<jsp:getProperty name="stud" property="surname" />.</p>
<p> Your USN is :
<jsp:getProperty name="stud" property="usn" />.</p>
<p> Your COURSE Name is :
<jsp:getProperty name="stud" property="course" />.</p>
<p> Your SEM is :
<jsp:getProperty name="stud" property="sem" />.</p>
<p> Your AGE is :
<jsp:getProperty name="stud" property="age" />.</p>
<p> Your Address is :
<jsp:getProperty name="stud" property="address" />.</p>
</body>
</html>

Student.java

package com;
public class Student{
private String firstName;
private String surname;
private String usn;
private String course;
private int sem;
private int age;
private String address;
public String getFirstName(){
return firstName;
}
public String getSurname(){
return surname ;
}
public String getUsn(){
return usn;
}
public String getCourse(){
return course;
}
public int getAge(){
return age;
}
public int getSem(){
return sem;
}
public String getAddress(){
return address;
}
public void setFirstName(String newFirstName)
{
this.firstName =newFirstName;
}
public void setSurname(String newSurname )
{
this.surname =newSurname;
}
public void setUsn(String newUsn)
{
this.usn =newUsn;
}
public void setCourse(String newCourse)
{
this.course =newCourse;
}
public void setSem(int newSem )
{
this.sem = newSem;
}
public void setAge(int newAge )
{
this.age =newAge;
}
public void setAddress(String newAddress )
{
this.address =newAddress;
}
}

7. Write a JAVA JSP Program which uses tag to run a applet.

index.jsp

<%@ page language="java" %>
<html>
<head><title>Welcome JSP-Applet Page</title></head>
<body>
<jsp:plugin type="applet" code="Myapplet.class" width="600" height="600">
<jsp:fallback><p>Unable to load applet</p></jsp:fallback>
</jsp:plugin>
</body>
</html>

p7.java

import java.awt.*;
import java.applet.*;
public class Myapplet extends Applet
{
public void init()
{
setBackground(Color.blue);
}
public void paint(Graphics g)
{
int y=50,x=50;
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
if((i+j)%2!=0)
{
g.setColor(Color.black);
}
else
{
g.setColor(Color.white);
}
g.fillRect(x,y,50,50);
x=x+50;
}
y=y+50;
x=50;
}
}
}

6. Write a JAVA JSP Program which uses jsp:include and jsp:forward action to display a Webpage.

header.jsp

<%@ page import="java.util.Date" %>
<html>
<head>
<title> </title>
</head>
<body>
<h1>
My website. Time:
<% Date d=new Date();%>
<%=d%>
</h1>
</body>
</html>
index.jsp
<html>
<head>
<title>Index Page</title>
</head>
<body>
<center>
<jsp:include page="header.jsp"/>
<br />
<h1>
Enter Data
</h1>
<br />
<form method="post" action="val.jsp">
Username:
<input type="text" name="uname"/>
<br/> password:
<input type="password" name="upass"/>
<br/>
<input type="submit" value="login">
</form>
</center>
</body>
</html>

val.jsp

<% if(request.getParameter("uname").equals("student") &&
request.getParameter("upass").equals("ait")){%>
<jsp:forward page="welcome.jsp" />
<%}
else{ %>
<jsp:forward page="index.jsp" />
<% } %>
welcome.jsp
<!DOCTYPE html>
<html>
<head>
<title>welcome page</title>
</head>
<body bgcolor="pink">
<center>
<jsp:include page="header.jsp"/><br/>
<h1>Welcome Mr./Ms. <%=request.getParameter("uname") %></h1>
</center>
</body>
</html>

5 b. Write a JSP program to demonstrate the import attribute.

<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%
System.out.println( "Evaluating date now" );
Date date = new Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>

5. a. Write a JAVA JSP Program to implement verification of a particular user login and display a Welcome page.

login.jsp

<html>
<head> <title> Login page </title>
</head>
<body>
<form action="validation.jsp">
<table border="0">
<tr>
<td> USER ID: </td>
<td>
<input type="text" name="uname" /> <br>
</td>
</tr>
<tr>
<td> PASSWORD: </td>
<td>
<input type="password" name="password" /> <br>
</td>
</tr>
<tr> <td align ="center">
<input type="submit" value="submit" >
<input type="reset" value="reset">
</td>
</tr>
</form>
</body>
</html>

validation.jsp

<html>
<body>
<%! String uid="student"; %>
<%! String pass="aitmca"; %>
<%! String id, password; %>
<% id=request.getParameter("uname"); %>
<% password=request.getParameter("password"); %>
<% if(uid.equals(id)&&pass.equals(password))
{
%>
<jsp:forward page="welcome.jsp"/>
<%
}
else
%>
<jsp:forward page="error.jsp" />
<%
}
%>
</body>
</html>

welcome.jsp


<html>
<body bgcolor="pink">
<center>
<%! String id; %>
<% id=request.getParameter("uname"); %>
<h1> welcome <%=id%> to the home page </h1>
</center>
</body>
</html>

error.jsp

<html>
<head> <title>JSP Page</title> </head>
<body bgcolor="pink">
<h1>INVALID ENTRY</h1>
</body>
</html>

4. Write a JAVA Servlet Program using cookies to remember user preferences.

index.html

<html>
<head>
<title>Cookies</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form id="form1" action="SetCookieServlet" method="post">
<table>
<tr>
<td>Name</td><td><input type="text" name="uname"/></td>
</tr>
<tr>
<td>Email</td><td><input type="email" name="uemail"/></td>
</tr>
<tr>
<td>Password</td><td><input type="password" name="upass"/></td>
</tr>
</table>
<input type="submit" value="Set Cookie"/>
</form>
<br/>
<form id="form2" action="FetchCookieServlet" method="post">
<input type="submit" value="Fetch Cookie"/>
</form>
</center>
</body>
</html>


SetCookieServlet.java

package com;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetCookieServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie_name = new Cookie("uname",request.getParameter("uname"));
Cookie cookie_email = new Cookie("uemail",request.getParameter("uemail"));
Cookie cookie_pass = new Cookie("upass",request.getParameter("upass"));
cookie_name.setMaxAge(60*60*24);
cookie_email.setMaxAge(60*60*24);
cookie_pass.setMaxAge(60*60*24);
response.addCookie(cookie_name);
response.addCookie(cookie_email);
response.addCookie(cookie_pass);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML><html><head><title>Set Cookie</title></head>"+
"<body><center>"+
"<h1>Cookie has been set successfully!</h1><br/>"+
"<a href='index.html'>Click here to go back to previous page</a>"+
"</body></html>");
}
}

FetchCookieServlet

package com;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FetchCookieServlet extends HttpServlet {
Cookie cookie = null;
Cookie[] cookies = null;
PrintWriter out;
private String searchCookie(String s)
{
for (Cookie cookie1 : cookies) {
cookie = cookie1;
if((cookie.getName( )).compareTo(s)==0)
return cookie.getValue( );
}
return "";
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
cookies = request.getCookies();
response.setContentType("text/html");
out = response.getWriter();
out.println("<!DOCTYPE HTML><html><head><title>Fetch Cookie</title> </head> <body>
<center>");
if( cookies != null )
{
out.println("<h1>Welcome "+searchCookie("uname")+"</h1><br/>"+
"Your Email ID: "+searchCookie("uemail")+"<br/>"+
"Your Password: "+searchCookie("upass"));
}
else
{
out.println("<h1>No Cookies found!</h1>");
}
out.println("<br/><a href='index.html'>Click here to go back to previous
page</a></center></body></html>");
}
}

3. Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet Class).

index.html

<html><head><title>Demonstration of Get and Post Method</title></head>
<body bgcolor="pink">
<center>
<form action="Prog3" method="post">
<a href="Prog3"><b>Click here to call get method</b></a><br><br>
<p><b>Press submit button to call Post method</b></p><br><B>color:</B>
<select name="color" size="1">
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select><br><br>
<input type=submit value="submit">
</form>
</body>
</html>

Prog3.java (Servlet File)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Prog3 extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
String color=request.getParameter("color");
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Prog3</title>");
out.println("</head>");
out.println("<body bgcolor="+color+">");
out.println("<b>Hello from Post method</b><br><br>");
out.println("You have selected" + " " + color + " " + "color");
out.println("</body></html>");
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
try (PrintWriter out = response.getWriter())
{
out.println("<b>Hello from Get method</b>");
out.println("<h1>Welcome to AIT</h1>");
}
}

2. Write a JAVA Servlet Program to Auto Web Page Refresh (Consider a webpage which is displaying Date and time or stock market status. For all such type of pages, you would need to refresh your web page regularly; Java Servlet makes this job easy by providing refresh automatically after a given interval).

index.html

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>JAVA Servlet Program to Auto Web Page Refresh</p>
<p>Click on the following link for Auto Web Page Refresh:</p>
<!-- this will redirect to ServletApplication as URL-pattern for ServletApplication was
mentioned as /home -->
<a href="home"><b>More...</b></a> <hr />
</body>
</html>


TestServlet.java

import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
response.setContentType("text/html");
response.addHeader("Refresh", "2");
out.println("TestServlet says hi at " + new Date());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}





web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

1. Write a JAVA Servlet Program to implement a dynamic HTML using Servlet (user name and Password should be accepted using HTML and displayed using a Servlet).


index.html (HTML file it can be JSP file also)

<html><body>
<center>
<form action="LoginServlet" method="POST">
<b> Login form </b><br><br>
Username: <input type="text" name="uname" value="" /><br><br>
Password: <input type="password" name="pass" value="" /><br><br>
<input type="submit" value="submit" />
</form>
</center>
</body></html>

LoginServlet.java (Servlet File)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>UserPassword</title></head>");
out.println("<body>");
String username = request.getParameter("uname");
String password = request.getParameter("pass");
out.println("Username " + username);
out.println("<br>");
out.println("Password is : " + password);
out.println("</body></html>");
out.close();
}
}

15. Implement N Queen's problem using Back Tracking

#include<stdio.h>
#include<conio.h>
#include<math.h>
int x[20],count=1;
void queens(int,int);
int place(int,int);
void main()
{
int n,k=1;
clrscr();
printf("\n enter the number of queens to be placed\n");
scanf("%d",&n);
queens(k,n);
}
void queens(int k,int n)
{
int i,j;
for(j=1;j<=n;j++)
{
if(place(k,j))
{
x[k]=j;
if(k==n)
{
printf("\n %d solution",count);
count++;
for(i=1;i<=n;i++)
printf("\n \t %d row <---> %d
column",i,x[i]);
getch();
}
else
queens(k+1,n);
}
}
}
int place(int k,int j)
{
int i;
for(i=1;i<k;i++)
if((x[i]==j) || (abs(x[i]-j))==abs(i-k))
return 0;
return 1;
}

14b. Compute the Transitive closure of a given Directed grath using Warshall's algorithm.

#include<stdio.h>
#include<conio.h>
int a[10][10];
void main()
{
int j,k,n;
clrscr();
printf("enter the number of vertice\n");
scanf("%d",&n);
printf("enter the adjacency matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=a[i][j] || a[i][k] && a[k][j];
printf("\n the transitive closure is\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("\t%d",a[i][j]);
printf("\n");
}
getch();
}

14. a. Implement Floyd's algorithm for the All-pairs-Shortest-Path problem.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],a[10][10];
void all_paths(int[10][10],int[10][10],int);
int min1(int,int);
void main()
{
int i,j,n;
clrscr();
printf("\n enter the number of vertices\n");
scanf("%d",&n);
printf("enter the adjacency matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
all_paths(cost,a,n);
printf("\n shortest path obtained is\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("\t%d",a[i][j]);
printf("\n");
}
getch();
}
void all_paths(int cost[10][10],int a[10][10],int n)
{
int i,j,k;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=cost[i][j];
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=min1(a[i][j],a[i][k]+a[k][j]);
}
int min1(int a,int b)
{
return(a<b)?a:b;
}

13. Find Minimum Cost Spanning Tree of a given undirected graph using Prims algorithm.

#include<stdio.h>
#include<conio.h>
void main()
{
int cost[20][20],t[20][20],near1[20],a[20];
int i,j,n,min,minimum,k,l,mincost,c,b;
clrscr();
printf("\n enter the number of nodes\n");
scanf("%d",&n);
printf("\n enter the adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
minimum=cost[1][1];
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(minimum>=cost[i][j])
{
minimum=cost[i][j];
k=i;
l=j;
}
}
mincost=minimum;
t[1][1]=k;
t[1][2]=l;
for(i=1;i<=n;i++)
{
if(cost[i][l]<cost[i][k])
near1[i]=l;
else
near1[i]=k;
}
near1[k]=near1[l]=0;
for(i=2;i<=n-1;i++)
{
min=999;
for(j=1;j<=n;j++)
{
if(near1[j]!=0)
{
a[j]=cost[j][near1[j]];
{
min=a[j];
c=near1[j];
b=j;
printf("\n");
}
}
}
mincost=mincost+cost[b][c];
near1[b]=0;
for(k=1;k<=n;k++)
if((near1[k]!=0) &&
(cost[k][near1[k]]>cost[k][b]))
near1[k]=b;
}
printf("\n\ the cost of minimum spanning tree is=%d",mincost);
getch();
}

12. b. Find the Binomial Co-efficient using Dynamic Programming.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,n,c[50][50];
clrscr();
printf("enter the value of n and k\n");
scanf("%d %d",&n,&k);
for(i=0;i<=n;i++)
for(j=0;j<=k;j++)
c[i][j]=0;
for(i=0;i<=n;i++)
{
c[i][0]=1;
c[i][i]=1;
}
for(i=2;i<=n;i++)
for(j=1;j<=i-1;j++)
c[i][j]=c[i-1][j-1]+c[i-1][j];
printf("the table for valuadation is\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=k;j++)
if(c[i][j]!=0)
printf("\t%d",c[i][j]);
printf("\n");
}
printf("the binomial cofficient of c(%d,%d) is %d\n",n,k,c[n][k]);
getch();
}

12. a. Implement Horspool’s algorithm for String Matching.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int table[126];
char t[100], p[25];
int n, i, k, j, m, flag=0;
clrscr();
printf("Enter the text\n");
gets(t);
n=strlen(t);
printf("Enter the pattern\n");
gets(p);
m=strlen(p);
for(i=0;i<126;i++)
table[i]=m;
for(j=0;j<=m-2;j++)
table[p[j]]=m-1-j;
i=m-1;
while(i<=n-1)
{
k=0;
while(k<=m-1 && p[m-1-k]==t[i-k])
k++;
if(k==m)
{
printf("The position of the pattern is %d\n",i-m+2);
flag=1;
break;
}
else
i=i+table[t[i]];
}
if (!flag)
printf("Pattern is not found in the given text\n");
getch();
}

11. Find a subset of a given set S={s1,s2,….sn} of n positive integers whose sum is equal to a given positive integer d. For example, if S={1,2,5,6,8} and d=9 there are two solutions {1,2,6} and {1,8}. A suitable message is to be displayed if the given problem instance doesn’t have a solution.


#include<stdio.h>
#include<conio.h>
int s[10],d,n,set[10],count=0;
void display(int);
int flag=0;
void main()
{
int subset(int,int);
int i;
clrscr();
printf("Enter the number of elements in set\n");
scanf("%d",&n);
printf("Enter the set values\n");
for(i=0;i<n;++i)
scanf("%d",&s[i]);
printf("Enter the sum\n");
scanf("%d",&d);
printf("The progrm output is\n");
subset(0,0);
if(flag==0)
printf("there is no solution");
getch();
}
int subset(int sum,int i)
{
if(sum==d)
{
flag=1;
display(count);
return;
}
if(sum>d||i>=n)
return;
else
{
set[count]=s[i];


count++;
subset(sum+s[i],i+1);
count--;
subset(sum,i+1);
}
}
void display(int count)
{
int i;
printf("{");
for(i=0;i<count;i++)
printf("%d",set[i]);
printf("}");
}

10. check whether a given graph is connected or not using DFS method.

#include<stdio.h>
#include<conio.h>
void dfs(int n,int cost[10][10],int u,int s[])
{
int v;
s[u]=1;
for(v=0;v<n;v++)
{
if(cost[u][v]==1 && s[v]==0)
{
dfs(n,cost,v,s);
}
}
}
void main()
{
int n,i,j,cost[10][10],s[10],connected,flag;
clrscr();
printf("\n enter the number of nodes\n");
scanf("%d",&n);
printf("\n enter the adjacency matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cost[i][j]);
]
}
connected=0;
for(j=0;j<n;j++)
{
for(i=0;i<n;i++)
s[i]=0;
dfs(n,cost,j,s);
flag=0;
for(i=0;i<n;i++)
{
if(s[i]==0)
flag=1;
}
if(flag==0)
connected=1;
}
if(connected==1)
printf("graph is connected\n");
else
printf("graph is not connected\n");
getch();
}

9. Print all the nodes reachable from a given starting node in a digraph using BFS method

#include<stdio.h>
#include<conio.h>
void distance(int,int);
int a[10][10];
void main()
{
int i,j,n;
clrscr();
printf("\n enter the number of vertices in the diagraph:");
scanf("%d",&n);
printf("\n enter the adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(i=1;i<=n;i++)
{
printf("\n the starting vertex is %d\n",i);
distance(i,n);
printf("\n\t press enter for other source vertex\n");
getch();
}
}
void distance(int v,int n)
{
int queue[40],visited[20],dis[20],front,rear,i,j;
for(i=1;i<=n;i++)
visited[i]=dis[i]=0;
front=rear=0;
queue[rear++]=v;
visited[v]=1;
do
{
i=queue[front++];
for(j=1;j<=n;j++)
if(a[i][j]&&!visited[j])
{
dis[j]=dis[i]+1;
queue[rear++]=j;
visited[j]=1;
printf("\n\t the vertex %d to %d is of distance=%d\n",v,j,dis[j]);
}
}
while(front<rear);
}

8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.

#include<conio.h>
#include<stdio.h>
int root[10],flag=0,count=0,temp,min;
int a[20],cost[20][20],i,n,j,k,totalcost=0,x,y;
void find_min(),check_cycle(),update();
void main()
{
clrscr();
printf("Enter the number of vertices please\n");
scanf("%d",&n);
printf("Enter the cost of the matrix please\n");
printf("Enter 999 if the edge is not present or for the self loop\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
find_min();
while(min!=999&&count!=n-1)
{
check_cycle();
if(flag)
{
printf("%d --> %d = %d\n",x,y,cost[x][y]);
totalcost+=cost[x][y];
update();
count++;
}
cost[x][y]+=cost[x][y]=999;
find_min();
}
if(count<n-2)
printf("The graph is not connected\n");
else
printf("The graph is connected & the min cost is %d\n",totalcost);
getch();
}
void check_cycle()
{
if((root[x]==root[y]&&root[x]!=0))
flag=0;
else
flag=1;
}
void find_min()
{
min=999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(min>cost[i][j])
{
min=cost[i][j];
x=i;
y=j;
}
}
void update()
{
if(root[x]==0&&root[y]==0)
root[x]=root[y]=x;
else if(root[x]==0)
root[x]=root[y];
else if(root[y]==0)
root[y]=root[x];
else
{
temp=root[y];
for(i=1;i<=n;i++)
if(root[i]==temp)
root[i]=root[x];
}
}

7. Sort a given set of elements using the Quick sort method and determine the time requied to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

#include<stdio.h>
#include<conio.h>
#include<time.h>
void quicksort(int[],int,int);
int partition(int[],int,int);
void main()
{
int i,n,a[20],ch=1;
clock_t start,end;
clrscr();
while(ch)
{
printf("enter the number of elements\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
start=clock();
quicksort(a,0,n-1);
end=clock();
printf("the sorted array elements are \n");
for(i=0;i<n;i++)
printf("\n%d",a[i]);
printf("timetaken =%lf",(end-start)/CLK_TCK);
printf("\n do u want to continue (0/1) \n");
scanf("%d",&ch);
}
getch();
}
void quicksort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=partition(a,low,high);
quicksort(a,low,mid-1);
quicksort(a,mid+1,high);
}
}
int partition(int a[],int low,int high)
{
int key,i,j,temp,k;
delay(500);
key=a[low];
i=low+1;
j=high;
while(i<=j)
{
while(i<=high && key>=a[i])
i=i+1;
while(key<a[j])
j=j-1;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
k=a[j];
a[j]=a[low];
a[low]=k;
}
}
return j;
}

6. form a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm.

#include<stdio.h>
main ()
{
int n, cost[15][15], i, j, s[15], v,dist[15],num,min;
clrscr();
printf ("Enter the vertices please\n");
scanf ("%d", &n);
printf ("Enter the cost of the edges please\n");
printf ("Enter 999 if the edge is not present or for the self loop\n");
for (i = 1; i<= n; i++)
for (j = 1; j <= n; j++)
scanf ("%d", &cost[i][j]);
printf ("Enter the Source vertex please\n");
scanf ("%d", &v);
for (i = 1; i<= n; i++)
{
s[i] = 0;
dist[i] = cost[v][i];
}
s[v] = 1;
dist[v] = 0;
for (num = 2; num <= n - 1; num++)
{
min = 999;
for (i = 1; i<= n; i++)
if (s[i] == 0 &&dist[i] < min)
{
min = dist[i];
j = i;
}
s[j] = 1;
for (i = 1; i<= n; i++)
{
if (s[i] == 0)
{
if (dist[i] > (dist[j] + cost[j][i]))
dist[i] = (dist[j] + cost[j][i]);
}
}
}
printf ("VERTEX\tDESTINATION\tCOST\n");
for (i = 1; i<= n; i++)
printf (" %d\t %d\t\t %d\n", v, i, dist[i]);
getch();
}

5. Implement 0/1 Knapsack problem using dynamic programming.

#include<stdio.h>
#include<conio.h>
int v[20][20];
int max1(int a,int b)
{
return(a>b)?a:b;
}
void main()
{
int i,j,p[20],w[20],n,max;
clrscr();
printf("\n Enter the number of items\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\n enter the weight and profit of the item %d:",i);
scanf("%d %d",&w[i],&p[i]);
}
printf("\ enter the capacity of the knapsack");
scanf("%d",&max);
for(i=0;i<=n;i++)
v[i][0]=0;
for(j=0;j<=max;j++)
v[0][j]=0;
for(i=1;i<=n;i++)
for(j=1;j<=max;j++)
{
if(w[i]>j)
v[i][j]=v[i-1][j];
else
v[i][j]=max1(v[i-1][j],v[i-1][j-w[i]]+p[i]);
}
printf("\n\nThe table is\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=max;j++)
printf("%d\t",v[i][j]);
printf("\n");
}
printf("\n The maximum profit is %d",v[n][max]);
printf("\nThe most valuable subset is:{");
j=max;
for(i=n;i>=1;i--)
if(v[i][j]!=v[i-1][j])
{
printf("\t item %d:",i);
j=j-w[i];
}
printf("}");
getch();
}

4. Obtain the Topological ordering of vertices in a given graph.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],t[10],stack[10],indeg[10],n,u,v,i,j,sum=10,top=-1,k=0;
clrscr();
printf("enter the no of vertex\n");
scanf("%d",&n);
printf("enter the adjency matrix\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<n;i++)
indeg[i]=0;
for(j=0;j<n;j++)
{
sum=0;
for(i=0;i<n;i++)
{
sum=sum+a[i][j];
}
indeg[j]=sum;
}
for(i=0;i<n;i++)
{
if(indeg[i]==0)
{
stack[++top]=i;
}
}
while(top!=-1)
{
u=stack[top--];
t[k++]=u;
for(v=0;v<n;v++)
{
if(a[u][v]==1)
{
indeg[v]--;
if(indeg[v]==0)
{
stack[++top]=v;
}
}
}
}
printf("toplog is\n");
for(i=0;i<n;i++)
{
printf("%d\t",t[i]+1);
printf("\n");
}
getch();
}

Saturday, July 8, 2017

3. Sort a given set of elements using the Merge sort method and determine the time requied to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

#include<stdio.h>
#include<conio.h>
#include<time.h>
#define MAX 20
void mergesort(int a[],int low,int high);
void merge(int a[],int low,int mid,int high);
void main() { int n,i,a[MAX],
ch=1;
clock_t start,end; clrscr();
while(ch)
{
printf("\n \t enter the number of elements\n");
scanf("%d",&n); printf("\n \t enter the elements \n");
for(i=0;i<n;i++) scanf("%d",&a[i]);
start=clock();
mergesort(a,0,n-1); end=clock();
printf("\n the sorted array is \n"); for(i=0;i<n;i++)
printf("%d\n",a[i]);
printf("\n\ntime taken =%lf",(end-start)/CLK_TCK);
printf("\n \ndo u wish to continue(0/1)\n");
scanf("%d",&ch);
}
getch();
}
void mergesort(int a[],int low,int high)
{
int mid;
delay(100);
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
}
void merge(int a[],int low,int mid,int high)
{
int i,j,k,t[MAX];
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
if(a[i]<a[j])
t[k++]=a[i++];
else t[k++]=a[j++];
while(i<=mid)
t[k++]=a[i++];
while(j<=high)
t[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=t[i];
}    

2. Sort a given set of elements using the Heap sort method and determine the time requied to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

#include<stdio.h>
#include<conio.h>
#include<time.h>
void heapsort(int n,int arr[]);
void heapy(int n,int arr[]);
void adjust(int n,int arr[]);
void heapsort(int n,int arr[])
{
int i,item;
delay(100);
heapy(n,arr);
for(i=n;i>=1;i--)
{  
item=arr[1];  
arr[1]=arr[i];  
arr[i]=item;  
adjust(i,arr);
} }
void heapy(int n,int arr[])
{
int i,j,k,item;
for(i=1;i<=n;i++)
{  
item=arr[i];  
j=i;
k=j/2;  
while(k!=0 && item>arr[k])  
{  
arr[j]=arr[k];  
j=k;  
k=j/2;  
}  
arr[j]=item;
} }
void adjust(int n,int arr[])
{  int i,j,item;
j=1;
item=arr[j];
i=j*2;
while(i<n)
{  
if((i+1)<n)  
{  
if(arr[i]<arr[i+1])  
i++;  
}  
if(item<arr[i])  
{  
arr[j]=arr[i];  
j=i;  
i=2*j;  
}  
else  
break;  }
arr[j]=item; }
void main()
{
int i,n,arr[20];
clock_tend,start;
clrscr();
printf("\nEnter the number of Elements: \t");
scanf("%d",&n);
printf("\nEnter the %d Elements:",n);
for(i=1;i<=n;i++)
scanf("%d",&arr[i]);
start=clock();
heapsort(n,arr);
end=clock();
printf("\nSorted Elements are\n");
for(i=1;i<=n;i++)
printf("%d ",arr[i]);
printf("\nTime taken by Heapsort %f CPU Cycle",(end-start)/CLK_TCK);
getch();
}

1. Implement Recursive Binary search and Linear search and determine the time required to search an element. Repeat the experiment for different values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n.

#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#define max 20 Int pos;
Int binsearch (int,int[],int,int,int);
Int linsearch (int,int[],int);
void main()
{ Int ch=1; double t; int n,i,a [max],k,op,low,high,pos; clock_tbegin,end;
clrscr();
while(ch)
{
printf("\n.......MENU.......\n 1.BinarySearch \n 2.Linear search \n 3.Exit \n");
printf("\n enter your choice\n");
scanf("%d",&op);
switch(op)
{
case 1:printf("\n enter the number of elments\n"); scanf("%d",&n);
printf("\n enter the number of an array in the order \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n enter the elements to be searched \n");
scanf("%d",&k); low=0;high=n-1; begin=clock();
pos=binsearch(n,a,k,low,high);
end=clock();
if(pos==-1)
printf("\n\nUnsuccessful search");
else
printf("\n element %d is found at position %d",k,pos+1);
printf("\n Time Taken is %lf CPU1 cycles \n",(end-begin)/CLK_TCK);
getch();
break;
case 2:printf("\n enter the number of elements \n");
scanf("%d",&n);
printf("\n enter the elements of an array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n enter the element to be searched \n");
scanf("%d",&k);
begin=clock();
pos=linsearch(n,a,k);
end=clock();
if(pos==-1)
printf("\n\n Unsuccessful search");
else
printf("element %d is found at position %d",k,pos+1);
printf("\n Time taken is %lf CPU cycles \n",(end-begin)/CLK_TCK); getch();
break;
default:printf("Invalid choice entered \n");
exit(0);
}
printf("\n Do you wish to run again(1/0) \n");
scanf("%d",&ch);
}
getch();
}
intbinsearch(intn,int a[],intk,intlow,int high)
{
int mid;
delay(1000);
mid=(low+high)/2;
if(low>high)
return -1;
if(k==a[mid])
return(mid);
else
if(k<a[mid])
returnbinsearch(n,a,k,low,mid-1);
else
returnbinsearch(n,a,k,mid+1,high);
}
intlinsearch(intn,int a[],int k)
{
delay(1000); if(n<0) return -1;
if(k==a[n-1])
return (n-1);
else
returnlinsearch(n-1,a,k);
}