Sei sulla pagina 1di 80

Web Technology &

E-Commerce/Java/C++

DEPARTMENT OF COMPUTER SCIENCE


SRI VENKATESWARA UNIVERSITY
TIRUPATI-517502
2013-2016

Lab Manual for the Academic Year 2013-16

SUBJECT : Web Technology

STREAM : B.Com
1. Create a web page with the following using HTML :
i) To embed an image map in a web page
ii) To fix the hot spots
iii) Show all the related information when the hot spots are clicked.
2. Create a web page with all types of Cascading style sheets
3. Client Side Scripts for Validating Web Form Controls using DHTML.
4. Write programs in Java to create applets incorporating the following features: Create a
color palette with matrix of buttons Set background and foreground of the control text
area by selecting a color from color palette. In order to select Foreground or background
use check box control as radio buttons To set background images
5. Write programs in Java using Servlets:
i) To invoke servlets from HTML forms
ii) To invoke servlets from Applets
6. Write programs in Java to create three- tier applications using JSP and Databases for
conducting on-line examination, for displaying student mark list. Assume that student
information is available in a database which has been stored in a database server.
7. Programs using XML - Schema - XSLT/XSL
8. Program using DOM / SAX
9. Programs using AJAX
10. Consider A Case Where We Have Two Web Services An Airline Service And A Travel
Agent And The Travel Agent Is Searching For An Airline. Implement This Scenario Using
Web Services And Data Base.
1.Create a web page with the following using HTML
i) To embed an image map in a web page
ii) To fix the hot spots
iii) Show all the related information when the hot spots are checked

AIM:
To create a web page with embed an image map and to with hot spots and related
information when hotspots are c licked.

ALGORITHM:

Step 1: Create a html page.


Step 2: Using image tag embed an any image map in the created html page.
Step 3: Create hotspots in embedded image using different styles(rect,wide…).
Step 4: To get detailed information when hotspots clicked ,using href tag create
some html pages for hot spot
Step 5: Display the results
Step 6: Stop

PROGRAM CODING:
(EXP1.HTML)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<head>
<title>Tamilnadu map</title>
</head>
<body bgcolor="white" text="Black">
<p>
<i>
<font size="45">
Tamilnadu state map
</font>
</i>
</p>
<map name="tamilnadu" align="middle">
<area href="kovai.html" shape="rect" coords="320,334,190,282">
<area href="Thrichy.html" shape="rect" coords="520,150,160,382">
<area href="madurai.html" shape="rect" coords="680,488,190,280">
<area href="http://en.wikipedia.org/wiki/Chennai" shape="rect" coords="700,40,190,100">
</map>
<img src="TN.02.jpg"
usemap="#tamilnadu" align="middle">
</body>
</html>
(KOVAI.HTML)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<head>
<title>kovai district map</title>
</head>
<body text="black">
<img src="coimbatore.jpg">
<p>
<font size="3.9">
Coimbatore, also known as Kovai,it is the second largest city in the Indian state of </p>
<p>Tamil Nadu and the 15th largest urban agglomeration in India with a metropolitan population
of</p><p> over 2 million.It is the second largest urban agglomeration in the
state.</p></font></p>
</body>
</html>

(MADURAI.HTML)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<head>
<title>Madurai</title>
</head>
<body text="black">
<img src="madurai_map.jpg" align="middle">
<font size="4">
<p>Madurai is the administrative headquarters of Madurai<p> District
in the South Indian state of Tamil Nadu.</p> It is the third largest city
in Tamilnadu next to Chennai and Coimbatore and the <p>second largest
municipal corporation in Tamil Nadu next only to Chennai.It is the
most important city in Tamil Nadu state after Chennai and Coimbatore
respectively.</p> It is the capital of Tamil Nadu by administration
headquarters of southern districts in Tamil Nadu.<p>Located on the
banks of River Vaigai, it has been a major settlement for over two millennia.
</p>
</font>
</body>
</html>
(TRICHY.HTML)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<head>
<title>Trichy</title>
</head>
<body text="black">
<img src="trichy mpa.jpg">
<font size="4">
<p>Tiruchirappalli also called Tiruchi or Trichy, is a city in the</p> <p> Indian state of Tamil
Nadu and the administrative headquarters of Tiruchirappalli District.</p> <p> It is the Fourth
largest municipal corporation in Tamil Nadu and also the Fourth largest urban agglomeration in
the state.
</p>
</font>
</body>
</html>

OUTPUT:
TRICHY.HTML

RESULT:
Thus web page with embed an image map and with hot spots and related information
are successfully created.
2.Create a web page with all types of Cascading style sheets.

AIM:
To create a web page by using external as well as internal style sheets.

ALGORITHM :
Step 1: Create a HTML page with necessary DOC TYPE.

Step 2: Give the title in the head tag.

Step 3: Create a internal style sheet in the head using style tag,

Step 4: Call the external style sheet file XYZ.CSS using link real attribute.

Step 5: In the body tag ,using the style sheet class give the contents.

Step 6: In h3 tag create a table using external style sheet.

Step 7: Display the output.

Step 8: Close.

PROGRAM CODING:
(XYZ.CSS)

h3{font_family:arial;font_size:20;color:cyan}
table{border_color:green}
td{font_size;20pt;color:magenta}
(EXP2.HTML)

<html>

<head><h1><center> ALL STYLE SHEETS</center></h1>

<title>USE OF INTERNAL AND EXTERNAL STYLE SHEETS

</title>

<link rel="style sheet" href="xyz.css"type="text/css">

<style type="text/css">

.vid{font_family:verdana;font_style:italic,color:red;text_align:center}

.ani{font_family:tahoma;font_style:italic;font_size:20;text_align:center;}

font{font_family:georgia;color:blue;font_size:20}

ul{list_style_type:circle}
</style>

</head>

<body>

</ol>

<p style="font_size;20pt;color:purple"> Vickram College of Engineering </p>

<p class="ani"> Vickram college of engineering is owned by M.K.S.Srinivasan <br> It is


approved by AICTE. Affilaiated to anna university chennai <br></p>

<h2 class="vid"> Vickram College of Engineering </h2>

<br>

<font> It is an ISO certified institution </font><br>

<br>

<font>

<h2> List of subjects</h2>

<ul>

<li> Numerical method </li>

<li> Web Technology </li>

<li> Network proramming management </li>

<li> Cryptography and network security </li>

<li> Embedded System </li>

<li> Object Oriented Analysis And Design </li>

</ul>

</font>

<h3> Internal mark list </h3>

<table width="100%"cellspacing="2"cellpadding="2"border="5">

<tr>

<th> S.Name </th>

<th> Marks </th>


<th> Results </th>

</tr>

