O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

JAVA Program Examples

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
DESIGN AND ANALYSIS OF ALGORITHM LABORATORY
Chethan Raj C, Asst Professor Dept. of CSE Page 1
CHETHAN RAJ C,BE, M.Tech (Ph...
DESIGN AND ANALYSIS OF ALGORITHM LABORATORY
Chethan Raj C, Asst Professor Dept. of CSE Page 2
Compilation and execution of...
DESIGN AND ANALYSIS OF ALGORITHM LABORATORY
Chethan Raj C, Asst Professor Dept. of CSE Page 3
1. Suppose we write a java p...
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Próximos SlideShares
Java
Java
Carregando em…3
×

Confira estes a seguir

1 de 58 Anúncio
Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Semelhante a JAVA Program Examples (20)

Anúncio

Mais recentes (20)

JAVA Program Examples

  1. 1. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 1 CHETHAN RAJ C,BE, M.Tech (Ph.D) Dept. of CSE Execution Flow of Java Program Compiler: When executing (running), the compiler first parses (or analyzes) all of the language statements syntactically one after the other and then, in one or more successive stages or "passes", builds the output code, making sure that statements that refer to other statements are referred to correctly in the final code. Traditionally, the output of the compilation has been called object code or sometimes an object module . Interpreter: Programs written in a high level language are either directly executed by some kind of interpreter or converted into machine code by a compiler (and assembler and linker) for the CPU to execute. Therefore interpreter is a program that executes instructions written in a high level language. There are two ways to run programs written in a high-level language. The most common is to compile the program; the other method is to pass the program through an interpreter. Difference between Compiler and interpreter Compiler reads entire code at a time. Interpreter reads code line by line take more time to check. compiler execute whole program at a time while interpreter execute program line by line. Compiler required more memory while interpreter required less memory. The control structure can execute in compiler more efficiently while control structure can execute in interpreter less efficient Note: Bytecode make Java a platform independent language. (Platform Independent) Java Program Structure & Syntax Java programs usually has a structure like package, import statements, class declaration and many methods in the class. Java is both compiler and interpreter language. Compiler translates source code into byte code Interpreter generates machine code from byte code In general Java Program Execution consists of two steps namely: 1. Compilation 2. Interpretation Compilation: Compiler is a program helps to translate the Java source language into bytecode. At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the java code into bytecode. Assume the class name & file name assigned is simple.java
  2. 2. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 2 Compilation and execution of a Java program is two step process. During compilation phase Java compiler compiles the source code and generates bytecode. This intermediate bytecode is saved in form of a .class file. In second phase, Java virtual machine (JVM) also called Java interpreter takes the .class as input and generates output by executing the bytecode. Java is an object oriented programming language; therefore, a program in Java is made of one or more classes javac which is java compiler searches for the code structure like syntax of members like return type,data type of variables assigned etc. Interpretation: Interpreter is a program which implements the JVM specification and helps to actual helps to execute the bytecode. Java virtual machine interprets the bytecode. After java compilation the class file is generated which is in byte code form which JVM (Java virtual machine) can understand. At runtime, following steps are performed: Classloader: is the subsystem of JVM that is used to load class files. Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects. Interpreter: read bytecode stream then execute the instructions. JVM searches for main method,here starts the execution by JVM and all the methods which are to be executed has to be called in main method which JVM uses stack to pull in(For the methods to be executed) and pull out (for the methods already executed). JAVA is a compiled and interpreted language and not only just the interpreted language. The step by step execution of its program.
  3. 3. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 3 1. Suppose we write a java program and save it as “hello.java” in a folder somewhere on a hard disk. 2. The name of the java compiler is “javac”. For its compilation we have to write “javac hello.java” on the command line. 3. At this stage the high level code gets converted to the machine level code. Java converts it into a .class file as “hello.class” . This code is also known as a byte code because every instruction in this file is of 1 Byte. 4. This byte code can also be taken away on any other platform like Mac, Linux or Windows. It only takes a JVM of respective OS for its execution. Hence, JAVA is known as a first platform independent and architecturally neutral language. 5. Now, for its execution, interpreter is used. It is named as a “java” itself. For its interpretation, “java hello.java” should be used on the command line. It internally invokes class loader which is responsible for loading the „hello.class‟ file from hard disk to JVM‟s address space. 6. Here there comes a „Byte code verifier‟ which verifies the code to avoid run time failures. After successful verification, JVM executes the byte by byte code with the help of OS. Thus the whole java program gets executed by JVM and OS. While JVM acts as a mini OS for the java program and it concerns OS only when the instructions are not in its scope. The byte code is independent of the operating system or hardware. The same byte code will be executed by JVM running on any operating system / hardware. JVM, JRE and JDK Java Virtual Machine (JVM) is a program that runs pre compiled Java programs, which mean JVM executes .class files (byte-code) and produces output. The JVM is written for each platform supported by Java included in the Java Runtime Environment (JRE). The Oracle JVM is written in the C programming language. There are many JVM implementations developed by different organizations. They may somewhat differ in performance, reliability, speed and so. They can too differ in implementation specially in those features where Java specification does not mention implementation details of the feature. Garbage collection is the nice example which is left on vendor's choice and Java specification does not provide any implementation details. JRE is an implementation of the JVM which actually executes Java programs. It includes the JVM, core libraries and other additional components to run applications and applets written in Java. Java Runtime Environment is a must install on machine in order to execute pre compiled Java Programs. JRE is smaller than the JDK so it needs less disk space and it is so because JRE does not contain Java compiler and other software tools needed to develop Java programs. Java Development Kit(JDK) is needed for developing Java applications. It is a bundle of software that is used to develop Java based applications. It includes the JRE, set of API classes, Java compiler, Web start and additional files needed to write Java applets and applications. Conclusively, to compile and run Java program you would need JDK installed, while to run a pre compiled Java class file (byte-code) you would need JRE. JRE contains java Java interpreter but not javac the Java compiler.
  4. 4. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 4 Note: User can save a java source file by other name than the class name , but java interpreter reads the .class file of byte code for run or execute the code. In command prompt to run the code: To compile: javac Hard.java To execute: java Simple As shown above for Compilation File name is considered & for Interpretation Class name is considered. Hence it’s always better to give the file name same as class name. User can have multiple classes in a java source file Java Programming standard coding convention User has to follow the standard coding convention in order to any program (Syntax/Semantics). That standard convention improves the readability and maintainability of the code. For ex: To calculate the Square root the syntax is math.sqrt(4), math.max(95,75), math.min(5,7) Java Program Standard Coding Conventions
  5. 5. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 5 1) Comment Lines (optional) 2) Package Statement 3) Class name 4) Method name/Logic 5) Main Method (optional) If user is writing utility program (EJB) then main method is not required but all stand alone applications/program and the program running from command prompt then main method is compulsory. -->All class is part of package hence for good practice of java program always starts with package statement -->class name should have meaningful name and that represents the functionality of the class. -->In a program No instance variable (No instance Method) then declare that method as static method -->If the instance variable is available then the instance method is called by creating a object of that class. How to run Java Program: 1) User can run java program from the command prompt .class file. (java Commnd). 2) User can run java program from the command prompt the .jar file. 3) User can run java program by Double click a .jar file. 3) User can run java program by Double click a .batch file. JDK: Developing a java program/Application (Phase-I) and executing (run- Phase 11) the required environement is JDK JDK provides an environment to develop and run the java application. Ex: Develper User (Software Development) JRE: If user want to run only the java application then required environment is JRE Ex: Client Users (Software Access) JVM: JRE is responsible for run the application but within JRE , JVM is respondible to run the java program Line by line (JVM is interpreter)
  6. 6. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 6 JDK=JRE + Development Tools (JRE is a part of JDK) JRE= JVM+ Library Classes (JVM is a part of JRE) JDK=JVM+JRE ==================== Java Compiler doesnt check for main method in class but in run time JVM checks for main method , if main method is not available then JVM raises an error No such method:main At run time JVM is responsibe for class contains main method or not =================== At run time JVM always searches the main method wit the prototype like of main method should public, static and return type is void , and name of main method is main and argument is string array. JVM always searches for main method is that, JVM is a software program and with JVM in this it is configured with the synatx PSVM(Sring args[]) User can change the main method with user defined name but the customization within JVM is required for main method (Default name is used). ===================== Public, void & Static: Public: In general JVM calls the main method, but to call the main method from anywhere by JVM, the main should be declared as public (Any directory/path/Location) Static: JVM calls the main method, Main method is class level method and not link wit objects i,e witout existing objects also JVM has to cal this main method & main method is no where related to any object hence static is required.(without object also main method has to execute) void:JVM calls the main method and main method wont return anything to JVM hence return type is void Main:Main is the name is configured with in the JVM Command line arguments The main method syntax is very strict no modifcation is allowed in it otherwise JVM raises an Run time exception, But some changes are aceptable.i e public and static are modifiers hence alter of modifiers doesnt affect in the syntax(any where is java is applicable) Void main ---No modifications are allowed
  7. 7. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 7 String can declare it in any acceptable form:string[] args, string []args, string args[] args is an name of an string array: In general instead of args user can take any valid java identifiers. String[] is replaced with var arg parameter (3 dots) --String... args Main method can declare with following modifiers. Main method can declare with final modifier keyword:Ex: Every Child class is depends parent class method Synchronized modifier is allowed:main method should be executed by only 1 thread at a time Strictfp modifier: Modifiers public class MyClass The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors. The modifiers are classifies into 2 types: 1. Access Modifiers - controls the access level 2. Non-Access Modifiers - do not control access level, but provides other functionality. Access Modifiers For classes, user can use either public or default: Modifier Description public The class is accessible by any other class default The class is only accessible by classes in the same package. This is used when User don't specify a modifier. User will learn more about packages in the Packages chapter For attributes, methods and constructors, User can use the one of the following: Modifier Description public The code is accessible for all classes private The code is only accessible within the declared class default The code is only accessible in the same package. This is used when User don't specify a modifier. User will learn more about packages in the Packages chapter protected The code is accessible in the same package and subclasses. User will learn more about subclasses and super classes in the Inheritance. Non-Access Modifiers For classes, User can use either final or abstract:
  8. 8. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 8 Modifier Description final The class cannot be inherited by other classes (User will learn more about inheritance in the Inheritance chapter) abstract The class cannot be used to create objects (To access an abstract class, it must be inherited from another class. User will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters) For attributes and methods, User can use the one of the following: Modifier Description final Attributes and methods cannot be overridden/modified static Attributes and methods belongs to the class, rather than an object abstract Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from). User will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters transient Attributes and methods are skipped when serializing the object containing them synchroni zed Methods can only be accessed by one thread at a time volatile The value of an attribute is not cached thread-locally, and is always read from the "main memory" Final If User don't want to override the existing attribute values, declare the attributes as final: Static A static method means that it can be accessed without creating an object of the class, unlike public : Abstract An abstract method belongs to an abstract class, and it does not have a body. The body is provided by the subclass: Lab Programs //All Programs are Verified by using the Ubuntu platform.User may practise the programs Using any Java IDE’s like Eclipse, Netbeans wit bit of modifications….. 1)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 nStudent objects and print the USN, Name, Branch, and Phone of these objects with suitable headings.*/ // Package Statement import java.util.Scanner; class StudentDetails
  9. 9. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 9 { String USN, Name, Branch, Phone; Scanner input = new Scanner(System.in); void read() { System.out.println("Enter the Student Detailsn"); System.out.println("Enter USN"); USN = input.nextLine(); System.out.println("Enter Name"); Name = input.nextLine(); System.out.println("Enter Branch"); Branch = input.nextLine(); System.out.println("Enter Phone"); Phone = input.nextLine(); } void display() { System.out.printf("%-20s %-20s %-20s %-20s", USN, Name, Branch, Phone); } } class Student1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter number of student details to be created"); int number = input.nextInt(); Student s[] = new Student[number]; // Read student details into array of student objects for (int i = 0; i < number; i++) { s[i] = new Student(); s[i].read(); } System.out.printf("----------The Entered Student details are--------------n"); // Display student information System.out.printf("%-20s%-20s%-20s%-20s","USN","NAME","BRANCH","PHONE"); for (int i = 0; i < number; i++) { System.out.println(); s[i].display(); } //input.close();//Terminates the input for the class
  10. 10. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 10 } } Output: CRC16@CRC:~/CRC17$ javac Student1.java CRC16@CRC:~/CRC17$ java Student1 Enter number of student details to be created 2 Enter the Student Details Enter USN 1 Enter Name A Enter Branch CSE Enter Phone 12345 Enter the Student Details Enter USN 2 Enter Name B Enter Branch CSE Enter Phone 6789 ----------The Entered Student details are-------------- USN NAME BRANCH PHONE 1 A CSE 12345 2 B CSE 6789 1)b Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to demonstrate its working. import java.util.*; class arrayStack { int arr[]; int top, max; arrayStack(int n) { max = n; arr = new int[max]; top = -1; }
  11. 11. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 11 void push(int i) { if (top == max - 1) System.out.println("Stack Overflow"); else arr[++top] = i; } void pop() { if (top == -1) { System.out.println("Stack Underflow"); } else { int element = arr[top--]; System.out.println("Popped Element: " + element); } } void display() { System.out.print("nStack = "); if (top == -1) { System.out.print("Emptyn"); return; } for (int i = top; i >= 0; i--) System.out.print(arr[i] + " "); System.out.println(); } } class Stack { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter Size of Integer Stack "); int n = scan.nextInt(); boolean done = false; arrayStack stk = new arrayStack(n); char ch; do {
  12. 12. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 12 System.out.println("nStack Operations"); System.out.println("1. push"); System.out.println("2. pop"); System.out.println("3. display"); System.out.println("4. Exit"); int choice = scan.nextInt(); switch (choice) { case 1: System.out.println("Enter integer element to push"); stk.push(scan.nextInt()); break; case 2: stk.pop(); break; case 3: stk.display(); break; case 4: done = true; break; default: System.out.println("Wrong Entry n "); break; } } while (!done); } } Output: CRC16@CRC:~/CRC17$ javac Stack.java CRC16@CRC:~/CRC17$ java Stack Enter Size of Integer Stack 3 Stack Operations 1. push 2. pop 3. display 4. Exit 2 Stack Underflow Stack Operations 1. push 2. pop 3. display 4. Exit 3
  13. 13. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 13 Stack = Empty Stack Operations 1. push 2. pop 3. display 4. Exit 1 Enter integer element to push 25 Stack Operations 1. push 2. pop 3. display 4. Exit 3 Stack = 25 Stack Operations 1. push 2. pop 3. display 4. Exit 1 Enter integer element to push 55 Stack Operations 1. push 2. pop 3. display 4. Exit 3 Stack = 55 25 Stack Operations 1. push 2. pop 3. display 4. Exit 2 Popped Element: 55
  14. 14. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 14 Stack Operations 1. push 2. pop 3. display 4. Exit 3 Stack = 25 Stack Operations 1. push 2. pop 3. display 4. Exit 1 Enter integer element to push 75 Stack Operations 1. push 2. pop 3. display 4. Exit 1 Enter integer element to push 35 Stack Operations 1. push 2. pop 3. display 4. Exit 1 Enter integer element to push 222 Stack Overflow Stack Operations 1. push 2. pop 3. display 4. Exit 3 Stack = 35 75 25
  15. 15. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 15 Stack Operations 1. push 2. pop 3. display 4. Exit 4 Programs Terminate 2)a Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a Java program to read and display at least 3 staff objects of all three categories.*/ import java.util.Scanner; class Staff { String StaffID, Name, Phone, Salary; Scanner input = new Scanner(System.in); void read() { System.out.println("Enter StaffID"); StaffID = input.nextLine(); System.out.println("Enter Name"); Name = input.nextLine(); System.out.println("Enter Phone"); Phone = input.nextLine(); System.out.println("Enter Salary"); Salary = input.nextLine(); } void display() { System.out.printf("n%-15s", "STAFFID: "); System.out.printf("%-15s n", StaffID); System.out.printf("%-15s", "NAME: "); System.out.printf("%-15s n", Name); System.out.printf("%-15s", "PHONE:"); System.out.printf("%-15s n", Phone); System.out.printf("%-15s", "SALARY:"); System.out.printf("%-15s n", Salary); } } class Teaching extends Staff { String Domain, Publication; void read_Teaching() {
  16. 16. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 16 super.read(); // call super class read method System.out.println("Enter Domain"); Domain = input.nextLine(); System.out.println("Enter Publication"); Publication = input.nextLine(); } void display() { super.display(); // call super class display() method System.out.printf("%-15s", "DOMAIN:"); System.out.printf("%-15s n", Domain); System.out.printf("%-15s", "PUBLICATION:"); System.out.printf("%-15s n", Publication); } } class Technical extends Staff { String Skills; void read_Technical() { super.read(); // call super class read method System.out.println("Enter Skills"); Skills = input.nextLine(); } void display() { super.display(); // call super class display() method System.out.printf("%-15s", "SKILLS:"); System.out.printf("%-15s n", Skills); } } class Contract extends Staff { String Period; void read_Contract() { super.read(); // call super class read method System.out.println("Enter Period"); Period = input.nextLine(); } void display() { super.display(); // call super class display() method
  17. 17. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 17 System.out.printf("%-15s", "PERIOD:"); System.out.printf("%-15s n", Period); } } class Staffdetails { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter number of staff details to be created"); int n = input.nextInt(); Teaching steach[] = new Teaching[n]; Technical stech[] = new Technical[n]; Contract scon[] = new Contract[n]; // Read Staff information under 3 categories for (int i = 0; i < n; i++) { System.out.println("----------------Teaching Staff Details-----------------n"); System.out.println("Enter Teaching staff information"); steach[i] = new Teaching(); steach[i].read_Teaching(); } for (int i = 0; i < n; i++) { System.out.println("----------------Technical Staff Details----------------n"); System.out.println("Enter Technical staff information"); stech[i] = new Technical(); stech[i].read_Technical(); } for (int i = 0; i < n; i++) { System.out.println("----------------Contract Staff Details------------------n"); System.out.println("Enter Contract staff information"); scon[i] = new Contract(); scon[i].read_Contract(); } // Display Staff Information System.out.println("n STAFF DETAILS: n"); System.out.println("-----TEACHING STAFF DETAILS-----n "); for (int i = 0; i < n; i++) { steach[i].display(); }
  18. 18. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 18 System.out.println(); System.out.println("-----TECHNICAL STAFF DETAILS-----n"); for (int i = 0; i < n; i++) { stech[i].display(); } System.out.println(); System.out.println("-----CONTRACT STAFF DETAILS-----n"); for (int i = 0; i < n; i++) { scon[i].display(); } input.close(); } } Output: CRC@CRC-OptiPlex-3050:~$ javac Staffdetails.java CRC@CRC-OptiPlex-3050:~$ java Staffdetails Enter number of staff details to be created 2 ----------------Teaching Staff Details------------------- Enter Teaching staff information Enter StaffID 1 Enter Name A Enter Phone 123 Enter Salary 45678 Enter Domain CS Enter Publication Springer ----------------Teaching Staff Details------------------- Enter Teaching staff information Enter StaffID 2 Enter Name B Enter Phone 123 Enter Salary 456778 Enter Domain EC
  19. 19. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 19 Enter Publication Journals ----------------Technical Staff Details------------------- Enter Technical staff information Enter StaffID 3 Enter Name C Enter Phone 123 Enter Salary 67890 Enter Skills Designer ----------------Technical Staff Details------------------- Enter Technical staff information Enter StaffID 4 Enter Name D Enter Phone 2345 Enter Salary 89076 Enter Skills Coding ----------------Contract Staff Details------------------- Enter Contract staff information Enter StaffID 5 Enter Name E Enter Phone 234 Enter Salary 89098 Enter Period 5 ----------------Contract Staff Details------------------- Enter Contract staff information Enter StaffID 6 Enter Name F Enter Phone 3456 Enter Salary
  20. 20. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 20 90989 Enter Period 7 STAFF DETAILS: -----TEACHING STAFF DETAILS----- STAFFID: 1 NAME: A PHONE: 123 SALARY: 45678 DOMAIN: CS PUBLICATION: Springer STAFFID: 2 NAME: B PHONE: 123 SALARY: 456778 DOMAIN: EC PUBLICATION: Journals -----TECHNICAL STAFF DETAILS----- STAFFID: 3 NAME: C PHONE: 123 SALARY: 67890 SKILLS: Designer STAFFID: 4 NAME: D PHONE: 2345 SALARY: 89076 SKILLS: Coding -----CONTRACT STAFF DETAILS----- STAFFID: 5 NAME: E PHONE: 234 SALARY: 89098 PERIOD: 5 STAFFID: 6 NAME: F PHONE: 3456 SALARY: 90989 PERIOD: 7 2)b Write a Java class called Customer to store their name and date_of_birth. The date_of_birth format should be dd/mm/yyyy. Write methods to read customer data as <name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer class considering the delimiter character as
  21. 21. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 21 “/”.By using object references different class members are accessed by the main class under main function. import java.util.Scanner; import java.util.StringTokenizer; public class Customer { public static void main(String[] args) { String name; Scanner scan = new Scanner(System.in); System.out.println("Enter Name and Date_of_Birth in the format <Name,DD/MM/YYYY>"); name = scan.next(); // create stringTokenizer with delimiter "/" StringTokenizer st = new StringTokenizer(name, ",/"); // Count the number of tokens int count = st.countTokens(); // Print one token at a time and induce new delimiter "," for (int i = 1; i <= count && st.hasMoreTokens(); i++) { System.out.print(st.nextToken()); if (i < count) System.out.print(","); } } } Output:- CRC@CRC-OptiPlex-3050:~$ javac Customer.java CRC@CRC-OptiPlex-3050:~$ java Customer Enter Name and Date_of_Birth in the format <Name,DD/MM/YYYY> abc,01/01/1990 abc,01,01,1990 CRC@CRC-OptiPlex-3050:~$ java Customer Enter Name and Date_of_Birth in the format <Name,DD/MM/YYYY> Manu, 05/06/1995 Manu CRC@CRC-OptiPlex-3050:~$ java Customer Enter Name and Date_of_Birth in the format <Name,DD/MM/YYYY> Manu,02/06/1994 Manu,02,06,1994 CRC@CRC-OptiPlex-3050:~$ 3)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. import java.util.Scanner; class MyException extends Exception {
  22. 22. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 22 public String toString() { return "Denominator is 0! Division by zero ERROR"; } } class Compute { private int a,b; public Compute(int a, int b) { super(); this.a = a; this.b = b; } public void compute_a_by_b() { try { if (this.b != 0) { System.out.println("Result a/b="+(float)1.0*this.a/this.b); } else throw new MyException(); } catch (MyException e) { System.out.println("Error !!!!: " + e); } } } public class Exceptions { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a :-"); int a = in.nextInt(); System.out.print("Enter b:-"); int b = in.nextInt(); Compute compute = new Compute(a, b); compute.compute_a_by_b();
  23. 23. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 23 } } Output: CRC16@CRC:~/CRC17$ javac Exceptions.java CRC16@CRC:~/CRC17$ java Exceptions Enter a :-45 Enter b:-5 Result a/b=9.0 CRC16@CRC:~/daa18$ java Exceptions Enter a :-6 Enter b:-0 Error !!!!: Denominator is 0! Division by zero ERROR CRC16@CRC:~/daa18$ java Exceptions Enter a :--90 Enter b:-5 Result a/b=-18.0 3)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. import java.util.Random; class SquareThread implements Runnable { int x; SquareThread(int x) { this.x = x; } public void run() { System.out.println("Thread Name:Square Thread and Square of " + x + " is: " + x * x); } } class CubeThread implements Runnable { int x; CubeThread(int x) { this.x = x; } public void run() { System.out.println("Thread Name:Cube Thread and Cube of " + x + " is: " + x * x * x); } } class RandomThread implements Runnable
  24. 24. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 24 { Random r; Thread t2, t3; public void run() { int num; r = new Random(); try { while (true) { num = r.nextInt(100); System.out.println("Main Thread and Generated Number is " + num); t2 = new Thread(new SquareThread(num)); t2.start(); t3 = new Thread(new CubeThread(num)); t3.start(); Thread.sleep(1000); System.out.println("--------------------------------------"); } } catch (Exception ex) { System.out.println("Interrupted Exception"); } } } public class MainThread { public static void main(String[] args) { RandomThread thread_obj = new RandomThread(); Thread t1 = new Thread(thread_obj); t1.start(); } } Output: CRC@CRC-OptiPlex-3050:~$ javac MainThread.java CRC@CRC-OptiPlex-3050:~$ java MainThread Main Thread and Generated Number is 99 Thread Name:Square Thread and Square of 99 is: 9801 Thread Name:Cube Thread and Cube of 99 is: 970299 -------------------------------------- Main Thread and Generated Number is 8 Thread Name:Square Thread and Square of 8 is: 64 Thread Name:Cube Thread and Cube of 8 is: 512 --------------------------------------
  25. 25. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 25 Main Thread and Generated Number is 43 Thread Name:Square Thread and Square of 43 is: 1849 Thread Name:Cube Thread and Cube of 43 is: 79507 -------------------------------------- Main Thread and Generated Number is 57 Thread Name:Square Thread and Square of 57 is: 3249 Thread Name:Cube Thread and Cube of 57 is: 185193 -------------------------------------- Main Thread and Generated Number is 44 Thread Name:Square Thread and Square of 44 is: 1936 Thread Name:Cube Thread and Cube of 44 is: 85184 -------------------------------------- Main Thread and Generated Number is 88 Thread Name:Square Thread and Square of 88 is: 7744 Thread Name:Cube Thread and Cube of 88 is: 681472 -------------------------------------- Main Thread and Generated Number is 66 Thread Name:Square Thread and Square of 66 is: 4356 Thread Name:Cube Thread and Cube of 66 is: 287496 -------------------------------------- Main Thread and Generated Number is 7 Thread Name:Square Thread and Square of 7 is: 49 Thread Name:Cube Thread and Cube of 7 is: 343 -------------------------------------- Main Thread and Generated Number is 84 Thread Name:Square Thread and Square of 84 is: 7056 Thread Name:Cube Thread and Cube of 84 is: 592704 -------------------------------------- Main Thread and Generated Number is 83 Thread Name:Square Thread and Square of 83 is: 6889 Thread Name:Cube Thread and Cube of 83 is: 571787 ^Z //To stop the process enter Ctrl -Z[3]+ Stopped java MainThread 4. Sort a given set of n integer elements using the Quicksort 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. import java.util.Scanner; import java.util.Arrays; import java.util.Random; public class Quicksort { static final int MAX = 10005; static int[] a = new int[MAX]; public static void main(String[] args) {
  26. 26. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 26 Scanner input = new Scanner(System.in); System.out.print("Enter Max array size: "); int n = input.nextInt(); Random random = new Random(); System.out.println("Enter the array elements: "); for (int i = 0; i < n; i++) a[i] = input.nextInt(); // for keyboard entry // a[i] = random.nextInt(1000); // generate // random numbers – uniform distribution // a = Arrays.copyOf(a, n); // keep only non zero elements // Arrays.sort(a); // for worst-case time complexity System.out.println("Input Array:"); for (int i = 0; i < n; i++) System.out.print(a[i] + " "); // set start time long startTime = System.nanoTime(); QuickSortAlgorithm(0, n - 1); long stopTime = System.nanoTime(); long elapsedTime = stopTime - startTime; System.out.println("nSorted Array:"); for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } System.out.println(); System.out.println("Time Complexity in ms for n=" + n + " is: " + (double) elapsedTime / 1000000); } public static void QuickSortAlgorithm(int p, int r) { int i, j, temp, pivot; if (p < r) { i = p; j = r + 1; pivot = a[p]; // mark first element as pivot while (true) { i++; while (a[i] < pivot && i < r) i++; j--; while (a[j] > pivot)
  27. 27. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 27 j--; if (i < j) { temp = a[i]; a[i] = a[j]; a[j] = temp; } else break; // partition is over } a[p] = a[j]; a[j] = pivot; QuickSortAlgorithm(p, j - 1); QuickSortAlgorithm(j + 1, r); } } } Output: CRC16@CRC:~/CRC17$ javac Quicksort.java CRC16@CRC:~/CRC17$ java Quicksort Enter Max array size: 3 Enter the array elements: 2 89 5 Input Array: 2 89 5 Sorted Array: 2 5 89 Time Complexity in ms for n=3 is: 0.006133 CRC16@CRC:~/daa18$ java Quicksort Enter Max array size: 3 Enter the array elements: 9 99 199 Input Array: 9 99 199 Sorted Array: 9 99 199 Time Complexity in ms for n=3 is: 0.005732 CRC16@CRC:~/daa18$ java Quicksort Enter Max array size: 3 Enter the array elements:
  28. 28. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 28 -8 9 2 Input Array: -8 9 2 Sorted Array: -8 2 9 Time Complexity in ms for n=3 is: 0.006137 5.Sort a given set of n integer elements using Merge 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. import java.util.Random; import java.util.Scanner; public class Mergesort { static final int MAX = 10005; static int[] a = new int[MAX]; public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter Max array size: "); int n = input.nextInt(); Random random = new Random(); System.out.println("nThe array elements are gereated randomly:n"); for (int i = 0; i < n; i++) { //a[i] = input.nextInt(); for keyboard entry a[i] = random.nextInt(1000); // generate random numbers –uniform distribution System.out.println("-------------"+a[i]); } long startTime = System.nanoTime(); MergeSortAlgorithm(0, n - 1); long stopTime = System.nanoTime(); long elapsedTime = stopTime - startTime; System.out.println("------------------------"); System.out.println("Time Complexity (ms) for n = " + n + " is :" + (double) elapsedTime / 1000000); System.out.println("n-------Sorted Array (Merge Sort)-----------------n"); for (int i = 0; i < n; i++) System.out.println(a[i] + " ");
  29. 29. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 29 input.close(); } public static void MergeSortAlgorithm(int low, int high) { int mid; if (low < high) { mid = (low + high) / 2; MergeSortAlgorithm(low, mid); MergeSortAlgorithm(mid + 1, high); Merge(low, mid, high); } } public static void Merge(int low, int mid, int high) { int[] b = new int[MAX]; int i, h, j, k; h = i = low; j = mid + 1; while ((h <= mid) && (j <= high)) if (a[h] < a[j]) b[i++] = a[h++]; else b[i++] = a[j++]; if (h > mid) for (k = j; k <= high; k++) b[i++] = a[k]; else for (k = h; k <= mid; k++) b[i++] = a[k]; for (k = low; k <= high; k++) a[k] = b[k]; } } Output: CRC16@CRC:~/CRC17$ javac Mergesort.java CRC16@CRC:~/CRC17$ java Mergesort Enter Max array size: 3 The array elements are gereated randomly: -------------775 -------------432 -------------867
  30. 30. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 30 ------------------------ Time Complexity (ms) for n = 3 is :0.050594 -------Sorted Array (Merge Sort)----------------- 432 775 867 CRC16@CRC:~/daa18$ java Mergesort Enter Max array size: 3 The array elements are gereated randomly: -------------340 -------------699 -------------311 ------------------------ Time Complexity (ms) for n = 3 is :0.033258 -------Sorted Array (Merge Sort)----------------- 311 340 699 CRC16@CRC:~/daa18$ java Mergesort Enter Max array size: 5 The array elements are gereated randomly: -------------28 -------------422 -------------592 -------------565 -------------85 ------------------------ Time Complexity (ms) for n = 5 is :0.105371 -------Sorted Array (Merge Sort)----------------- 28 85 422 565 592 CRC16@CRC:~/daa18$ java Mergesort Enter Max array size: 5 The array elements are gereated randomly:
  31. 31. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 31 -------------362 -------------895 -------------494 -------------617 -------------917 ------------------------ Time Complexity (ms) for n = 5 is :0.088788 -------Sorted Array (Merge Sort)----------------- 362 494 617 895 917 6)a Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method. import java.util.Scanner; public class Knapsack6a { static final int MAX = 20; // max. no. of objects static int w[]; // weights 0 to n-1 static int p[]; // profits 0 to n-1 static int n; // no. of objects static int M; // capacity of Knapsack static int V[][]; // DP solution process - table static int Keep[][]; // to get objects in optimal solution public static void main(String args[]) { w = new int[MAX]; p = new int[MAX]; V = new int [MAX][MAX]; Keep = new int[MAX][MAX]; int optsoln; ReadObjects(); for (int i = 0; i <= M; i++) V[0][i] = 0; for (int i = 0; i <= n; i++) V[i][0] = 0; optsoln = Knapsack(); System.out.println("Optimal solution = " + optsoln);
  32. 32. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 32 } static int Knapsack() { int r; // remaining Knapsack capacity for (int i = 1; i <= n; i++) for (int j = 0; j <= M; j++) if ((w[i] <= j) && (p[i] + V[i - 1][j - w[i]] > V[i - 1][j])) { V[i][j] = p[i] + V[i - 1][j - w[i]]; Keep[i][j] = 1; } else { V[i][j] = V[i - 1][j]; Keep[i][j] = 0; } // Find the objects included in the Knapsack r = M; System.out.println("Items = "); for (int i = n; i > 0; i--) // start from Keep[n,M] if (Keep[i][r] == 1) { System.out.println(i + " "); r = r - w[i]; } System.out.println(); return V[n][M]; } static void ReadObjects() { Scanner scanner = new Scanner(System.in); System.out.println("Knapsack Problem - Dynamic Programming Solution: "); System.out.println("Enter the max capacity of knapsack: "); M = scanner.nextInt(); System.out.println("Enter number of objects: "); n = scanner.nextInt(); System.out.println("Enter Weights: "); for (int i = 1; i <= n; i++) w[i] = scanner.nextInt(); System.out.println("Enter Profits: "); for (int i = 1; i <= n; i++) p[i] = scanner.nextInt(); scanner.close();
  33. 33. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 33 } } Output: CRC16@CRC:~/CRC17$ javac Knapsack6a.java CRC16@CRC:~/CRC17$ java Knapsack6a Knapsack Problem - Dynamic Programming Solution: Enter the max capacity of knapsack: 5 Enter number of objects: 3 Enter Weights: 12 10 4 Enter Profits: 100 2 60 Items = 3 Optimal solution = 60 CRC16@CRC:~/daa18$ java Knapsack6a Knapsack Problem - Dynamic Programming Solution: Enter the max capacity of knapsack: 4 Enter number of objects: 2 Enter Weights: 78 99 Enter Profits: 8 10 Items = Optimal solution = 0 CRC16@CRC:~/daa18$ java Knapsack6a Knapsack Problem - Dynamic Programming Solution: Enter the max capacity of knapsack: 4 Enter number of objects: 2 Enter Weights:
  34. 34. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 34 78 99 Enter Profits: 3 5 Items = Optimal solution = 0 6)b. Implement in Java, the 0/1 Knapsack problem using Greedy method. import java.util.Scanner; class KObject { // Knapsack object details float w; float p;
  35. 35. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 35 float r; } public class KnapsackGreedy { static final int MAX = 20; static int n; static float M; // max. no. of objects // no. of objects // capacity of Knapsack public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter number of objects: "); n = scanner.nextInt(); KObject[] obj = new KObject[n]; for(int i = 0; i<n;i++) obj[i] = new KObject();// allocate memory for members ReadObjects(obj); Knapsack(obj); scanner.close(); } static void ReadObjects(KObject obj[]) { KObject temp = new KObject(); Scanner scanner = new Scanner(System.in); System.out.println("Enter the max capacity of knapsack: "); M = scanner.nextFloat(); System.out.println("Enter Weights: "); for (int i = 0; i < n; i++) obj[i].w = scanner.nextFloat(); System.out.println("Enter Profits: "); for (int i = 0; i < n; i++) obj[i].p = scanner.nextFloat(); for (int i = 0; i < n; i++) obj[i].r = obj[i].p / obj[i].w; // sort objects in descending order, based on p/w ratio for(int i = 0; i<n-1; i++) for(int j=0; j<n-1-i; j++) if(obj[j].r < obj[j+1].r) { temp = obj[j];
  36. 36. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 36 obj[j] = obj[j+1]; obj[j+1] = temp; } scanner.close(); } static void Knapsack(KObject kobj[]) { float x[] = new float[MAX]; float totalprofit; int i; float U; // U place holder for M U = M; totalprofit = 0; for (i = 0; i < n; i++) x[i] = 0; for (i = 0; i < n; i++) { if (kobj[i].w > U) break; else { x[i] = 1; totalprofit = totalprofit + kobj[i].p; U = U - kobj[i].w; } } System.out.println("i = " + i); if (i < n) x[i] = U / kobj[i].w; totalprofit = totalprofit + (x[i] * kobj[i].p); System.out.println("The Solution vector, x[]: "); for (i = 0; i < n; i++) System.out.print(x[i] + " "); System.out.println("nTotal profit is = " + totalprofit); } OUTPUT: CRC16@CRC:~/CRC17$ javac KnapsackGreedy.java CRC16@CRC:~/CRC17$ java KnapsackGreedy Enter number of objects: 3 Enter the max capacity of knapsack: 5 Enter Weights:
  37. 37. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 37 12 33 5 Enter Profits: 12 3 8 i = 1 The Solution vector, x[]: 1.0 0.0 0.0 Total profit is = 8.0 CRC16@CRC:~/daa18$ java KnapsackGreedy Enter number of objects: 3 Enter the max capacity of knapsack: 5 Enter Weights: 77 55 99 Enter Profits: 2 2 10 i = 0 The Solution vector, x[]: 0.05050505 0.0 0.0 Total profit is = 0.5050505
  38. 38. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 38 } 7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm. Write the program in Java. import java.util.Scanner; public class Dijkstras { public static void main(String[] args) { int i, j;
  39. 39. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 39 int dist[]=new int[10], visited[]=new int[10]; int cost[][]=new int[10][10], path[]=new int[10]; Scanner in = new Scanner(System.in); System.out.println("**** DIJKSTRA'S ALGORITHM ******"); System.out.println("Enter the number of nodes: "); int n = in.nextInt(); System.out.println("Enter the cost matrix"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) cost[i][j] = in.nextInt(); System.out.println("The entered cost matrix is"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { System.out.print(cost[i][j]+"t"); } System.out.println(); } System.out.println("Enter the source vertex: "); int sv = in.nextInt(); dij(cost,dist,sv,n,path,visited); printpath(sv,n,dist,path,visited ); System.out.println("n********* *************** *********"); } static void dij(int cost[][],int dist[],int sv,int n,int path[],int visited[]) { int count = 2,min,v=0; for(int i=1; i<=n; i++) { visited[i]=0; dist[i] = cost[sv][i]; if(cost[sv][i] == 999) path[i] = 0; else path[i] = sv; } visited[sv]=1; while(count<=n) { min = 999; for(int w=1; w<=n; w++) if((dist[w]< min) && (visited[w]==0))
  40. 40. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 40 { min = dist[w]; v = w; } visited[v] = 1; count++; for(int w=1; w<=n; w++) { if((dist[w]) >(dist[v] + cost[v][w])) { dist[w] = dist[v] + cost[v][w]; path[w] = v; } } } } static void printpath(int sv,int n,int dist[],int path[],int visited[]) { for(int w=1; w<=n; w++) { if(visited[w] == 1 && w != sv) { System.out.println("The shortest distance between "); System.out.println(sv+"-> ="+w+" is :"+ dist[w]); int t=path[w]; System.out.println("The path is:"); System.out.print(" "+w); while(t != sv) { System.out.print("<-->"+t); t=path[t]; } System.out.print("<-->"+sv); } } } } OUTPUT : CRC16@CRC:~/CRC17$ javac Dijkstras.java CRC16@CRC:~/CRC17$ java Dijkstras **** DIJKSTRA'S ALGORITHM ****** Enter the number of nodes: 3 Enter the cost matrix
  41. 41. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 41 0 5 999 5 0 999 2 0 0 The entered cost matrix is 0 5 999 5 0 999 2 0 0 Enter the source vertex: 1 The shortest distance between 1-> =2 is :5 The path is: 2<-->1 ********* *************** ********* CRC16@CRC:~/daa18$ java Dijkstras **** DIJKSTRA'S ALGORITHM ****** Enter the number of nodes: 4 Enter the cost matrix 0 5 0 999 5 0 1 999 999 1 999 2 999 999 5 0 The entered cost matrix is 0 5 0 999 5 0 1 999
  42. 42. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 42 999 1 999 2 999 999 5 0 Enter the source vertex: 1 The shortest distance between 1-> =2 is :1 The path is: 2<-->3<-->1The shortest distance between 1-> =3 is :0 The path is: 3<-->1The shortest distance between 1-> =4 is :2 The path is: 4<-->3<-->1 ********* *************** ******** ********* DIJKSTRA'S ALGORITHM ********* Enter the number of nodes: 4 Enter the cost matrix 0 1 4 999 1 0 2 8 4 2 0 3 999 8 3 0 The entered cost matrix is 0 1 4 999 1 0 2 8 4 2 0 3 999 8 3 0 Enter the source vertex: 1 The shortest distance between 1-> =2 is :1 The path is: 2<-->1The shortest distance between 1-> =3 is :3 The path is: 3<-->2<-->1The shortest distance between 1-> =4 is :6 The path is: 4<-->3<-->2<-->1 ********* ************************ ********* 8)a Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm. Implement the program in Java language. import java.util.Scanner; public class KRUSKAL { public static void main(String[] args) {
  43. 43. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 43 int cost[][]=new int[10][10]; int i, j,mincost=0; Scanner in = new Scanner(System.in); System.out.println("********* KRUSKAL'S ALGORITHM *******"); System.out.println("Enter the number of nodes: "); int n = in.nextInt(); System.out.println("Enter the cost matrix"); for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ cost[i][j] = in.nextInt(); } } System.out.println("The entered cost matrix is"); for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ System.out.print(cost[i][j]+"t"); } System.out.println(); } mincost=kruskals(n,mincost,cost); System.out.println("The minimum spanning tree cost is:"); System.out.println(mincost); System.out.println("********* ****************** **********"); } static int kruskals(int n,int mincost,int cost[][] ) { int ne = 1,a=0,u=0,b=0,v=0,min; int parent[]=new int[10]; while(ne < n){ min=999; for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { if(cost[i][j] < min) { min = cost[i][j]; a=u=i; b=v=j; } } } while(parent[u]>0)
  44. 44. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 44 u = parent[u]; while(parent[v]>0) v = parent[v]; if(u != v) { System.out.print((ne++)+">minimum edge is :"); System.out.println("("+a+","+b+") and its cost is:"+min); mincost += min; parent[v] = u; } cost[a][b] = cost[b][a] = 999; } return mincost; } } Output: CRC16@CRC:~/Desktop/CRC$ javac KRUSKAL.java CRC16@CRC:~/Desktop/CRC$ java KRUSKAL ********* KRUSKAL'S ALGORITHM ******* Enter the number of nodes: 3 Enter the cost matrix 0 2 6 2 0 2 6 2 0 The entered cost matrix is 0 2 6 2 0 2 6 2 0 1>minimum edge is :(1,2) and its cost is:2 2>minimum edge is :(2,3) and its cost is:2 The minimum spanning tree cost is: 4 ********* KRUSKAL'S ALGORITHM ********* Enter the number of nodes: 5 Enter the cost matrix
  45. 45. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 45 0 1 2 999 6 1 0 3 999 999 2 3 0 4 999 999 999 4 0 5 6 999 999 5 0 The entered cost matrix is 0 1 2 999 6 1 0 3 999 999 2 3 0 4 999 999 999 4 0 5 6 999 999 5 0 1> minimum edge is :(1,2) and its cost is:1 2> minimum edge is :(1,3) and its cost is:2 3> minimum edge is :(3,4) and its cost is:4 4> minimum edge is :(4,5) and its cost is:5 The minimum spanning tree cost is : 12 ********* *********************** ********** 8)b Find Minimum Cost Spanning Tree of a given undirected graph using Prim's algorithm. Implement the program in Java language. import java.util.Scanner; public class PRIM { public static void main(String[] args) { int cost[][]=new int[10][10]; int i, j, mincost = 0; Scanner in = new Scanner(System.in); System.out.println("********* PRIMS ALGORITHM *********"); System.out.println("Enter the number of nodes"); int n = in.nextInt(); System.out.println("Enter the cost matrix"); for(i=1; i<=n; i++) { for(j=1; j<=n; j++) { cost[i][j] = in.nextInt(); } } System.out.println("The entered cost matrix is"); for(i=1; i<=n; i++) { for(j=1; j<=n; j++) { System.out.print(cost[i][j]+"t"); }
  46. 46. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 46 System.out.println(); } System.out.println("Minimum Spanning Tree Edges and costs are"); mincost=prims(cost,n,mincost); System.out.println("******* ********************* *******"); System.out.print("The minimum spanning tree cost is"); System.out.print(+mincost); System.out.println("******* ********************* *******"); } static int prims(int cost[][],int n,int mincost) { int nearV[]=new int[10],t[][]=new int[10][3],u = 0,i,j,k; for(i=2; i<=n; i++) nearV[i]=1; nearV[1]=0; for(i=1; i<n; i++) { int min=999; for(j=1;j<=n;j++) { if(nearV[j]!=0 && cost[j][nearV[j]]<min) { min=cost[j][nearV[j]]; u=j; } } t[i][1] = u; t[i][2] = nearV[u]; mincost += min; nearV[u] = 0; for(k=1; k<=n; k++){ if(nearV[k] != 0 && cost[k][nearV[k]] > cost[k][u]) nearV[k] = u; } System.out.print(i+") Minimum edge is ("+t[i][1]); System.out.println(","+t[i][2]+") and its cost is :"+min); } return mincost; } } Output: CRC16@CRC:~/Desktop/CRC$ javac PRIM.java CRC16@CRC:~/Desktop/CRC$ java PRIM
  47. 47. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 47 ********* PRIMS ALGORITHM ********* Enter the number of nodes 3 Enter the cost matrix 0 2 999 2 0 1 999 1 0 The entered cost matrix is 0 2 999 2 0 1 999 1 0 Minimum Spanning Tree Edges and costs are 1) Minimum edge is (2,1) and its cost is :2 2) Minimum edge is (3,2) and its cost is :1 The minimum spanning tree cost is3******* ********************* ******* ************** PRIMS ALGORITHM ************** Enter the number of nodes 5 Enter the cost matrix 0 1 2 999 6 1 0 3 999 999 2 3 0 4 999 999 999 4 0 5 6 999 999 5 0 The entered cost matrix is 0 1 2 999 6 1 0 3 999 999 2 3 0 4 999 999 999 4 0 5 6 999 999 5 0 Minimum Spanning Tree Edges and costs are 1) Minimum edge is (2,1) and its cost is :1 2) Minimum edge is (3,1) and its cost is :2 3) Minimum edge is (4,3) and its cost is :4 4) Minimum edge is (5,4) and its cost is :5 The minimum spanning tree cost is 12 ******* ******************************** *******
  48. 48. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 48 ************** PRIMS ALGORITHM ************** Enter the number of nodes 6 Enter the cost matrix 0 60 10 999 999 999 60 0 999 20 40 70 10 999 0 999 999 50 999 20 999 0 999 80 999 40 999 999 0 30 999 70 50 80 30 0 The entered cost matrix is 0 60 10 999 999 999 60 0 999 20 40 70 10 999 0 999 999 50 999 20 999 0 999 80 999 40 999 999 0 30 999 70 50 80 30 0 Minimum Spanning Tree Edges and their costs are 1) Minimum edge is (3,1) and its cost is :10 2) Minimum edge is (6,3) and its cost is :50 3) Minimum edge is (5,6) and its cost is :30 4) Minimum edge is (2,5) and its cost is :40 5) Minimum edge is (4,2) and its cost is :20 The minimum spanning tree cost is 150 ******* ******************************** ******* 9)a. Write Java programs to implement All-Pairs Shortest Paths problem using Floyd's algorithm. import java.util.Scanner; class Floyd { public static void main(String[] args) { int a[][]=new int[10][10]; int i, j; Scanner in = new Scanner(System.in); System.out.println("***********FLOYD'SALGORITHM**********"); System.out.println("Enter the number of vertices: "); int n = in.nextInt(); System.out.println("Enter the adjacency matrix"); for (i=1;i<=n;i++) for (j=1;j<=n;j++) a[i][j] = in.nextInt(); System.out.println("Entered adjacency matrix is: "); for(i=1;i<=n;i++) { for(j=1; j<=n; j++)
  49. 49. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 49 { System.out.print(a[i][j]+"t"); } System.out.println(); } floyd(a,n); System.out.println("All pair shortest path matrix:"); for (i=1; i<=n; i++) { for (j=1; j<=n; j++) System.out.print(a[i][j]+"t"); System.out.println(); } System.out.println("************ ********* **************"); } static void floyd(int a[][],int n) { for (int k=1; k<=n; k++) { for (int i=1; i<=n; i++) for (int j=1; j<=n; j++) a[i][j] = min(a[i][j], a[i][k] + a[k][j]); } } static int min(int a,int b) { if(a>b) return b; else return a; } } Output: CRC16@CRC:~/Desktop/CRC$ javac Floyd.java CRC16@CRC:~/Desktop/CRC$ java Floyd ***********FLOYD'SALGORITHM********** Enter the number of vertices: 4 Enter the adjacency matrix 0 1 3 1
  50. 50. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 50 2 0 5 999 4 7 999 1 33 2 1 3 Entered adjacency matrix is: 0 1 3 1 2 0 5 999 4 7 999 1 33 2 1 3 All pair shortest path matrix: 0 1 2 1 2 0 4 3 4 3 2 1 4 2 1 2 ***********FLOYD'S ALGORITHM********** Enter the number of vertices: 4 Enter the adjacency matrix 0 1 8 5 1 0 2 999 8 2 0 3 5 999 3 0 Entered adjacency matrix is: 0 1 8 5 1 0 2 999 8 2 0 3 5 999 3 0 All pair shortest path matrix: 0 1 3 5 1 0 2 5 3 2 0 3 5 5 3 0 ************** ********* ************** 9)b. Write Java programs to implement Travelling Sales Person problem using Dynamic programming.
  51. 51. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 51 import java.util.Scanner; public class Tsp { public static void main(String[] args) { int c[][]=new int[10][10], tour[]=new int[10]; Scanner in = new Scanner(System.in); int i, j,cost; System.out.println("**** TSP DYNAMIC PROGRAMMING *******"); System.out.println("Enter the number of cities: "); int n = in.nextInt(); if(n==1) { System.out.println("Path is not possible"); System.exit(0); } System.out.println("Enter the cost matrix"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) c[i][j] = in.nextInt(); System.out.println("The entered cost matrix is"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { System.out.print(c[i][j]+"t"); } System.out.println(); } for(i=1;i<=n;i++) tour[i]=i; cost = tspdp(c, tour, 1, n); System.out.println("The accurate path is"); for(i=1;i<=n;i++) System.out.print(tour[i]+"->"); System.out.println("1"); System.out.print("The accurate mincost is "+cost); System.out.println("******* ************* ***************"); } static int tspdp(int c[][], int tour[], int start, int n) { int mintour[]=new int[10], temp[]=new int[10], mincost=999,
  52. 52. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 52 ccost, i, j, k; if(start == n-1) { return (c[tour[n-1]][tour[n]] + c[tour[n]][1]); } for(i=start+1; i<=n; i++) { for(j=1; j<=n; j++) temp[j] = tour[j]; temp[start+1] = tour[i]; temp[i] = tour[start+1]; if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost) { mincost = c[tour[start]][tour[i]] + ccost; for(k=1; k<=n; k++) mintour[k] = temp[k]; } } for(i=1; i<=n; i++) tour[i] = mintour[i]; return mincost; } } Output: CRC16@CRC:~/Desktop/CRC$ javac Tsp.java CRC16@CRC:~/Desktop/CRC$ java Tsp **** TSP DYNAMIC PROGRAMMING ******* Enter the number of cities: 4 Enter the cost matrix 0 1 3 6 1 0 2 3 3 2 0 1 6 3 1 0 The entered cost matrix is 0 1 3 6 1 0 2 3 3 2 0 1 6 3 1 0 The accurate path is 1->2->4->3->1 The accurate mincost is 8******* ************* *************** 10)a Design and implement in Java to find a subset of a given set S = {Sl, 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,
  53. 53. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 53 there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem instance doesn't have a solution.*/ import java.util.Scanner; public class Subset { static int c=0; public static void main(String[] args) { int w[]=new int[10]; int n, d, i, sum=0; int x[]=new int[10]; Scanner in=new Scanner(System.in); System.out.println("********** SUBSET PROBLEM ************"); System.out.println("Enter the number of elements: "); n=in.nextInt(); System.out.println("Enter the elements in increasing order"); for(i=0;i<n;i++) w[i]=in.nextInt(); System.out.println("Enter the value of d: "); d=in.nextInt(); for(i=0;i<n;i++) sum=sum+w[i]; System.out.println("SUM ="+sum); if(sum < d || w[0] > d) { System.out.println("Subset is not possible ! "); System.out.println("********** *********** *************"); System.exit(0); } subset(0,0,sum,x,w,d); if(c==0) System.out.println("Subset is not possible ! "); System.out.println("n********** ********* *************"); } static void subset(int cs, int k, int r,int x[],int w[],int d) { x[k] = 1; if(cs+w[k] == d) { c++; System.out.print("nSolution "+c+" is {"); for(int i=0;i<=k;i++) if(x[i] == 1)
  54. 54. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 54 { System.out.print(w[i]+" "); } System.out.print("}"); } else if((cs + w[k] + w[k+1]) <= d) subset(cs + w[k], k+1, r-w[k],x,w,d); if((cs + r - w[k]) >= d && (cs + w[k+1]) <= d) { x[k] = 0; subset(cs, k+1, r-w[k],x,w,d); } } } Output: CRC16@CRC:~/Desktop/CRC$ javac Subset.java CRC16@CRC:~/Desktop/CRC$ java Subset ********** SUBSET PROBLEM ************ Enter the number of elements: 5 Enter the elements in increasing order 1 2 3 6 8 Enter the value of d: 9 SUM =20 Solution 1 is {1 2 6 } Solution 2 is {1 8 } Solution 3 is {3 6 } ********** ********* ************* CRC16@CRC:~/Desktop/CRC$ java Lab10A ********** SUBSET PROBLEM ************ Enter the number of elements: 3 Enter the elements in increasing order 5 8 10 Enter the value of d: 25 SUM =23 Subset is not possible ! *********** SUBSET PROBLEM ************ Enter the number of elements:
  55. 55. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 55 5 Enter the elements in increasing order: 1 2 3 6 8 Enter the value of d: 9 SUM =20 Solution 1 is {1 2 6 } Solution 2 is {1 8 } Solution 3 is {3 6 } ********** ****************** ************* *********** SUBSET PROBLEM ************ Enter the number of elements: 3 Enter the elements in increasing order: 5 8 10 Enter the value of d: 25 SUM =23 Subset is not possible ! ********** ****************** ************* *********** SUBSET PROBLEM ************ Enter the number of elements: 3 Enter the elements in increasing order: 3 5 9 Enter the value of d: 7 SUM =17 Subset is not possible ! ********** ****************** ************* *********** SUBSET PROBLEM ************ Enter the number of elements: 3 Enter the elements in increasing order: 7 9 12 Enter the value of d: 6 SUM =28
  56. 56. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 56 Subset is not possible ! ********** ****************** ************* 10)b. Design and implement the presence of Hamiltonian Cycle in an undirected Graph G of n vertices.*/ import java.util.Scanner; public class Hamiltonian { static int n; public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter no. of vertices"); n=in.nextInt(); int graph[][]=new int[10][10]; System.out.println("Enter adjacency matrix of graph"); for(int i=1;i<n;i++) for(int j=0;j<n;j++) graph[i][j] =in.nextInt(); System.out.println("Entered adjacency matrix of graph is"); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print("t"+graph[i][j]); } System.out.println(); } hamCycle(graph); System.out.println("n*********************************n"); } static void printSolution(int path[]) { System.out.println("Solution Exists:"); System.out.println(" Following is one Hamiltonian Cycle "); for (int i = 0; i <n; i++) System.out.println(path[i]); System.out.println(path[0]); } static boolean isSafe(int v,int graph[][],int path[],int pos) { if (graph[path[pos-1]][v] == 0) return false;
  57. 57. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 57 for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true; } /* A recursive utility function to solve Hamiltonian cycle problem */ static boolean hamCycleUtil(int graph[][],int path[],int pos) { if (pos == n) { if (graph[path[pos-1]][path[0]] == 1) return true; else return false; } for (int v = 1; v < n; v++) { if (isSafe(v, graph, path, pos)) { path[pos] = v; if (hamCycleUtil (graph, path, pos+1) == true) return true; path[pos] = -1; } } return false; } /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path.This function prints one of the feasible solutions. */ static boolean hamCycle(int graph[][]) { int path[] = new int[n+1]; for (int i = 0; i < n; i++) path[i] = -1; path[0] = 0; if (hamCycleUtil(graph, path, 1) == false){ System.out.println("nSolution does not exist"); return false; } printSolution(path); return true; } }
  58. 58. DESIGN AND ANALYSIS OF ALGORITHM LABORATORY Chethan Raj C, Asst Professor Dept. of CSE Page 58 OUTPUT : *******************Hamiltonian cycle***************** Enter no. of vertices 5 Enter adjacency matrix of graph 0 1 0 1 0 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 Entered adjacency matrix of graph is 0 1 0 1 0 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 Solution Exists: Following is one Hamiltonian Cycle 0 -->1 -->2 -->4 -->3 -->0 ****************************************************** *******************Hamiltonian cycle***************** Enter no. of vertices 5 Enter adjacency matrix of graph 0 1 0 1 0 1 0 1 1 1 0 1 0 0 1 1 1 0 0 0 0 1 1 0 0 Entered adjacency matrix of graph is 0 1 0 1 0 1 0 1 1 1 0 1 0 0 1 1 1 0 0 0 0 1 1 0 0 Solution does not exist ******************************************************

×