Professional Documents
Culture Documents
LABORATORY MANUAL
DESIGN AND ANALYSIS OF ALGORITHM LABORATORY
[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2015 -2016)
15CSL47
PREPARED BY
Mission
To achieve academic excellence in science, engineering and technology through
dedication to duty, innovation in teaching and faith in human values.
To enable our students to develop into outstanding professional with high ethical
standards to face the challenges of 21st century.
To provide educational opportunities to the deprived and weaker section of the
society to uplift their socio-economic status.
Vision
To empower students through wholesome education and enable the students to develop
into highly qualified and trained professionals with ethics and emerge as responsible
citizen with broad outlook to build a vibrant nation.
Mission
To provide excellent technical knowledge and computing skills to make the
graduates globally competitive with professional ethics.
To involve in research activities and be committed to lifelong learning to make
positive contributions to the society.
Vision
To advance the intellectual capacity of the nation and the international community by
imparting knowledge to graduates who are globally recognized as innovators,
entrepreneur and competent professionals.
HKBK COLLEGE OF ENGINEERING
(Affiliated to VTU, Belgaum and Approved by AICTE)
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Programme Outcomes
a. Engineering Knowledge: Apply knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering
problems.
b. Problem Analysis: Identify, formulate, research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences
c. Design/ Development of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet specified needs with
appropriate consideration for public health and safety, cultural, societal and
environmental considerations.
d. Conduct investigations of complex problems using research-based knowledge and
research methods including design of experiments, analysis and interpretation of data
and synthesis of information to provide valid conclusions.
e. Modern Tool Usage: Create, select and apply appropriate techniques, resources and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an under- standing of the limitations.
f. The Engineer and Society: Apply reasoning informed by contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to professional engineering practice.
g. Environment and Sustainability: Understand the impact of professional engineering
solutions in societal and environmental contexts and demonstrate knowledge of and
need for sustainable development.
h. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of engineering practice.
i. Individual and Team Work: Function effectively as an individual, and as a member
or leader in diverse teams and in multi disciplinary settings.
j. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as being able to comprehend and
write effective reports and design documentation, make effective presentations and give
and receive clear instructions.
k. Life-long Learning: Recognize the need for and have the preparation and ability to
engage in independent and life- long learning in the broadest context of technological
change.
l. Project Management and Finance: Demonstrate knowledge and understanding of
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
Programme Specific Outcomes
Course objectives:
This course will enable students to
Design and implement various algorithms in JAVA
Employ various design strategies for problem solving.
Measure and compare the performance of different algorithms
List of Experiments
Subject Code 15CSL47 IA Marks 20
S.No Questions- DAA-1
1. Write a Java program to print 'Hello' on screen and then print your name on a separate line
2. Write a program to print the factorial of 4
3. Write a Java Program to compute the area and perimenter of a circle by reading its radius as a
command line argument.
4. Write a program in Java to compute the sum of the digits of a given integer. Remember, your
integer should not be less than the five digits. (e.g., if input is 23451 then sum of the digits of
23451will be 15)
5. Write a program in Java to reverse a given number and check for palindrome and display
appropriate message.
6. Write a java program to find maximum element in an array?
7. Write a java program to sort the elements of the array using selection sort?
8. a. Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone Write a Java program to create nStuden8tobjects and print the
USN, Name, Branch, and Phone of these objects with suitable heading
s.
b. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.
9. a. Write a Java program to read two integers a andb. Compute a/b and print, when b is
not zero. Raise an exception when b is equal to zero
b. Write a Java program that implements a multi-thread application that hash tree
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number and prints; third thread will print the value of cube
of the number.
10. Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n > 5000 and record the time taken to sort.
Plot a graph of the time taken versus n on graph sheet. The elements can be read from a file
or can be generated using the random number generator. Demonstrate using Java how the
divideand-conquer method works along with its time complexity analysis: worst case,
average case and best case.
11. Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method (b)
Greedy method.
12. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.
Implement program in java language.
13. Find Minimum Cost Spanning Tree of a given undirected graph using Prim's algorithm
Implement program in java language.
14. Write a Java Applet program which reads your name and address in different text fields and
when a button named find is pressed the sum of the length of characters in name and address
is displayed in another text field. Use appropriate colors, layout to make your applet look
good.
15. Write a Java Applet program, which provides a text area with horizontal and vertical
scrollbars. Type some lines of text in the text area and use scrollbars for movements in the
text area. Read a word in a text field and find whether the word is in the content of the text
area or not.
Course Outcomes:
After studying this course, students will be able to
CO1. Design algorithms using appropriate design techniques (brute-force, greedy, dynamic
programming, etc.)
CO2. Implement a variety of algorithms such assorting, graph related, combinatorial, etc., in a
high level language.
CO3. Analyze and compare the performance of algorithms using language features.
CO4. Apply and implement learned algorithm design techniques and data structures to solve
realworldproblems
PO a B c D E f g h i j k l m n O
CO
1. Write a Java program to print 'Hello' on screen and then print your name on a separate
line
ALGORITHM
1. Algorithm
2. {
3. write “hello”
4. write “<name>”
5. }
PROGRAM:
Public class first {
Public static void main(String []args) {
System.out.println("Hello");
System.out.println("DAA");
}
}
OUTPUT:
Hello
DAA
PROGRAM :
public class fact {
}
}
OUTPUT:
factorial of 4 is 24
3. Write a Java Program to compute the area and perimenter of a circle by reading its radius
as a command line argument
Algorithm Area(r)
1. {
2. Read r
3. Area=3.14*r*r
4. Circumference=2*3.14*r
5. Write area and circumference
6. }
Program :
public class circle{
}
Output:
O1 Radius=5
Area of the circle is 78.5
circumference of the circle is 31.400000000000002
O2 Radius=0
Area of the circle is 0.0
circumference of the circle is 0.0
O3 Radius=3.5
Area of the circle is 38.465
circumference of the circle is 21.98
O4 Radius=4
Area of the circle is 50.24
circumference of the circle is 25.12
O5 Radius=2.8
Area of the circle is 24.6176
circumference of the circle is 17.584
4. Write a program in Java to compute the sum of the digits of a given integer. Remember,
your integer should not be less than the five digits. (e.g., if input is 23451 then sum of the
digits of 23451will be 15)
ALGORITHM sum(n)
1. {
2. sum:=0
3. Read num
4. If num>=9999;
while( num!=0 )
{
rem=n%10
sum+=rem
n=n/10
}
else
write “number should be 5digit”
5. }
PROGRAM:
importjava.util.Scanner;
classSumdigits
{
public static void main(String args[])throws IOException
{
Scanner input=new Scanner(System.in));
int num,rem;
CSE @ HKBKCE 10 2017-18
15CSL47 DAA Lab-1 Manual
int sum=0;
System.out.println("Enter a number");
num=input.nextInt();
if(num>=999)
{
while(num>0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
System.out.println("The sum of the digits"+sum);
}
else
{
System.out.println(“it should be a 5 digit number”);
}
}
}
OUTPUT:
O1 Enter a number
122
Output:
It should be a 5 digit number
O2 Enter a number
23415
Output:
The sum of the digits is:15
O3 Enter a number
234165
Output:
The sum of the digits is:21
O4 Enter a number
67854
Output:
The sum of the digits is:30
O5 Enter a number
56713
Output:
The sum of the digits is:22
5. Write a program in Java to reverse a given number and check for palindrome and display
appropriate message.
ALGORITHM reverse ()
// to reverse a given number and check for palindrome
{
Read num
Orig := num
While num> 0
{ Rem:= num%10
Rev:=rev*10+rem;
Num:=num/10;
}
Write rev
If rev == orig
Write “the number is palindrome”
Else
Write “the number is not palindrome”
}
PROGRAM:
importjava.util.Scanner;
publicclass reverse {
publicstaticvoid main(String[] args)
{
Scanner input=newScanner(System.in);
intnum,rem,orig;
int rev=0;
System.out.println("Enter a number");
num=input.nextInt();
orig=num;
while(num>0)
{
rem=num%10;
rev=rev*10+rem;
CSE @ HKBKCE 12 2017-18
15CSL47 DAA Lab-1 Manual
num=num/10;
}
System.out.println("The reverse of the digits"+sum);
if(rev==orig)
System.out.println("the number is a palindrome");
else
System.out.println("the number is not a palindrome");
}
}
OUTPUT:
O1 Enter a number
123
The reverse of the digits 321
the number is not a palindrome
O2 Enter a number
0
The reverse of the digits0
the number is a palindrome
O3 Enter a number
5335
The reverse of the digits 5335
The number is a palindrome
O4 Enter a number
9999
The reverse of the digits 9999
the number is a palindrome
O5 Enter a number
1231
The reverse of the digits1321
The number is not a palindrome
5 for i := 2 to n do
6 if A[i] > Result then Result := A[i];
7 return Result;
8}
PROGRAM:
importjava.io.*;
importjava.util.Scanner;
class maximum
{
int Max(int a[], int n)
{
int max=a[1];
for(int i=2;i<=n;i++)
if(a[i]>max) max=a[i];
return max;
}
7. Write a Java program to sort the elments in an array using selection sort.
for(int i=1;i<=n;i++)
{
int j=i;
for(int k=i+1;k<=n;k++)
if(a[k]<a[j]) j=k;
int t=a[i];
a[i]=a[j];
a[j]=t;
}
System.out.println("the sorted elemnts are:");
for(int i=1;i<=n;i++)
System.out.println(a[i]);
}
int n=in.nextInt();
System.out.println(" enter the elments to be sorted");
for(int i=1;i<=n;i++)
a[i]=in.nextInt();
System.out.println(" the elments to be sorted are:");
for(int i=1;i<=n;i++)
System.out.println(a[i]);
OUTPUT:
O1: enter the no of elements
5
enter the elements to be sorted
10 4 8 3 1
the elements to be sorted are
10
4
8
3
1
The sorted elements are:
1
3
4
8
10
4
enter the elements to be sorted
49 82 33 16
the elements to be sorted are
49
82
33
16
The sorted elements are:
16
33
49
82
8. A. Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create nStudentobjects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.
ALGORITHM StudentDetails
//display the student details with headings
{
Read n
for i:= 1 to n do
Read usn, name, branch phone number
for i:= 1 to n do
Write usn, name, branch phone number
}
PROGRAM:
importjava.io.*;
importjava.util.Scanner;
class StudentDetails
{
publicstaticvoid main(String s[])
{
Scanner in = newScanner(System.in);
System.out.println("enter the number of students");
int n=in.nextInt();
Student students[] = new Student[n];
class Student
{
String name;
String usn;
String branch;
intphno;
}
OUTPUT:
8. B.Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.
ALGORITHM: push(item)
// push element to top of stack
{
If top== size-1 then Write “stack full”
Else
{
Top:= top+1
S[top]:= item
}
}
ALGORITHM: pop()
// pops element from top of stack
{
If top==-1 then Write “stack empty”
Else
{
Itemdel:=S[top]
Top:=top-1
}
}
ALGORITHM: Diplay()
// diplay element in stack
{
For i:= 0 to top do
Write s[i];
}
ALGORITHM main ()
{
While true do
{ Write 1.push, 2.Pop, 3.Display, 4. Exit
Read choice
Case
{ :1: push
:2: pop
: 3: display
: 4: exit
}}
PROGRAM:
CSE @ HKBKCE 23 2017-18
15CSL47 DAA Lab-1 Manual
importjava.io.*;
importjava.util.Scanner;
publicclass stack {
int size=5;
int top;
int s[]= newint[size];
stack()
{
top=-1;
}
int pop()
{
if (top==-1)
{
System.out.println("Stack is Empty ");
return 0;
}
else
return s[top--];
}
void display()
{
if (top==-1)
System.out.println("Stack is Empty ");
else
{
for(inti=top;i>=0;i--)
System.out.println(s[i]);
}
}
publicstaticvoid main(String[] args)
CSE @ HKBKCE 24 2017-18
15CSL47 DAA Lab-1 Manual
{
stack s1 = new stack();
while(true)
{
System.out.println("1.push 2.pop, 3. display, 4. Exit");
System.out.println("Enter the Choice");
Scanner in= newScanner(System.in);
intch=in.nextInt();
switch(ch)
{
case 1: System.out.println("Enter the item");
int item=in.nextInt();
s1.push(item);break;
case 2: intitemdel=s1.pop();
if(itemdel!=0)
System.out.println("The item deleted is "+itemdel);
break;
case 3:s1.display(); break;
default:System.exit(0);
}
}
}
}
OUTPUT:
O1
1.push 2.pop, 3. display, 4. Exit
Enter the Choice
2
Stack is Empty
O2
1.push 2.pop, 3. display, 4. Exit
Enter the Choice
1
Enter the item
CSE @ HKBKCE 25 2017-18
15CSL47 DAA Lab-1 Manual
O3
1.push 2.pop, 3. display, 4. Exit
Enter the Choice
3
Elemensts are
8
9
7
CSE @ HKBKCE 26 2017-18
15CSL47 DAA Lab-1 Manual
6
4
O4
1.push 2.pop, 3. display, 4. Exit
Enter the Choice
2
The item deleted is 8
O5
1.push 2.pop, 3. display, 4. Exit
Enter the Choice
3
7
6
4
9. A. Write a Java program to read two integers a and b. Compute a/b and print, when b is
not zero. Raise an exception when b is equal to zero.
ALGORITHM div3a()
{
Read a, b
If b! =0 then
{
c=a/b;
Write c;
}
Else
Write exception “b is equal to zero“
}
CSE @ HKBKCE 27 2017-18
15CSL47 DAA Lab-1 Manual
PROGRAM:
importjava.io.*;
importjava.util.Scanner;
class div3a
{
publicstaticvoid main(String s[])
{
}
}
OUTPUT:
9.B. Write a Java program that implements a multi-thread application that hashtree threads.
First thread generates a random integer for every 1 second; second thread computes the
square of the number and prints; thirdthread will print the value of cube of the number
ALGORITHM multithread ()
{
Thread 1: generate random number num
Thread 2: write num*num
Thread 3: write num*num*num
}
PROGRAM:
importjava.util.Random;
class square extends Thread
{
publicint x;
public square(int x)
{
this.x = x;
}
publicvoid run()
{
System.out.println("New Thread -" +" Number generated is " + x + " square of num is: " + x
* x);
}
}
class cube extends Thread
{
publicint x;
public cube(int x)
{
this.x = x;
}
publicvoid run()
{
OUTPUT:
O1.
CSE @ HKBKCE 30 2017-18
15CSL47 DAA Lab-1 Manual
O2.
Main Thread - Generated Number is 68
New Thread - Number generated is 68 square of num is: 4624
New Thread - Number Generated is 68 cube of num is: 314432
O3.
Main Thread -Generated Number is 99
New Thread - Number generated is 99 square of num is: 9801
New Thread - Number Generated is 99 cube of num is: 970299
--------------------------------------
O4.
Main Thread -Generated Number is 25
New Thread - Number generated is 25 square of num is: 625
New Thread - Number Generated is 25 cube of num is: 15625
O5.
Main Thread - Generated Number is 20
New Thread - Number generated is 20 square of num is: 400
New Thread - Number Generated is 20 cube of num is: 8000
--------------------------------------
10. Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n > 5000 and record the time taken to
sort. Plot a graph of the time taken versus n on graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divide and-conquer method works along with its time complexity analysis: worst
case, average case and best case.
ALGORITHM QuickSort(a,p,q)
{
// Sorts the elements a[p],……,a[q] which reside in the global array a[1 : n] into //ascending order.
{
if( p < q) then // if there are more than one element// divide P into two sub problems
{
j=Partition (a, p,q+1);
2. QuickSort (p, j 1);
3. QuickSort (j + 1, q);
4. }
5. }
Partition (a, m, p)
2. {
3. v = a[m];i=m; j=p;
4. repeat
5. {
repeati=i+1;
until a[i] >=v;
repeat j = j1;
until a[j] <=v;
if i< j then exchange A[i] ↔ A[j]
} until ( i>= j);
a[m]=a[j]; a[j]=v; return j;
}
PROGRAM:
importjava.util.Scanner;
publicclass MyQuickSort1 {
publiclong a[];
publicvoid quicksort1( long [] inputArr, int low, int high) {
int j;
if(low < high)
{
j=partition1(inputArr,low,high);
quicksort1(inputArr,low,j-1);
quicksort1(inputArr,j+1,high);
}
key=a[low];
i=low+1;
j=high;
while(i<j)
{
while (i<high && a[i]<=key)
i++;
while (a[j]>key)
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
sorter.quicksort1(input,0,n-1);
longendtime= System.currentTimeMillis();
longtotaltime= endtime-startime;
for(int j=0;j<n;j++)
System.out.println(input[j]);
System.out.println("Total time required for execution=" + totaltime +"ms");;
System.out.println("the best case and average case time complexity = “
+n*Math.log(n));
System.out.println("the worst case time complexity = " +n*n);
}
}
OUTPUT:
O1.
N=5000
Total time required for execution=3ms
The best case and average case time complesity = 42585.96595708119
The worst case time complexity = 25000000
O2.
N=6000
Total time required for execution=8ms
The best case and average case time complesity = 52197.08848926115
The worst case time complexity = 36000000
O3.
N=7000
Total time required for execution=14ms
The best case and average case time complesity = 61975.657996262154
The worst case time complexity = 49000000
O4.
N=8000
Total time required for execution=16ms
The best case and average case time complesity = 71897.57456529578
The worst case time complexity = 64000000
O5.
N=10000
Total time required for execution=18ms
The best case and average case time complesity = 92103.40371976183
CSE @ HKBKCE 34 2017-18
15CSL47 DAA Lab-1 Manual
11. A.Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method
ALGORTIHM:
Input: S, a set of n items as described earlier, W the total weight of the knapsack. (Assume that the
weights and values are stored in separate arrays named w and v, respectively.)
Output: The maximal value of items in a valid knapsack.
int w, k;
2. for (w=0; w <= W; w++)
3. B[w] = 0
4. for (k=0; k<n; k++) {
5. for (w = W; w>= w[k]; w--)
6. if (B[w – w[k]] + v[k]> B[w])
7. B[w] = B[w – w[k]] + v[k]
PROGRAM:
import java.util.Scanner;
class knapsack_Dp1
{
}
}
int j=W;
int x[]=new int[100];
for(i=1;i<=n;i++)
x[i]=0;
i=n;
while(j!=0&&i!=0)
{
if(K[i][j]!=K[i-1][j])
{
x[i]=1;
j=j-wt[i];
i--;
}
else
i--;
}
System.out.println("Items included are\n");
System.out.println("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i]==1)
System.out.println((++count)+ "\t"+wt[i]+ "\t"+val[i]);
System.out.println("Total profit = "+K[n][W]);
int W = sc.nextInt();
k.knapSack1(W, wt, val, n);
}
}
OUTPUT:
O1
Enter the number of items:
4
Enter the items weights:
7345
Enter the items values:
42 12 40 77
Enter the maximum capacity:
10
Items included are
Sl.no weight profit
1 4 40
2 5 77
Total profit = 117
O2
Enter the number of items:
2
Enter the items weights:
5 10
Enter the items values:
345 4
Enter the maximum capacity:
8
Items included are
Sl.no weight profit
1 5 345
Total profit = 345
O3
Enter the number of items:
5
Enter the items weights:
26734
Enter the items values:
23 565 234 456 0
Enter the maximum capacity:
15
Items included are
Sl.no weight profit
1 2 23
2 6 565
3 3 456
O4
Enter the number of items:
4
Enter the items weights:
7354
Enter the items values:
42 14 40 25
Enter the maximum capacity:
10
Items included are
Sl.no weight profit
1 5 40
2 4 25
Total profit = 65
O5
Enter the number of items:
3
Enter the items weights:
18 15 10
Enter the items values:
25 25 15
Enter the maximum capacity:
CSE @ HKBKCE 38 2017-18
15CSL47 DAA Lab-1 Manual
25
Items included are
Sl.no weight profit
1 15 25
2 10 15
Total profit = 40
11. B. Implement in Java, the 0/1 Knapsack problem using Greedy method.
ALGORITHM:
GreedyKnapsack(m,n)
//p[1;n] and w[1:n] contains the profits and weights respectively of the n objects ordered such that
//p[i]/w[i] p[i+1]
// m is the knapsack size and x[1:n] is the solution vector.
{
1. for i:= 1 to n do
2. x[i]=0 // initialize x
3. u:=m;
4. for i:=1 to n do;
5. {
6. if (w[i] > U ) then break;
7. x[i]:=1.0; U=U-w[i];
8. }
9. If(in) then x[i]:=U/w[i];
}
PROGRAM:
importjava.util.Scanner;
public class GreedyKnapsack
{
int[] profit;
int[] weight;
int[] take = newint[100];
public void unitPriceOrder()
{
for (inti = 0; i<profit.length; i++)
{
for (int j = 0; j < (profit.length - i-1); j++)
{
double x=profit[j] / weight[j];
CSE @ HKBKCE 39 2017-18
15CSL47 DAA Lab-1 Manual
OUTPUT:
O1
Enter the number of items:
3
Enter the items weights:
18 15 10
Enter the items values:
24 25 15
Enter the maximum capacity:
25
Optimal soluation to knapsack instance with values given as follows : m=25
item | profit | weight | Unit Price | Take weight
0 15 10 1 1
1 25 15 1 1
2 24 18 1 0
O2
Enter the number of items:
4
Enter the items weights:
7345
Enter the items values:
42 12 40 25
Enter the maximum capacity:
10
O3
Enter the number of items:
5
Enter the items weights:
26734
Enter the items values:
23 565 234 456 0
Enter the maximum capacity:
15
Optimal soluation to knapsack instance with values given as follows : m=25
item | profit | weight | Unit Price | Take weight
0 456 3 152 1
1 565 6 94 1
2 234 7 33 0
3 23 2 11 1
4 0 4 0 1
O4
Enter the number of items:
CSE @ HKBKCE 42 2017-18
15CSL47 DAA Lab-1 Manual
3
Enter the items weights:
2 3 5
Enter the items values:
23 56 43
Enter the maximum capacity:
7
O5
Enter the number of items:
2
Enter the items weights:
5 10
Enter the items values:
345 43
Enter the maximum capacity:
8
12. Find Minimum Cost Spanning Tree of a given undirected graph using kruskal’s
ALGORITHM:
Algorithm KruskalMST
2. Input: A weighted, connected and undirected graph G = (V,E).
3. Output: A minimal spanning tree of G.
4. T=f.
5. while T contains less than n1edgesdo
6. Choose an edge (v,w) from E of the smallest weight.
CSE @ HKBKCE 43 2017-18
15CSL47 DAA Lab-1 Manual
PROGRAM:
import java.util.Scanner;
class Edge
{
int v1,v2,wt; // wt is the weight of the edge
}
class kruskals
{
public static void main(String args[])
{
int i,j,mincost=0;
Scanner br=new Scanner(System.in);
System.out.println(" Enter no.of vertices:");
int v=br.nextInt();
System.out.println(" Enter no.of edges:");
int e=br.nextInt();
Edge ed[]=new Edge[e+1];
for(i=1;i<=e;i++)
{
ed[i]=new Edge();
System.out.println(" Enter the vertices and the weight of edge "+(i)+ ":");
ed[i].v1=br.nextInt();
ed[i].v2=br.nextInt();
ed[i].wt=br.nextInt();
}
for(i=1;i<=e;i++) // sorting the edges in ascending order
for(j=1;j<=e-1;j++)
{
if(ed[j].wt>ed[j+1].wt)
{
Edge t=new Edge();
t=ed[j];
ed[j]=ed[j+1];
ed[j+1]=t;
}
}
int visited[]=new int[v+1]; // array to check whether the vertex is visited or not
for(i=1;i<=v;i++)
visited[i]=0;
System.out.println("MINIMUM SPANNING TREE :");
for(i=1;i<=e;i++)
{
if(i>v)
break;
else if( visited[ed[i].v1]==0 || visited[ed[i].v2]==0)
{
System.out.println(ed[i].v1+ "-"+ ed[i].v2);
visited[ed[i].v1]=visited[ed[i].v2]=1;
mincost+=ed[i].wt;
}
}
System.out.println("MINIMUM COST = " +mincost);
}
}
OUTPUT :
Enter no.of vertices:
4
Enter no.of edges:
5
Enter the vertices and the weight of edge 1:
121
Enter the vertices and the weight of edge 2:
132
Enter the vertices and the weight of edge 3:
141
Enter the vertices and the weight of edge 4:
233
Enter the vertices and the weight of edge 5:
342
MINIMUM SPANNING TREE :
1-2
1-4
1-3
MINIMUM COST = 4
13. Find Minimum Cost Spanning Tree of a given undirected graph using prim’s algorithm
ALGORITHM:
Prim(E,cost,n,t)
//E is the set of edges in G.cost [1:n,1:n] is the cost
//adjacency matrix of an n vertex graph such that cost[i,j] is
//either a positive real number or infinity if no edge of (i,j) exists
//a minimum spanning tree is computed and stored as a set of
//edges in the array t[1:n-1,1:2] . (t[i,1],t[i,2] is an edge in the minimum cost spanning
//tree .The final cost is returned.
2. {
3. Let (k,l) be an edge of minimum cost in Ei
4. mincost :=cost[k,l];
5. t[1,1]:=k;t[1,2]:=l;
6. for i:=1 to n do //initialize near
7. if(cost[i,l]<cost[i,k])
8. then near[i] :=l;
9. else
10. near[i]:=k;
11. near[k]:=near [l]:=0;
12. for i:=2 to n-1 do
13. {
14. // Find n-2 additional edges for t
15. Let j be an index such that near[j]!=0and
16. Cost[j,near[j]] is minimum
17. t[i,1]:=j;t[i,2]:=near[j];
18. mincost :=mincost+cost[j,near[j]];
19. near[j]:=0;
20. for k:=1 to n do //Update near[].
21. if((near[k]!=0) and (cost[k,near[k]]>cost[k,j]))
22. then near[k]:=j;
23. }
24. return mincost;
25. }
CSE @ HKBKCE 46 2017-18
15CSL47 DAA Lab-1 Manual
PROGRAM:
importjava.util.Scanner;
publicclassprims {
publicstaticvoid main(String args[])
{
int f[]= newint[10];
intmin,ne,mincost;
int c[][]= newint[10][10];
inta,b,i,j;
ne=1;
mincost=0;
a=0;
b=0;
Scanner in= newScanner(System.in);
System.out.println("enter n\n");
int n=in.nextInt();
System.out.println("enter cost adj. matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
c[i][j]= in.nextInt();
if(c[i][j]==0)
c[i][j]=999;
}
for(i=1;i<=n;i++)
f[i]=0;
f[1]=1;
while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(c[i][j]<min && f[i]==1)
{
min=c[i][j];
a=i;b=j;
}
if( f[b]==0)
{
CSE @ HKBKCE 47 2017-18
15CSL47 DAA Lab-1 Manual
ne++;
System.out.println("\nedge ->\t"+ a + "--" + b +
"\t Min cost "+min);
mincost+=min;
f[b]=1;
}
c[a][b]=c[b][a]=999;
}
System.out.println("\nMINCOST=\n"+ mincost);
}
}
OUTPUT:
O1
enter n
4
enter cost adj. matrix
0121
1 0 3 999
2302
1 999 2 0
MINCOST= 4
O2
enter n
3
enter cost adj. matrix
0 999 1
8 0 999
999 6 0
MINCOST= 7
O3.
enter n
3
enter cost adj. matrix
0 1 0
10 0 1
999 8 0
MINCOST= 2
O4
enter n
2
enter cost adj. matrix
999 4
5 6
MINCOST= 4
O5
enter n
5
enter cost adj. matrix
5 1 2 3 4
999 0 1 2 999
7 8 4 999 4
8 6 999 0 1
CSE @ HKBKCE 49 2017-18
15CSL47 DAA Lab-1 Manual
0 1 0 999 999
MINCOST= 5
14. Write a Java Applet program which reads your name and address in different text fields
and when a button named find is pressed the sum of the length of characters in name and
address is displayed in another text field. Use appropriate colors, layout to make your applet
look good.
ALGORITHM-
1. Create a java file with .java extension.
2. Create a class that extends applet class and implements action listener.
3. Write an applet code that cretaes 3 text fields and button.
4. Save and compile the program using command
javac filename.java.
5. Run the code using appletviewer as
appletviewer filename.java
PROGRAM
Import java.applet.*;
Import java.awt.*;
Import java.awt.event.*;
/*<applet code="nameaddr" width=800 height=1000></applet>*/
public class nameaddr extends Applet implements ActionListener {
public void init()
{
label1 = new Label();
label2 = new Label();
label3 = new Label();
t1 = new TextField(30);
t2 = new TextField(40);
t3 = new TextField(45);
b1 = new Button("Total");
setBackground(new Color(0, 153, 102));
label1.setText("Name");
add(label1);
add(t1);
label2.setText("Address");
add(label2);
add(t2);
b1.addActionListener(this);
add(b1);
label3.setText("\nTotal length");
add(label3);
add(t3);
}
public void actionPerformed(ActionEvent ae)
{
int a=t1.getText().length();
a+=t2.getText().length();
t3.setText(Integer.toString(a));}
Label label1;Label label2; Label label3; TextField t1; TextField t2; TextField t3; Button b1;
}
OUTPUT:
15. Write a Java Applet program, which provides a text area with horizontal and vertical
scrollbars. Type some lines of text in the text area and use scrollbars for movements in the text
area. Read a word in a text field and find whether the word is in the content of the text area or
not.
ALGORITHM
1. Create a java file with .java extension.
2. Create a class that extends applet class and implements action listener.
3. Write an applet code that cretaes a textarea and text fields and button.
4. Save and compile the program using command
CSE @ HKBKCE 52 2017-18
15CSL47 DAA Lab-1 Manual
javac filename.java.
5. Run the code using appletviewer as
appletviewer filename.java
PROGRAM
importjava.applet.*;
importjava.awt.*;
importjava.awt.event.*;
/*<APPLET Code="AppletWithTxtFlds" Width=500 Height=200>
</APPLET>*/
public class AppletWithTxtFlds extends Applet implements ActionListener {
public void init()
{
Label label1 = new Label("enter multiple line text: ");
taDetails = new TextArea("", 3, 40);
Label label2 = new Label("enter the word to be searched: ");
textField1 = new TextField(40);
Label label3 = new Label("the word to be searched is: ");
textField2 = new TextField(40);
swapEm = new Button("find");
swapEm.addActionListener(this);
add(label1);
add(taDetails);
add(label2);
add(textField1);
add(swapEm);
add(label3);
add(textField2);
}8
{
textField2.setText("not found");
}
}
catch(Exception x)
{
System.out.println("Exception caught ");
}
}
TextArea Details;
TextField textField1, textField2;
Button swapEm;
}
OUTPUT:
Word found
VIVA QUESTIONS:
SL.NO QUESTION
1. What is object oriented programming? How is it different form procedure oriented
programming
2. Describe the structure of a typical Java program?
3. What is a class?
4. What are objects? How are they created?
5. How are arrays created and accesed in java?
6. What is an exception?
7. How do we define try and catch block?
8. What is a thread?
9. What are the two ways of implementing a thread?
10. What is stack?
11. What is an algorithm?
12. What is a pseudocode?
13. Name some important problem types in algorithm
14. What is an adjacency matrix?
15. What is an adjacency Linked list
16. Define weighted digraph
17. What is a tree?
18. What is a Rooted tree?
19. What are the two kinds of efficiency
20. Define time and space efficiency
21. What is a basic operation?
22. How we estimate the running time
23. Explain Brute force method. Give an example
24. Explain Divide and conquer method. Give an example
25. Explain Decrease and conquer method. Give an example
26. Explain Dynamic programming method. Give an example
27. Explain greedy technique. Give an example
28. Define Order of growth
29. What is an asymptotic notation?
30. Explain basic efficiency classes?
31. What is Master theorem?
32. What is the time complexity for Mergesort, Quicksort, Binary search, Selection
sort, heap sort
33. Explain the 3 major variations of decrease and conquer
34. State the 2 different types of heap construction?
35. What is transitive closure?
36. Explain warshall & floyds algorithm?
37. What is a spanning tree?
38. Differentiate Prims , Kruskals & Dijskstra’s algorithm
39. What is Bactracking?
40. What is Branch and bound technique?