<tr>

<td align="center"> Abi </td>

<td align="center"> 100 </td>

<td align="center"> pass </td>

</tr>

<tr>

<td align="center"> aseefa </td>

<td align="center"> 100 </td>

<td align="center"> pass </td>

</tr>

<tr>

<td align="center"> Anusha </td>

<td align="center"> 100 </td>

<td align="center"> pass </td>

</tr>

</table>

</body>

</html>
OUTPUT:

RESULT:

Thus we created a web page by using as well as internal style sheets and successfully
executed.
3.Client Side Scripts for validating Web Forms Controls using DHTML.

AIM:
Create a client side script for validatinig web form controls usiing HTML.

ALGORITHM:
Step 1: Create a html page using script tag.
Step 2: Define the function validate and define all the validation opearation.
Step 3: Produce the alert message on incomplete submission and also for complete
Submission.
Step 4: In the body attribute tag define background font colors and font style.
Step 5: Create the input type label as a name,depart and id number.
Step 6: Fix the range of the id number as input using max length.
Step 7: On clciking the submit button the validating form function will invoke.
Step 8: Execute the html code in internet explorer on any of the browser.

PROGRAM CODING:

<html>
<head>
<title>validation checking </title>
</head>
<script language="javascript"> function passwordStrength(password)
{
var str1="strong"; var str2="weak";
if (password.length > 6)
document.getElementById("passwordDescription").innerHTML =str1; else
document.getElementById("passwordDescription").innerHTML =str2;
}
function a()
{
var i=document.form1.uname.value; var a=i.length;
var j=document.form1.pass.value; var b=j.length;
if(a==0&&b==0)
window.alert("Enter username and password"); else
{
if(a==0)
window.alert("Enter username "); if(b==0)
window.alert("Enter password");
}
if(a!=0&&b!==0&&b<7) window.alert("password is too short");
}
</script> <body>
<form name="form1" >
<font color="red"><marquee>WEBSITE MODERATORS : </marquee></font>
<br> <br>
UserName:<input type="text" name="uname">@india.com <br>
Password:&nbsp;&nbsp;<input type="password" name="pass"
onkeyup="passwordStrength(this.value)">
<label >Password strength:</label><label id="passwordDescription" >password not
entered</label> <p><h6>Minimum of 7 characters in length.</h6></p> <br>
Powered By www.technoscriptz.com
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;&nbsp;
<input type="button" value="Submit" onclick="a()">
</form>
</body>

OUTPUT:

RESULT:

Thus we created a client side script for validating web form controls using DHTML.
4.Write programs in java to create applet incorporating following features:
Create a color palette with matrix of buttons , set background and foreground of
the control text area by selecting a color from color palette. In order to select
foreground or background use check box control as radio buttons , to set
background images.

AIM:
To write programs in java to create applets incorporating the following features.
i) Create a color palette with matrix of buttons.

ii) Set background and foreground of the control text area by selecting a color from color

palette.

iii) In order to select foreground and background use checkbox control as radio button.

iv) To set background images.

ALGORITHM:

Step 1: Include all necessary header files.

Step 2: Initialize the applet code with height as 800 and width as 300.

Step 3: Extend applet/code with height as 800 and width as 300 which implements

ItemListener

Step 4: Initialize the six buttons with red , blue , green , yellow , magenta and white.

Step 5: The default color of background is white.

Step 6: The default color of text is set as black.

Step 7: Image can be imported.

Step 8: Run the program.

PROGRAM CODING:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="exp" width=400 height=400>
</applet>*/
public class exp extends Applet implements ItemListener
{
int currcolor=5;
int flag=1;
String text="Click any of the buttons";
Button buttons[]=new Button[5];
String colours[]={"Red","Blue","Green","Yellow","Magenta"};
Image img;
CheckboxGroup cbg=new CheckboxGroup();
Checkbox box1=new Checkbox("Background Color",cbg,true);
Checkbox box2=new Checkbox("Text Color",cbg,false);
Checkbox box3=new Checkbox("Loading Image",cbg,false);
public void init()
{
for(int i=0;i<5;i++)
{
buttons[i]=new Button(" ");
add(buttons[i]);
}
buttons[0].setBackground(Color.red);
buttons[1].setBackground(Color.blue);
buttons[2].setBackground(Color.green);
buttons[3].setBackground(Color.yellow);
buttons[4].setBackground(Color.magenta);
add(box1);
add(box2);

add(box3);
box1.addItemListener(this);
box2.addItemListener(this);
box3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ev)
{
if(box1.getState()==true)
flag=1;
else if(box2.getState()==true)
{
text="Default color is black";
flag=2;
}
else if(box3.getState()==true)
{
img=getImage(getDocumentBase(),"Blue hills.jpg");
flag=3;
}
repaint();
}
public void paint(Graphics g)
{
if(flag==2)
{
g.drawString(text,30,100);
switch(currcolor)
{
case 0:
g.setColor(Color.red);
break;
case 1:
g.setColor(Color.blue);
break;
case 2:
g.setColor(Color.green);
break;
case 3:
g.setColor(Color.yellow);
break;
case 4:
g.setColor(Color.magenta);
break;
case 5:
g.setColor(Color.black);
break;
}
g.drawString(text,30,100);
}
else if(flag==1)
{
g.drawString(text,30,100);
switch(currcolor)
{
case 0:
setBackground(Color.red);
break;
case 1:
setBackground(Color.blue);
break;
case 2:
setBackground(Color.green);
break;

case 3:
setBackground(Color.yellow);
break;
case 4:
setBackground(Color.magenta);
break;
case 5:
setBackground(Color.white);
break;
}
}
else if(flag==3)
{
g.drawImage(img,20,90,this);
}
}
public boolean action(Event e,Object o)
{
for(int i=0;i<5;i++)
{
if(e.target==buttons[i])
{
currcolor=i;
text="You have chosen "+colours[i];
repaint();
return true;
}
}
return false;
}
}
OUTPUT:
RESULT:
Thus the java program for color palette, with background, foreground and to set
background images is creates and executed successfully.
5.Write programs in java using servlets:
i) To invoke servlets from HTML forms

AIM:

To write a java program to invoke servlets from HTML form.

ALGORITHM:

client.html

Step 1: Create a web page using HTML form that contains the fields such as text,
password
and one submit button.
Step 2: Set the URL of the server as the value of form’s action attribute.
Step 3: Run the HTML program.
Step 4: Submit the form data to the server.

server.java

Step 1: Define the class server that extends the property of the class GenericServlet.
Step 2: Handle the request from the client by using the method service() of
GenericServlet
class.
Step 3: Get the parameter names from the HTML form by using the method
getParameterNames().
Step 4: Get the parameter values from the HTML forms by using the method
getParameter().
Step 5: Send the response to the client by using the method of PrintWriter class.

