SWAPNA MEDIKONDA
Associate Professor, CSE Department, Keshav Memorial Institute of Technology, Narayanaguda, Hyderabad - 500020
Thursday, December 29, 2016
Thursday, December 22, 2016
Write a Programme that computes the simple interest and compound interest payable on principal amount (in Rs.) of loan borrowed by the customer from a bank for a giver period of time (in years) at specific rate of interest. Further determine whether the b bank will benefit by charging simple interest or compound interest
/*Write a Programme that computes the simple interest and compound interest payable on
principal amount (in Rs.) of loan borrowed by the customer from a bank for a giver period of
time (in years) at specific rate of interest. Further determine whether the b bank will benefit
by charging simple interest or compound interest*/
#include <math.h>
int main()
{
int P,R,T,SI,CI;
cout<<"Enter the principal ,time period & interest rate";
cin>>P>>R>>T;
SI=(P*R*T*)/100;
CI=P*(pow(1+R/100),T);
cout<<"The S I is"<<SI<<endl;
cout<<"The C I is"<<CI<<endl;
if(SI<CI)
{
cout<<"Bank is Benfited by COMPOUND INTREST";
}
else
{
cout<<"Bank is Benfited by SIMPLE INTREST";
}
return 0;
}
/*Write a Programme to calculate the fare for the passengers traveling in a bus. When a
Passenger enters the bus, the conductor asks “What distance will you travel?” On knowing
distance from passenger (as an approximate integer), the conductor mentions the fare to the
passenger according to following criteria.*/
principal amount (in Rs.) of loan borrowed by the customer from a bank for a giver period of
time (in years) at specific rate of interest. Further determine whether the b bank will benefit
by charging simple interest or compound interest*/
#include <math.h>
int main()
{
int P,R,T,SI,CI;
cout<<"Enter the principal ,time period & interest rate";
cin>>P>>R>>T;
SI=(P*R*T*)/100;
CI=P*(pow(1+R/100),T);
cout<<"The S I is"<<SI<<endl;
cout<<"The C I is"<<CI<<endl;
if(SI<CI)
{
cout<<"Bank is Benfited by COMPOUND INTREST";
}
else
{
cout<<"Bank is Benfited by SIMPLE INTREST";
}
return 0;
}
/*Write a Programme to calculate the fare for the passengers traveling in a bus. When a
Passenger enters the bus, the conductor asks “What distance will you travel?” On knowing
distance from passenger (as an approximate integer), the conductor mentions the fare to the
passenger according to following criteria.*/
Tuesday, December 20, 2016
Write a JAVA program to create a class MyThread in this class a constructor, call the base class constructor, using super and starts the thread. The run method of the class starts after this. It can be observed that both main thread and created child thread are executed concurrently
Aim: Write a JAVA program to create a class MyThread in this class a constructor, call the base class constructor, using super and starts the thread. The run method of the class starts after this. It can be observed that both main thread and created child thread are executed concurrently.
Program:
class Thread1 extends Thread{
Thread1()
{
super();
start();
}
public void run()
{
for ( int i=1; i<=10; i++)
{
System.out.println( "Message from Thread1 : " +i);
try
{
Thread.sleep (1000);
}
catch(InterruptedException interruptedException)
{
System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException);
}
}
}
}
public class ThreadDemo1
{
public static void main(String args[])throws InterruptedException
{
Thread1 firstThread = new Thread1();
for ( int i=1; i<=10; i++)
{
System.out.println( "Message from main method : " +i);
Thread.sleep(500);
}
}
}
Output:
Labels: Java Programming Lab
Monday, December 19, 2016
Write a JAVA program illustrating multiple inheritance using interfaces.
import java.lang.*;
import java.io.*;
interface Exam
{
void percent_cal();
}
class Student
{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
{
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display()
{
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
}
}
class Result extends Student implements Exam
{
Result(String n, int r, int m1, int m2)
{
super(n,r,m1,m2);
}
public void percent_cal()
{
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}
}
class MultipleInheritance
{
public static void main(String args[])
{
Result R1 = new Result("hasini",12,93,84);
R1.display();
R1.percent_cal();
Result R2 = new Result("diya",15,90,75);
R2.display();
R2.percent_cal();
}
}
import java.io.*;
interface Exam
{
void percent_cal();
}
class Student
{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
{
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display()
{
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
}
}
class Result extends Student implements Exam
{
Result(String n, int r, int m1, int m2)
{
super(n,r,m1,m2);
}
public void percent_cal()
{
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}
}
class MultipleInheritance
{
public static void main(String args[])
{
Result R1 = new Result("hasini",12,93,84);
R1.display();
R1.percent_cal();
Result R2 = new Result("diya",15,90,75);
R2.display();
R2.percent_cal();
}
}
Output:
Labels: Java Programming Lab
Java Viva Voce -2
1. What is a
variable?
Name which refers memory locations and it can hold a value
which can be changed at runtime is called Variable.
2. What are
primitive data types?
A primitive type is predefined by the language and is named
by a reserved keyword.
3. How many
primitive data types are there in Java?
There are 8 primitive data types and they are byte, int,
short, long, float, double, char and Boolean.
4. Does Java
has any unsigned types?
No, Java does not have any unsigned types.
5. What do
the floating-point numbers without an F suffix indicate?
Floating-point
numbers without an F suffix indicate to be of type double. We can optionally
supply the D suffix also (ex. 3.402D).
6. What are
identifiers?
Identifiers are the names of variables, methods, classes, packages and
interfaces. Unlike literals they are not the things themselves, just ways of
referring to them.
7. Why do we
use Unicode in Java?
Most
of the countries now use Unicode so we use them in Java too.
8. What is
Escape sequence for special character in Java? List some of them.
A character preceded by
a backslash (\) is an escape sequence and has special
meaning to the
compiler. \b, \t, \n, \r etc. are some escape sequences in Java.
9. Can you
use a Java reserved word for a variable name?
No,
we cannot use a Java reserved word for a variable name.
10. Why do
we use the keyword final in Java?
In
Java, you use the keyword final to denote a constant. The keyword final
indicates that you can assign to the variable once, and then its value is set
once and for all. It is compulsory to name constants in all uppercase.
11. How can
you avoid the Math prefix for the mathematical methods and constants?
By importing the package:
import static java.lang.Math.*; we
can avoid the Math prefix for the mathematical methods and constants.
12. Does
Java has built in String type?
Java does not have a built-in string type.
Instead, the standard Java library contains a predefined class called String.
13. how is
Instance variable declared?
Instance variables are created when an object is
created with the use of the keyword 'new' and destroyed when the object is
destroyed.
An
instance variable is a variable which has one copy for an object.
A class variable is a variable which has one copy per class. The class variables will not have a copy in the object.
A class variable is a variable which has one copy per class. The class variables will not have a copy in the object.
For numbers, the default value is 0, for Booleans
it is false and for object references it is null.
Java naming
convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method etc.
Class name should start with an Uppercase and
method name should start with Lowercase.
A literal is a value assigned to a
variable or a constant is called a literal. Java language
specifies five major types of literals: Integer literals, Floating
literals, Character literals,
String literals, Boolean literals.
19.
What is Type casting?
When the data is
converted from one data type to another data type, then it is called type
casting. Type casting is nothing but changing the type of the data.
20. What are the types of casting?
There are
two types of casting.
1) Primitive Casting: When
the data is casted from one primitive type (like int, float, double etc…) to another primitive
type, then it is called Primitive Casting.
2) Derived Casting: When the
data is casted from one derived type to another derived type, then it is called
derived casting.
Operator precedence determines the grouping of
terms in an expression. This affects how an expression is evaluated. For example, the multiplication operator has
higher precedence than the addition operator.
Control
flow statements, however, break up the flow of execution by employing
decision making, looping, and branching, enabling your program to conditionally execute particular
blocks of code.
Break, continue and return are Branching statement.
A loop
statement allows us to execute a statement or group of statements multiple
times which reduces the size of program.
26. What are access modifiers in
java?
These are
the modifiers which are used to restrict the visibility of a class or a
field or a method or a constructor.
27. How many access
modifiers are there in Java?
Java
supports 4 access modifiers.
a) Private: private
fields or methods or constructors are visible within the class in which
they are defined.
b) Protected:
Protected members of a class are visible within the package but they can
be inherited to sub classes outside the package.
c) Public: public
members are visible everywhere.
d) Default or No-access modifiers: Members of
a class which are defined with no access modifiers are visible within the
package in which they are defined.
28. Can we declare a class as protected?
We can’t
declare an outer class as protected but we can declare an inner class (class as
a member of another class) as protected.
29. What are non-access modifiers
in java?
These are
the modifiers which are used to achieve other functionalities like static, final, abstract.
A class
is a program construct which encapsulates data and operations on data. In
object oriented programming, the class can be viewed as a blue print of an
object. An object is a program construct that falls under a ‘classification’
(of a class) which has state and behavior.
There are three steps to create an object from a
class −
Declaration
− A variable is declared with an object type.
Instantiation
− the 'new' keyword is used to create the object.
Initialization
− the 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
A method (function) is a collection of statements
that are grouped together to perform an operation.
Constructor is a special type of method
that is used to initialize the object. Java constructor is invoked at the time of
object creation.
There are two types of constructors:
Default
constructor (no-argument constructor), Parameterized constructor.
35.
What is Constructor Overloading?
Constructor
overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.
36. What is Garbage Collection?
Garbage Collection is process of reclaiming the
runtime unused memory automatically. In other words, it is a way to destroy the
unused objects.
37.
What is the advantage of Garbage Collection?
It
makes java memory efficient because
garbage collector removes the unreferenced objects from heap memory.
38. What is finalize method?
The
finalize method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
39. What is static keyword?
The static keyword in java is used for
memory management mainly. We can apply java static keyword with variables,
methods, blocks and nested class.
40. What is a static
variable?
If you declare any variable as static, it is known
static variable. The static variable can be used to refer the common property
of all objects.
If you apply static keyword with any method, it is
known as static method.
42.What is
java command line argument?
Java command line argument is an
argument i.e. passed at a time of running the java program.
43. Where
the arguments are received and used?
The
arguments passed from the console can be received in the java program and it
can be used as an input.
44.How the
arguments are useful?
They
provide a convenient way to check the behaviour of the program for different
values.
45.What is
an ARRAY?
An array stores the fixed size
sequential collection of elements of the same type.
46.How is an
array used?
An
array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of same data type.
47.What is
for each loop also known as?
Enhanced
for loop.
48.What is the
use of for each loop?
It
enables us to traverse the complete array sequentially without using an index
variable.
49.What is
an ARRAY CLASS?
This
class contains various static methods for sorting and searching arrays, comparing
and filling array elements.
50.What is This
keyword in java?
THIS
keyword is used as a reference to the object of the current class, with in an
instance method or a constructor.
51.What is
use of this keyword?
Differentiate
the instance variables from local variables if they have some names, within a
constructor or a method.
52. Can we call method with
this keyword from constructor?
Yes, we can call non static methods from constructor using this keyword.
Yes, we can call non static methods from constructor using this keyword.
53. Is it possible to
assign reference to this?
No we cannot assign any value to "this" because it’s always
points to current object and it is a
final reference in java. If we try to change or assign value to this compile time
error will come.
54. Can we use this in static methods?
No we cannot use this in static methods. if we try to use compile
time error will come: Cannot use this in a static context.
Labels: VIVA-VOCE
Java Viva Voce
1.
Who designed the java programming?
A. James Gosling at Sun microsystems, Inc. in
1991.
2.
In the beginning what was the main intention behind creating Java?
A.
To connect many household machines.
3.
What was the earlier name of Java programming language?
A.
Oak
4.
Why Oak was renamed to Java?
A.
It is because there already existed a language by that name.
5.
What are the difference between Java and other programming languages?
A.
Java does not have pointers. We are forced to write the object oriented code in
Java.
6.
What features of Java are considered as the Java essentials?
A.
High level language, Java Bytecode, Java Virtual Machine.
7.
What is the Java Bytecode?
A.
It is an intermediate code generated by compiler which is executed by the JVM.
8.
What is JVM?
A.
It acts as an interpreter for the bytecode, which takes bytecodes as input and
executes it.
9.
What is the full form of JRE?
A.
Java runtime environment.
10.
What does the JRE consist of?
A.
JVM and core Java API libraries.
11.
What is the JDK consist of?
A.
JRE and development tools like compilers.
12.
What are the main features of Java?
A.
Platform independent, object oriented, incorporates both interpretation and
compilation, is robust and multithreaded.
13. What is an object in Java?
A. It is an instance of the class. An instance
contains members (fields and methods)
14.
What is a field?
A. A field is one that holds a value.
15. What is
a method?
A. A method defines operations on the
fields and values that are passed as arguments to the method.
16. What is a sandbox?
A.
It is a security model that Java uses, which makes it easier to work
with untrusted softwares by restricting codes.
17. What is the sandbox made of?
A. It consists of Class loader, Bytecode
verifier and Security manager.
18. What is a class Loader?
A.
It is the first link in the security chain that fetches executable codes
from networks.
19. What is a Bytecode verifier?
A.
It checks for any violations.
20. What is security manager?
A.
It enforces the boundary of the sandbox. It decides if the action
performed by applet is approved or not.
21. Why save a Java program with class
name?
A. Every class is placed in its own output
file named after the class and using the .class extension.
Labels: VIVA-VOCE
Write a JAVA program to illustrate creation of threads using runnable class.(start method start each of the newly created thread. Inside the run method there is sleep() for suspend the thread for 500 milliseconds).
Aim: Write a JAVA program to illustrate creation of threads using runnable class.(start method start each of the newly created thread. Inside the run method there is sleep() for suspend the thread for 500 milliseconds).
Program:
class FirstThread implements Runnable{
public void run()
{
for ( int i=1; i<=10; i++)
{
System.out.println( "Messag from First Thread : " +i);
try
{
Thread.sleep (500);
}
catch(InterruptedException interruptedException)
{
System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException);
}
}
}
}
class SecondThread implements Runnable
{
SecondThread()
{
Thread t=new Thread(this);
t.start();
}
public void run()
{
for ( int i=1; i<=10; i++)
{
System.out.println( "Messag from Second Thread : " +i);
try
{
Thread.sleep(500);
}
catch (InterruptedException interruptedException)
{
System.out.println( "Second Thread is interrupted when it is sleeping" +interruptedException);
}
}
}
}
public class ThreadDemo
{
public static void main(String args[])
{
FirstThread firstThread = new FirstThread();
Thread thread1 = new Thread(firstThread);
thread1.start();
SecondThread secondThread = new SecondThread();
}
}
Output:
Labels: Java Programming Lab
Wednesday, December 14, 2016
Write a JAVA program for creation of user defined exception.
Write a JAVA program for creation of user defined exception.
import java.util.Scanner;
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("You Are not eligible to vote");
else
System.out.println("You are Eligible, welcome to vote");
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Age");
int a=sc.nextInt();
try
{
validate(a);
}
catch(Exception m)
{
System.out.println(" Exception occured: "+m);
}
}
}
Labels: Java Programming Lab
Write a JAVA program to illustrate sub class exception precedence over base class.
Write a JAVA program to illustrate sub class exception precedence over base class.
import java.io.*;class Parent
{
void msg()throws ArithmeticException
{
System.out.println("parent");
int a=10,b=0;
int c=a/b;
}
}
class TestExceptionChild extends Parent
{
void msg()
{
int arr[]=new int[4];
System.out.println("child");
arr[4]=4;
}
public static void main(String args[]){
Parent p=new TestExceptionChild();
try
{
p.msg();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception Caught");
}
}
}
Labels: Java Programming Lab
Write a JAVA program for example of try and catch block. In this check whether the given array size is negative or not.
Write a JAVA program for example of try and catch block. In this check whether the given array size is negative or not.
import java.util.*;class Neg_Arr_Size_Exep
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of Array");
int n=sc.nextInt();
try
{
int[] arr=new int[n];
for(int i=0;i<arr.length;i++)
{
System.out.println("enter "+i+" th element");
arr[i]=sc.nextInt();
}
System.out.println("Elements of Array");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
catch(NegativeArraySizeException e)
{
System.out.println("Exception Caught: You have Given Negative Array Size");
}
}
}
Labels: Java Programming Lab
Write a JAVA program that describes exception handling mechanism.
Write a JAVA program that describes exception handling mechanism.
import java.util.Scanner;class DivisionByZero
{
public static void main(String[] args)
{
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
// try block
try
{
result = a / b;
System.out.println("Result = " + result);
}
// catch block
catch (ArithmeticException e)
{
System.out.println("Exception caught: Division by zero.");
}
}
}
Labels: Java Programming Lab
Write a JAVA program demonstrating the difference between method overloading and constructor overloading.
Write a JAVA program demonstrating the difference between method overloading and constructor overloading.
class Student{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Student s1 = new Student(111,"hasini");
Student s2 = new Student(222,"shirley",1);
s1.display();
s2.display();
s1.sum(10.5,10.5);
s1.sum(20,20);
}
}
Labels: Java Programming Lab
Tuesday, December 13, 2016
Write a JAVA program demonstrating the difference between method overloading and method overriding.
Write a JAVA program demonstrating the difference between method overloading and method overriding.
class Base{
void run()
{
System.out.println("Method from Base Class");
}
}
class OverLoad extends Base
{
void run()
{
System.out.println("Method from Derived Class");
}
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
OverLoad ovl=new OverLoad();
ovl.sum(10.5,10.5);
ovl.sum(20,20);
ovl.run();
Base b=new OverLoad();
b.run();
}
}
Labels: Java Programming Lab
Thursday, December 8, 2016
Write a JAVA program that illustrates multi-level inheritance
Aim: Write a JAVA program that illustrates multi-level inheritance.
Program:
class Add
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
}
class Subtract extends Add
{
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class Multiplication extends Subtract
{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[])
{
int a = 20, b = 10;
Multiplication demo = new Multiplication();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Output:
Labels: Java Programming Lab
Monday, December 5, 2016
Write a JAVA program to check whether given string is palindrome or not.
Aim: Write a JAVA program to check whether given string is palindrome or not.
Program:
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
Output:
Labels: Java Programming Lab
Write a JAVA program to sort an array of strings
Aim: Write a JAVA program to sort an array of strings.
Program:
import java.util.Scanner;
public class Alphabetical_Order
{
public static void main(String[] args)
{
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}
Output:
Labels: Java Programming Lab
Write a JAVA program to determine multiplication of two matrices.
Aim: Write a JAVA program to determine multiplication of two matrices.
Program:
import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();
System.out.println("Enter the number of rows and columns of second matrix");
p = in.nextInt();
q = in.nextInt();
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = in.nextInt();
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
System.out.println("Product of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
}
}
}
}
Output:
Labels: Java Programming Lab
Write a JAVA program to determine the subtraction of two matrices.
Aim: Write a JAVA program to determine the subtraction of two matrices.
Program:
import java.util.Scanner;
class SubTwoMatrix
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
int second[][] = new int[m][n];
int sum[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
second[c][d] = in.nextInt();
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] - second[c][d]; //replace '-' with '+' to add matrices
System.out.println("Sum of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
System.out.print(sum[c][d]+"\t");
System.out.println();
}
}
}
Output:
Labels: Java Programming Lab
Write a JAVA program to determine the addition of two matrices.
Aim: Write a JAVA program to determine the addition of two matrices.
Program:
import java.util.Scanner;
class AddTwoMatrix
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
int second[][] = new int[m][n];
int sum[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
second[c][d] = in.nextInt();
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices
System.out.println("Sum of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
System.out.print(sum[c][d]+"\t");
System.out.println();
}
}
}
Output:
Labels: Java Programming Lab
Write a JAVA program to search for an element in a given list of elements using binary search mechanism.
Aim: Write a JAVA program to search for an element in a given list of elements using binary search mechanism.
Program:
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
Output:
Labels: Java Programming Lab