PROGRAM CODING:
Servlethtml.HTML
<html>

<head>

<title>Invoking Servlet From HTML</title>

</head>

<body bgcolor="violet">

<form name="form1" method="post" action="http://localhost:8080/servlet/server">

<fieldset>

<legend>Registration</legend>

Enter E-mail&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:
<input type="text" name="LoginID" size="25"/><br/><br/>

Enter Password:

<input type="password" name="Password" size="25">

<input type="submit" Value="SUBMIT">

</fieldset>

</form>

</body>

</html>

Server.java

import java.io.*;

import java.util.*;

import javax.servlet.*;

public class server extends GenericServlet

public void service(ServletRequest req,ServletResponse res)throws


ServletException,IOException

PrintWriter pw=res.getWriter();

pw.print("<h3>Registration Successful...</h3>");

Enumeration e=req.getParameterNames();

while(e.hasMoreElements())

String str1=(String)e.nextElement();

String str2=req.getParameter(str1);

pw.print(str1+"="+str2+"<br/>");

}
pw.close();

Web.xml

servlet>

<servlet-name>server</servlet-name>

<servlet-class>server</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>server</servlet-name>

<url-pattern>/servlet/server</url-pattern>

</servlet-mapping>

Output:
Result:
Thus the program for invoking servlets from html file was successfully executed..
ii) To invoke servlets from Applet

AIM:

To write a java program that invokes servlet from applet.

ALGORITHM:

Step 1: Create the java program with the following


a) Define the class Myapplet which extends the property of the class Applet and
implements the interface ActionListener.
b) Define the objects for Button and add the button in the init() method of Applet
class
c) Make the button to listen the action by using the method addActionListener().
d) Set the URL of the servlet program by using the object of the class URL.
e) Define the object for AppletContext in order to display the output of the servlet on
new browser window.
Step 2: Create HTML file that contains the applet tag and pass the class name to that
applet
code.
Step 3: Create the simple servlet program that contains any response message
Step 4: Run the HTML file that contains the corresponding applet code.
Step 5: Click the button on the applet window in order to invoke the servlet program.

PROGRAM CODING:

Applet.html

<html>
<head>
<title>Invoking Servlets From Applet</title>
</head>
<body bgcolor="violet">
<applet code="AppletClient.class" width="400" height="200">
</applet>
</body>
</html>
AppletClient.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class AppletClient extends Applet implements ActionListener
{
public void init()
{
Label la=new Label("INVOKING SERVLET FROM APPLET");
la.setFont(new Font("Courier",Font.BOLD,15));
la.setForeground(Color.blue);
add(la);
Button b1=new Button("Click Here To Display Date Information From Server");
b1.setBackground(Color.black);
b1.setForeground(Color.white);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
try
{
AppletContext ac=getAppletContext();
URL url = new URL("http://localhost:8080/servlet/MyServer");
ac.showDocument(url);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
MyServer.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
public class MyServer extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{
PrintWriter pw=res.getWriter();
Date d=new Date();
pw.println("<html><body bgcolor=blue><h2>Server Response</h2>");
pw.println("<h3>Current Date and Time From Server:</h3>");
pw.println("<b>"+d+"</b></body></html>");
}
}
Web.xml

<servlet>
<servlet-name>AppletClient</servlet-name>
<servlet-class>MyServer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AppletClient</servlet-name>
<url-pattern>/servlet/MyServer</url-pattern>
</servlet-mapping>
OUTPUT:

RESULT:

Thus the program for invoking servlets from applet was successfully executed..
6. THREE TIER APPLICATION
AIM:

Write a program in Java to create a three tier application using servlet

 For conducting on-line examination

 For displaying the student mark list. Assume student information is available in a
database which

has been stored in a database server.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Write a servlet program using JSP

STEP 3: Create a Database in MS-ACCESS and name it as studentDB1.mdb

STEP 4: Save the JSP program with extension of jsp.

STEP 5: Open the saved file using web browser.

STEP 6: Stop the program.

PROGRAM:

HomePage.html

<%@ page language="java" import="java.sql.*" %>

<%@ page import="java.io.*" %>

<%@ page import="java.util.*" %>

<%

String SeatNum,Name;

String ans1,ans2,ans3,ans4,ans5;

int a1,a2,a3,a4,a5;

a1=a2=a3=a4=a5=0;

Connection connect=null;

Statement stmt=null;

ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url = "jdbc:odbc:StudentDB1";

connect = DriverManager.getConnection(url, " ", " ");

if(request.getParameter("action")!=null)

SeatNum = request.getParameter("Seat_no");

Name = request.getParameter("Name");

ans1 =request.getParameter("group1");

if(ans1.equals("True"))

a1=2;

else

a1=0;

ans2 = request.getParameter("group2");

if(ans2.equals("True"))

a2=0;

else

a2=2;

ans3 = request.getParameter("group3");

if(ans3.equals("True"))

a3=0;

else

a3=2;

ans4 = request.getParameter("group4");

if(ans4.equals("True"))

a4=2;

else

a4=0;

ans5 = request.getParameter("group5");

if(ans5.equals("True"))
a5=0;

else

a5=2;

int Total=a1+a2+a3+a4+a5;

stmt = connect.createStatement();

String query = "INSERT INTO StudentTable (" + "Seat_no,Name,Marks" + ")


VALUES ('" +SeatNum + "', '" + Name + "', '"+Total+ "')";

int result = stmt.executeUpdate(query);

stmt.close();

stmt = connect.createStatement();

query = "SELECT * FROM StudentTable WHERE Name="+"'"+Name+"'";

rs = stmt.executeQuery(query);

%>

<html><head><title>Student Mark List</title></head>

<body bgcolor=khaki>

<center>

<h2>Students Marksheet</h2>

<h3>Name of the College:ABC College of Engineering</h3>

<table border="1" cellspacing="0" cellpadding="0">

<tr>

<td><b>Seat_No</b></td>

<td><b>Name</b></td>

<td><b>Marks</b></td>

</tr>

<%

while(rs.next())

%>
<tr>

<td><%=rs.getInt(1)%></td>

<td> <%=rs.getString(2)%></td>

<td> <%=rs.getString(3)%></td>

</tr>

<%

rs.close();

stmt.close();

connect.close();

%>

</table>

</center>

<br/> <br/><br/>

<table>

<tr><td><b>Date:<%=new java.util.Date().toString() %></td></tr>

<tr><td><b>Signature: X.Y.Z. <b></td></tr>

</table>

<div>

<a href="http://127.0.0.1:8080/jsp-examples/StudExam/Exam.jsp">Click here to go


back</a>

</body>

</html>

<%}else{%>

<html>

<head><title>Online Examination</title>

<script language="javascript">

function validation(Form_obj)

{
if(Form_obj.Seat_no.value.length==0)

alert("Please,fill up the Seat Number");

Form_obj.Seat_no.focus();

return false;

if(Form_obj.Name.value.length==0)

alert("Please,fill up the Name");

Form_obj.Name.focus();

return false;

return true;

</script>

</head>

<body bgcolor=lightgreen>

<center>

<h1>OnLine Examination</h1>

</center>

<form action="Exam.jsp" method="post"

name="entry" onSubmit="return validation(this)">

<input type="hidden" value="list" name="action">

<table>

<tr>

<td><h3>Seat Number:</h3></td>

<td><input type="text" name="Seat_no"></td>

</tr>

<tr>
<td><h3>Name:</h3></td>

<td><input type="text" name="Name" size="50"></td>

</tr>

<hr/>

<tr>

<td><b>Total Marks:10(Each question carries equal marks) </b></td>

<td></td><td></td><td></td><td><b>Time: 15 Min.</b></td>

</tr>

</table>

<hr/>

<b>1. Apache is an open source web server</b><br/>

<input type="radio" name="group1" value="True">True

<input type="radio" name="group1" value="False">False<br>

<br/>

<b>2. In Modern PC there is no cache


memory.</b><br/>

<input type="radio" name="group2" value="True">True

<input type="radio" name="group2" value="False">False<br>

<br/>

<b>3. Tim-Berner Lee is the originator of Java.</b><br/>

<input type="radio" name="group3" value="True">True

<input type="radio" name="group3" value="False">False<br>

<br/>

<b>4.JPG is not a video file extension.</b><br/>

<input type="radio" name="group4" value="True">True

<input type="radio" name="group4" value="False">False<br>

<br/>
<b>5. HTTP is a statefull protocol</b><br/>

<input type="radio" name="group5" value="True">True

<input type="radio" name="group5" value="False">False<br>

<hr/>

<center>

<input type = "submit" value="Submit">

<input type = "reset" value="Clear"><br><br>

</center>

</form>

<%}%>

OUTPUT:
RESULT:

Thus the Web page using JSP has been executed successfully.

7. Programs using XML - Schema – XSLT/XSL


AIM:

To write a XSL program for converting the given XML document into equivalent
XHTML.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Write a sample XML program.

STEP 3: write a XSL program that contains the XSL elements for converting into
XHTML file

STEP 4: Insert the following tag in the second line of the XML file
<?xml-stylesheet type="text/xsl" href="7thexp.xsl"?>

STEP 5: Open the saved XML file using web browser.

STEP 6: Stop the program.

PROGRAM

7thexp.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<!-- Edited by XMLSpy® -->

<?xml-stylesheet type="text/xsl" href="7thexp.xsl"?>

<breakfast_menu>

<food>

<name>Belgian Waffles</name>

<price>$5.95</price>

<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>

<calories>650</calories>

</food>

<food>

<name>Strawberry Belgian Waffles</name>

<price>$7.95</price>

<description>light Belgian waffles covered with strawberries and whipped cream</description>

<calories>900</calories> </food>

<food>

<name>Berry-Berry Belgian Waffles</name>

<price>$8.95</price>
<description>light Belgian waffles covered with an assortment of fresh berries and whipped
cream</description>

<calories>900</calories>

</food>

<food>

<name>French Toast</name>

<price>$4.50</price>

<description>thick slices made from our homemade sourdough bread</description>

<calories>600</calories>

</food>

<food>

<name>Homestyle Breakfast</name>

<price>$6.95</price>

<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>

<calories>950</calories>

</food>

</breakfast_menu>

7thexp.xsl

<?xml version="1.0" encoding="ISO-8859-1"?>


<!-- Edited by XMLSpy® -->
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
<xsl:for-each select="breakfast_menu/food">
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold"><xsl:value-of select="name"/></span>
<xsl:value-of select="price"/>
</div>
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
<xsl:value-of select="description"/>
<span style="font-style:italic">
<xsl:value-of select="calories"/> (calories per serving)
</span>
</div>
</xsl:for-each>
</body>
</html>

OUTPUT
RESULT:
Thus the program for converting the XML into XHTML file using the XSLT
executed successfully.

8. Program using DOM / SAX


AIM
To develop a program for parsing the given XML file using DOM and SAX
parsers.

ALGORITHM
STEP 1: Start the program.

STEP 2: Write a sample XML program.

STEP 3: Write a DOM Parser program using java by including the necessary
package.

STEP 4: Execute the java program by including the XML file as an argument.

STEP 5: Write a SAX Parser program using java by including the necessary
package.

STEP 6: Execute the java program by including the XML file as an argument.

STEP 7:Stop the program.

PROGRAM
colorfile.xml
<?xml version="1.0"?>
<!DOCTYPE shapes [
<!ELEMENT shapes (circle)*>
<!ELEMENT circle (x,y,radius)>
<!ELEMENT x (#PCDATA)>
<!ELEMENT y (#PCDATA)>
<!ELEMENT radius (#PCDATA)>
<!ATTLIST circle color CDATA #IMPLIED>
]>
<shapes>
<circle color="BLUE">
<x>20</x>
<y>20</y>
<radius>20</radius>
</circle>
<circle color="RED" >
<x>40</x>
<y>40</y>
<radius>20</radius>
</circle>
</shapes>
//program using DOM parser.
import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
public class shapes_DOM {
static int numberOfCircles = 0; // total number of circles seen
static int x[] = new int[1000]; // X-coordinates of the centers
static int y[] = new int[1000]; // Y-coordinates of the centers
static int r[] = new int[1000]; // radius of the circle
static String color[] = new String[1000]; // colors of the circles

public static void main(String[] args) {

try{
// create a DOMParser
DOMParser parser=new DOMParser();
parser.parse(args[0]);

// get the DOM Document object


Document doc=parser.getDocument();

// get all the circle nodes


NodeList nodelist = doc.getElementsByTagName("circle");
numberOfCircles = nodelist.getLength();

// retrieve all info about the circles


for(int i=0; i<nodelist.getLength(); i++) {

// get one circle node


Node node = nodelist.item(i);

// get the color attribute


NamedNodeMap attrs = node.getAttributes();
if(attrs.getLength() > 0)
color[i]=(String)attrs.getNamedItem("color").getNodeValue();

// get the child nodes of a circle node


NodeList childnodelist = node.getChildNodes();

// get the x and y value


for(int j=0; j<childnodelist.getLength(); j++) {
Node childnode = childnodelist.item(j);
Node textnode = childnode.getFirstChild();//the only text node
String childnodename=childnode.getNodeName();
if(childnodename.equals("x"))
x[i]= Integer.parseInt(textnode.getNodeValue().trim());
else if(childnodename.equals("y"))
y[i]= Integer.parseInt(textnode.getNodeValue().trim());
else if(childnodename.equals("radius"))
r[i]= Integer.parseInt(textnode.getNodeValue().trim());
}

}
// print the result
System.out.println("circles="+numberOfCircles);
for(int i=0;i<numberOfCircles;i++) {
String line="";
line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
System.out.println(line);
}

} catch (Exception e) {e.printStackTrace(System.err);}

}
}

OUTPUT

//program using SAX parser.


import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.SAXParser;

public class shapes_SAX extends DefaultHandler {

static int numberOfCircles = 0; // total number of circles seen


static int x[] = new int[1000]; // X-coordinates of the centers
static int y[] = new int[1000]; // Y-coordinates of the centers
static int r[] = new int[1000]; // radius of the circle
static String color[] = new String[1000]; // colors of the circles

static int flagX=0; //to remember what element has occurred


static int flagY=0; //to remember what element has occurred
static int flagR=0; //to remember what element has occurred

// main method
public static void main(String[] args) {
try{
shapes_SAX SAXHandler = new shapes_SAX (); // an instance of this class
SAXParser parser=new SAXParser(); // create a SAXParser object
parser.setContentHandler(SAXHandler); // register with the ContentHandler
parser.parse(args[0]);
} catch (Exception e) {e.printStackTrace(System.err);} // catch exeptions
}

// override the startElement() method


public void startElement(String uri, String localName,
String rawName, Attributes attributes) {
if(rawName.equals("circle")) // if a circle element is seen
color[numberOfCircles]=attributes.getValue("color"); // get the color attribute

else if(rawName.equals("x")) // if a x element is seen set the flag as 1


flagX=1;
else if(rawName.equals("y")) // if a y element is seen set the flag as 2
flagY=1;
else if(rawName.equals("radius")) // if a radius element is seen set the flag as 3
flagR=1;
}

// override the endElement() method


public void endElement(String uri, String localName, String rawName) {
// in this example we do not need to do anything else here
if(rawName.equals("circle")) // if a circle element is ended
numberOfCircles += 1; // increment the counter
}

// override the characters() method


public void characters(char characters[], int start, int length) {
String characterData =
(new String(characters,start,length)).trim(); // get the text

if(flagX==1) { // indicate this text is for <x> element


x[numberOfCircles] = Integer.parseInt(characterData);
flagX=0;
}
else if(flagY==1) { // indicate this text is for <y> element
y[numberOfCircles] = Integer.parseInt(characterData);
flagY=0;
}
else if(flagR==1) { // indicate this text is for <radius> element
r[numberOfCircles] = Integer.parseInt(characterData);
flagR=0;
}
}

// override the endDocument() method


public void endDocument() {
// when the end of document is seen, just print the circle info
System.out.println("circles="+numberOfCircles);
for(int i=0;i<numberOfCircles;i++) {
String line="";
line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
System.out.println(line);
}
}
}

OUTPUT
RESULT
Thus the XML program is parsed and executed using DOM parser and SAX parser
separately.

9. Programs using AJAX

AIM:

To Write a Programs using Asynchronous Java Script and XML.


ALGORITHM
STEP 1: Start the program.

STEP 2: Write a program using html that includes the necessary tags and java
script function and object (XMLHttpRequest)

STEP 3: Update the web page using the content given in an input file.

STEP 4: Stop the program.

PROGRAM:

//input file ajax_info.txt

AJAX is not a new programming language.


AJAX is a technique for creating fast and dynamic web pages.
//source file

<html>

<head>

<script type="text/javascript">

function loadXMLDoc()

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange=function()

if (xmlhttp.readyState==4 && xmlhttp.status==200)

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

}
xmlhttp.open("GET","ajax_info.txt",true);

xmlhttp.send();

</script>

</head>

<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>

<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>

</html>

OUTPUT:

//output1

Let AJAX change this text

//output2

AJAX is not a new programming language.

AJAX is a technique for creating fast and dynamic web pages.

RESULT:

Thus the program using AJAX is executed successully.

10. Consider a case where we have two web Services an airline service and a travel
agent and the travel agent is searching for an airline. Implement this scenario using
Web Services and Data base.
AIM:

To create an airline reservation service and a travel agent and the travel agent is
searching for an airline using webservices and database

ALGORITHM:

Step 1: Start the Program

Step 2: Create a root process for Reservation

Step 3: Create a service with focus on each item

Step 4: Output the items

Step 5: Stop

Program:
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Airline Reservation System-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Airline Reservation System</title>
<script type = "text/javascript">
<!-- var input;
var secondInput;
var element;
var secondElement;
var firstCount = 0;
var economyCount = 0;
var seats = [ ,0,0,0,0,0,0,0,0,0,0]; //allocate 10-element Array
function startArray()
{
for(var i=0; i<11; i++)
{
input = window.prompt("Please type 1 for First Class and Please type 2 for
Economy.","0");
if (input == 1 || input == 2)
{
element = linearSearch(seats);
if (element==-1 && input == 1)
{
document.writeln("The First Class is already fully booked<br/>");
secondQuestion(seats);
}
else if (element ==-1 && input == 2)
{
document.writeln("The Economy Class is already fully booked<br/>");
secondQuestion(seats);
}
else
boardingPass(input);
} //to terminate the program
else
{
window.status = "Bye-bye!";
System.exit(0);
}}}
function linearSearch(theArray)
{
if (input == 1)
{
for (var n=0; n<6 ; n++)
if (theArray [n] == 0)
return n;
}
else if (input == 2)
{
for (var n=6; n<11 ; n++)
if (theArray [n] == 0)
return n;
}
return -1;
}
function boardingPass(theInput)
{
if (input ==1)
{
document.writeln("----------BOARDING PASS----------<br/>");
document.writeln("You are allocated in the First Class<br/>");
document.writeln("Your seat number is "+ element+"<br/>");
document.writeln("-----------------------------------------<br/>"); seats[element]= 1;
firstCount++;
}
else if (input ==2)
{
document.writeln("----------BOARDING PASS----------<br/>");
document.writeln("You are allocated in the Economy Class<br/>");
document.writeln("Your seat number is "+ element +"<br/>");
document.writeln("-----------------------------------------<br/>");
seats[element]= 1;
economyCount++;
}
}
function secondQuestion(theArray)
{
if (input == 1)
{
for (var n=6; n<11 ;n++)
{
if (theArray [n] == 0)
{
secondInput = window.prompt("Do you want to move to Economy Class? (If YES,
please press 1. If NO, please press 2)","0");
if ( secondInput == 1)
{
input = 2;
element=linearSearch(seats);
document.writeln("You have been allocated to Economy Class<br/>");
boardingPass(input);
break;
}
else if (secondInput == 2)
{ document.writeln("Next flight leaves in 3 hours<br/>");
break;
} }}
}
else if (input == 2)
{
for (var n=0; n<6 ;n++)
{
if (theArray [n] == 0)
{
secondInput = window.prompt("Do you want to move to First Class? (If YES, please
press 1. If NO, please press 2)","0");
if ( secondInput == 1)
{
input = 1;
element=linearSearch(seats);
document.writeln("You have been allocated to First Class<br/>");
boardingPass(input);
break;
}
else if (secondInput == 2)
{
document.writeln("Next flight leaves in 3 hours<br/>");
break;
} }}}
}
//-->
</script>
</head>
<body onload = "startArray()"></body>
</html>
Output

Result:
The web service for the required application is created.
C++
1. Write a Program in C# to Check whether a number is Palindrome or not.

using System;

class palindrome

public static void Main()

int num=0,rev,num1=0,num2=0;

Console.WriteLine("Enter a number");

num=int.Parse(Console.ReadLine());

num2=num;

while(num>0)

rev=num%10;

num=num/10;

num1=num1*10+rev;

if(num1==num2)

Console.WriteLine("Number is Palindrome");

else

Console.WriteLine("Number is NOT Palindrome");

2. Write a Program in C# to demonstrate Command line arguments Processing.

using System;

class cmdarg
{

public static void Main()

int num=0;

String[] argument=Environment.GetCommandLineArgs();

for(int i=1;i<argument.Length;i++)

num=num+int.Parse(argument[i]);

Console.WriteLine("Sum is "+ num);

3. Write a Program in C# to find the roots of Quadratic Equation.

using System;

public class roots

double a=0, b=0, c=0, d=0, r1=0, r2=0, n=0, m=0;

public void input()

Console.WriteLine("Enter the quardatic Equation");

a = double.Parse(Console.ReadLine());

b = double.Parse(Console.ReadLine());

c = double.Parse(Console.ReadLine());

d = Math.Sqrt(b * b - 4 * a * c);

if (d == 0)

Console.WriteLine("The Roots for the given Equation are Real and Equal");

r1 = r2 = -b / (2 * a);

Console.WriteLine("Root is: " + r1 + "and" + r2);

else if (d < 0)

Console.WriteLine("Roots for te given equation are Real and distinct");


r1 = (-b + d) / (2 * a);

r2 = (-b - d) / (2 * a);

Console.WriteLine("The Roots are: " + (int)r1 + "and" + (int)r2);

else

Console.WriteLine("The Roots for the given Equation are Imaginary");

n = -b / (2 * a);

m = Math.Sqrt(Math.Abs(b * b - 4 * a * c)) / (2 * a);

Console.WriteLine("Root 1: " + n + "+i " + m);

Console.WriteLine("Root 2: " + n + "-i " + m);

class Quad

public static void Main()

roots r = new roots();

r.input();

4. Write a Program in C# to demonstrate boxing and unBoxing.


using System;

class demo

static void box(object obj)

Console.WriteLine("value" + obj);

public static void Main()

Object o;

int a = 10;

double d = 4.4;

o = a; //boxing integer

Console.WriteLine("Passing integer");

box(a);

Console.WriteLine("Passing Object");

box(o);

int x = (int)o;//Unboxing

Console.WriteLine("Unboxing");

Console.WriteLine("a=" + x);

o = d; //boxing double

Console.WriteLine("Passing double");

box(d);

Console.WriteLine("Passing Object");

box(o);

double dd = (double)o; //Unboxing

Console.WriteLine("Unboxing");

Console.WriteLine("d=" + dd);

}
5. Write a Program in C# to implement Stack operations.

using System;

class stack

int top;

int[] s;

public stack(int size)

s = new int[size];

top = -1;

public stack() { }

public void pop()

if (top == -1)

Console.WriteLine("No elements to Pop\n");

return;

Console.WriteLine("The Poped element is" + s[top]);

top--;

public void push(int var)

//Console.WriteLine("top = " + top);

s[++top] = var;

public void display()

Console.WriteLine("The Contents of the Stack are\n");


if (top == -1)

Console.WriteLine("No elements to Display\n");

return;

for (int i = 0; i<=top; i++)

Console.WriteLine(s[i]);

public class demo

public static void Main()

Console.WriteLine("Enter the Size of Stack\n");

int size = int.Parse(Console.ReadLine());

stack st = new stack(size);

//st.init();

int eflag = 0;

do

Console.WriteLine("\n\nEnter your Choice\n");

Console.WriteLine("1. Push");

Console.WriteLine("2. Pop");

Console.WriteLine("3. Display");

Console.WriteLine("4. Exit\n\n");

int ch = int.Parse(Console.ReadLine());

switch (ch)

case 1: Console.WriteLine("Enter a Number to Push\n");

int var = int.Parse(Console.ReadLine());

st.push(var);

break;
case 2: st.pop();

break;

case 3: st.display();

break;

case 4: eflag=1;

break;

} while (eflag==0);

6. Write a program to demonstrate Operator overloading.

using System;

class OLoad

int var1,var2;

public OLoad(int a, int b)

var1=a;

var2=b;

public OLoad()

public static OLoad operator ++ (OLoad op1)

return new OLoad(op1.var1+1,op1.var2+1);

public static OLoad operator -- (OLoad op1)

return new OLoad(op1.var1-1,op1.var2-1);

}
public static OLoad operator + (OLoad op1,OLoad op2)

return new OLoad(op1.var1+op2.var1,op1.var2+op2.var2);

public static OLoad operator - (OLoad op1,OLoad op2)

return new OLoad(op1.var1-op2.var1,op1.var2-op2.var2);

public override string ToString()

return string.Format("[" + var1 + "," + var2 + "]");

class OLoadMain

public static void Main()

OLoad op1=new OLoad(10,20);

OLoad op2=new OLoad(30,40);

OLoad op3=new OLoad();

Console.WriteLine("Before overloading, the value of op1 is: " + op1 + "\n");

Console.WriteLine("Before overloading, the value of op2 is: " + op2 + "\n");

op1++;

op2++;

Console.WriteLine("After overloading, the value of op1 is: " + op1 + "\n");

Console.WriteLine("After overloading, the value of op2 is: " + op2 + "\n");

Console.WriteLine("Before overloading, the value of op3 is: " + op3 + "\n");

op3=op1+op2;

Console.WriteLine("After overloading, the value of op3 is: " + op3 + "\n");

op3=op1-op2;

Console.WriteLine("After overloading, the value of op3 is: " + op3 + "\n");

}
7. Write a Program in C# to find the second largest element in a single dimensional array.

using System;

class SLar

int size;

int[] nums;

int lar, sec;

public SLar(int n)

nums=new int[size=n];

public void input()

Console.WriteLine("Enter the Elements of the array");

for (int i = 0; i < size; i++)

nums[i] = int.Parse(Console.ReadLine());

public int second()

lar = nums[0];

sec = nums[1];

for (int i = 0; i < size; i++)

if (nums[i] > lar)

sec = lar;

lar = nums[i];

if ((sec < nums[i] && nums[i] > lar || (nums[i] != lar && sec == lar)))

sec = nums[i];

}
if(sec==lar)

return -1;

else

return sec;

class SLarMain

public static void Main()

Console.WriteLine("Enter the Size of Array");

SLar s = new SLar(int.Parse(Console.ReadLine()));

s.input();

Console.WriteLine((s.second() == -1 ? "\nAll Elements are Equal" : "\nSecond Largest=" +


s.second()));

8. Write a Program in C# to multiply to matrices using Rectangular arrays.

using System;

class MatMulti

int r1,r2,c1,c2;

double[,]a; double[,]b; double[,]c;

public MatMulti(int r1,int c1,int r2,int c2)

a=new double[(this.r1=r1),(this.c1=c1)];

b=new double[(this.r2=r2),(this.c2=c2)];

c=new double[r1,c2];

public void Multiply()

if(c1==r2)
{

Console.WriteLine("Enter elements of first matrix");

for(int i=0;i<r1;i++)

for(int j=0;j<c1;j++)

a[i,j]=double.Parse(Console.ReadLine());

Console.WriteLine("Enter elements of second matrix");

for(int i=0;i<r2;i++)

for(int j=0;j<c2;j++)

b[i,j]=double.Parse(Console.ReadLine());

for(int i=0;i<r1;i++)

for(int j=0;j<c2;j++)

c[i,j]=0;

for(int k=0;k<r2;k++)

c[i,j]+=a[i,k]*b[k,j];

Console.WriteLine("First matrix");

for(int i=0;i<r1;i++)

for(int j=0;j<c1;j++)

Console.Write(a[i,j]+" ");

Console.WriteLine();

Console.WriteLine("Second matrix");

for(int i=0;i<r2;i++)

{
for(int j=0;j<c2;j++)

Console.Write(b[i,j]+" ");

Console.WriteLine();

Console.WriteLine("Product matrix is:");

for(int i=0;i<r1;i++)

for(int j=0;j<c2;j++)

Console.Write(c[i,j]+" ");

Console.WriteLine();

else

Console.WriteLine("Multiplication is not possible:");

class MultiImpl

public static void Main()

int a,b,c,d;

Console.WriteLine("Enter no.of rows and columns of first matrix:");

a=int.Parse(Console.ReadLine());

b=int.Parse(Console.ReadLine());

Console.WriteLine("Enter no.of rows and columns of second matrix:");

c=int.Parse(Console.ReadLine());

d=int.Parse(Console.ReadLine());

MatMulti m=new MatMulti(a,b,c,d);

m.Multiply();

}
9. Find the sum of all the elements present in a jagged array of 3 inner arrays.

using System;

public class JaggedArrayDemo

public static void Main()

int sum = 0;

int[][] arr = new int[3][];

arr[0] = new int[3];

arr[1] = new int[5];

arr[2] = new int[2];

for (int i = 0; i < arr.Length; i++)

Console.WriteLine("Enter the Size of the Inner Array " + (i + 1) + " : ");

arr[i] = new int[int.Parse(Console.ReadLine())];

Console.WriteLine("Enter elements for Inner Array " + arr[i].Length + " : ");

for (int j = 0; j < arr[i].Length; j++)

arr[i][j] = int.Parse(Console.ReadLine());

sum += arr[i][j];

Console.WriteLine("The Sum is = " + sum);

10. Write a program to reverse a given string using C#.

using System;

using System.Collections.Generic;
using System.Linq;

using System.Text;

namespace RevStr

public class StrRev

string str1, str2;

public StrRev(string s)

str1 = s;

public string Reverse()

for (int i = str1.Length; i > 0; i--)

string s = str1.Substring(i - 1, 1);

str2 = str2 + s;

str2 = str2 + "\n";

return str2;

public class Program

public static void Main(string[] args)

string s1, s2;

Console.WriteLine("Enter a string : ");

s1 = Console.ReadLine();

StrRev sr = new StrRev(s1);

s2 = sr.Reverse();

Console.WriteLine("The reverse is : \n" + s2);


Console.ReadLine();

11. Using Try, Catch and Finally blocks write a program in C# to demonstrate error handling.

using System;

class ExceptionDemo

public static void Main()

int a = 1, b = 0, c;

try

c = a / b;

catch (ArithmeticException ae)

Console.WriteLine("Exception Divide by Zero\n\n" + ae);

try

int[] arr = new int[2];

arr[3] = 5;

catch (IndexOutOfRangeException iore)

Console.WriteLine("Array Index out of bounds Exception\n\n" + iore);

finally

Console.WriteLine("Finally block Executing...");


}

12. Design a simple calculator using Switch Statement in C#.

using System;

namespace SimpleCalc

class Calc

private float a, b, c;

char op;

public Calc(float a, float b, char op)

this.a = a;

this.b = b;

this.op = op;

public void Calculator()

try

if (op != '+' && op != '-' && op != '*' && op != '/')

throw new opchck("Operator Invalid");

else

switch (op)

case '+': c = a + b; break;

case '-': c = a - b; break;

case '*': c = a * b; break;


case '/':

try

c = a / b;

catch (ArithmeticException e)

Console.WriteLine("Denomination zero");

} break;

default: break;

Console.WriteLine("The answer is : " + c);

catch (opchck o)

Console.WriteLine(o);

class opchck : Exception

public opchck(string msg)

: base(msg)

public opchck()

public class Demo


{

public static void Main(string[] args)

char ch;

do

Console.WriteLine("\nEnter first operand : ");

float a = float.Parse(Console.ReadLine());

Console.WriteLine("Enter the operator : ");

char op = char.Parse(Console.ReadLine());

Console.WriteLine("Enter second operand : ");

float b = float.Parse(Console.ReadLine());

Calc c = new Calc(a, b, op);

c.Calculator();

Console.WriteLine("Do you want to continue(y/n)");

ch = char.Parse(Console.ReadLine());

} while (ch == 'Y' || ch == 'y');

//Console.ReadLine();

13. Demonstrate Use of Virtual and override key words in C# with a simple Program

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Virtualnride

class Bird

public string name;


public string type;

public virtual void setfun()

name = "Generic bird";

type = "Generic type";

public virtual void display()

Console.WriteLine("Name=" + name);

Console.WriteLine("Type=" + type);

class FlyingBird : Bird

public override void setfun()

//base.setfun();

name = "Indianswift";

type = "Fastest flying bird";

public override void display()

Console.WriteLine("Name=" + name);

Console.WriteLine("Type=" + type);

class Program

static void Main(string[] args)

Bird o1 = new Bird();

o1.setfun();

o1.display();
FlyingBird o2 = new FlyingBird();

o2.setfun();

o2.display();

Console.ReadLine();

14. Implement linked lists in C# using the existing collections name space.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

namespace LinkedList

public class MyLinked

private ArrayList arr;

public MyLinked()

Console.WriteLine("Linked list created");

arr = new ArrayList(0);

public void insert(int value, int pos)

if (checkpos(pos))

arr.Insert(pos, value);

public void add(int val)

{
arr.Add(val);

public Boolean checkpos(int pos)

if (arr.Count < pos || pos < 0)

Console.WriteLine("position should be greater than 0 and in between 1 & " +


arr.Count);

return false;

else

return true;

public Boolean checkLen()

if (arr.Count == 0)

Console.WriteLine("list empty");

return false;

return true;

public void remove(int pos)

if (pos >= 0 && pos < arr.Count)

arr.RemoveAt(pos);

else

Console.WriteLine("Position is out of array size");

public void delete(int val)


{

if (arr.IndexOf(val) >= 0 && arr.IndexOf(val) < arr.Count)

arr.Remove(val);

else

Console.WriteLine("The element does not present");

public void show()

int[] a = new int[arr.Count];

arr.CopyTo(a);

if (checkLen())

foreach (int i in arr)

Console.WriteLine(i);

public void clearAll()

arr.Clear();

public class Demo

public static void Main()

MyLinked l = new MyLinked();

int pos, val;

while (true)

Console.Write("\n\n1. Add \n2. Insert\n3. Delete By Position \n4. Delete By Value\n5.


Display \n6. Clear \n7. Exit \nEnter your choice : ");

String ch = Console.ReadLine();

switch (ch)

case "1":

Console.WriteLine("Enter the value : ");


val = int.Parse(Console.ReadLine());

l.add(val);

break;

case "2":

Console.WriteLine("Enter the value and position ");

val = int.Parse(Console.ReadLine());

pos = int.Parse(Console.ReadLine());

l.insert(val, pos - 1);

break;

case "3":

if (l.checkLen())

Console.WriteLine("Enter the position ");

pos = int.Parse(Console.ReadLine());

l.remove(pos - 1);

break;

case "4":

if (l.checkLen())

Console.WriteLine("Enter the value");

val = int.Parse(Console.ReadLine());

l.delete(val);

break;

case "5":

l.show();

break;

case "6":

l.clearAll();

break;

case "7":

Environment.Exit(0);
break;

default: break;

15. Write a program to demonstrate abstract class and abstract methods in C#.

using System;

namespace Abstract

public abstract class Vehicle

public string Name;

public int Wheels;

public double Amount;

public abstract void Calculate();

public class Motorcycle : Vehicle

public Motorcycle()

this.Wheels = 2;

public Motorcycle(string s)

this.Wheels = 2;

this.Name = s;

public override void Calculate()


{

this.Amount = 100000 + (500 * this.Wheels);

Console.WriteLine("This motor cycle name is " + this.Name + " and its price is " +
this.Amount);

public class Car : Vehicle

private string EngineType;

public Car()

this.Wheels = 4;

public Car(string s, string t)

this.Wheels = 4;

this.Name = s;

this.EngineType = t;

public override void Calculate()

this.Amount = 100000 + (500 * this.Wheels) + 8000;

Console.WriteLine("This car name is " + this.Name + " has engine type " + this.EngineType
+ " and price " + this.Amount);

public class Program

public static void Main(string[] args)

Vehicle v;

Motorcycle m = new Motorcycle("Pulsar");

Car c = new Car("Jazz", "Petrol");

//m.Calculate();
//c.Calculate();

v = m;

v.Calculate();

v = c;

v.Calculate();

Console.ReadLine();

16. Write a program in C# to build a class which implements an interface which is already
existing.

using System;

class MyClone : ICloneable

private int data1;

private String data2;

public MyClone()

data1 = 0;

data2 = "";

public MyClone(int d1, String d2)

data1 = d1;

data2 = d2;

public object Clone()

MyClone ob = new MyClone();

ob.data1 = data1;
ob.data2 = data2;

return ob;

public override String ToString()

String str = "data-1 : " + data1 + " data-2 : " + data2;

return str;

class Demo

public static void Main()

MyClone a = new MyClone(47, "Sharath");

Console.WriteLine("Object A: \n" + a);

MyClone b = (MyClone)a.Clone();

Console.WriteLine("\nObject B After Cloning: \n" + b);

Console.ReadLine();

17. Write a program to illustrate the use of different properties in C#.

using System;

class student

private String usn;

private String Name;

private double perc;

public String USN

get { return usn; }

}
public string name

set { Name = value; }

public double percentage

get { return perc; }

set { perc = value; }

public student(String usn)

this.usn = usn;

public void show()

Console.WriteLine("Usn : " + usn + "\nName : " + Name + "\nPecentage : " + perc);

public class Demo

public static void Main()

student s = new student("1RV07MCA47");

s.name = "Sharath";

s.percentage = 79.0;

s.show();

18. Demonstrate arrays of interface types with a C# program.


using System;

namespace InterfaceArray

public interface IShape

void Calculate();

void Display();

public class Rectangle : IShape

private double Area;

private double Length;

private double Breadth;

public Rectangle()

this.Length = 0;

this.Breadth = 0;

public Rectangle(double l, double b)

this.Length = l;

this.Breadth = b;

public void Calculate()

this.Area = this.Length * this.Breadth;

public void Display()

Console.WriteLine("Area of Rectangle is : " + this.Area);

}
public class Circle : IShape

private double Area;

private double Radius;

public Circle()

this.Radius = 0;

public Circle(double s)

this.Radius = s;

public void Calculate()

this.Area = 3.1416 * this.Radius * this.Radius;

public void Display()

Console.WriteLine("Area of Circle is : " + this.Area);

public class Program

public static void Main(string[] args)

IShape[] s = { new Rectangle(10, 20), new Circle(40) };

for (int i = 0; i < s.Length; i++)

s[i].Calculate();

s[i].Display();

Console.ReadLine();
}

Potrebbero piacerti anche