You are on page 1of 55

1

JAVA ASSIGNMENT

Submitted by – Ananya Bhagat


Roll no.-21C3008
Submitted to- Er. Mrs. Jyoti Haveliya
2

INDEX
* ASSIGNMENT 1 (3-9)
* ASSIGNMENT 2 (10-22)
* ASSIGNMENT 3 (23-34)
* ASSIGNMENT 4 (34- )

ASSIGNMENT – 1

Q1. Write a program to swap two variables without


using the third variable.

->CODE:
import java.util.*;
class swap{
public static void main(String args[]){
int x = 10;
int y = 5;
x = x + y;
3

y = x - y;
x = x - y;
System.out.println("After swapping:" + " x = " + x + ", y
= " + y);
}
}
OUTPUT:-
After swapping: x = 5, y = 10
__________________

Q2.Write a program of finding average of five


numbers .The numbers should be
entered at run time.

->CODE:
import java.util.*;
class average{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("enter the numbers");
int a= sc.nextInt();
4

int b= sc.nextInt();
int c= sc.nextInt();
int d= sc.nextInt();
int e= sc.nextInt();
int average;
average = (a+b+c+d+e)/5;
System.out.print(average);
}
}
OUTPUT:- enter the numbers 1 2 3 4 5
3
__________________
Q3.write a java program which takes two numbers as
input and display the product of two numbers.

->CODE:
import java.util.*;
class multi{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("enter a number");
5

int a = sc.nextInt();
System.out.println("enter other number");
int b = sc.nextInt();
int c;
c=a*b;
System.out.println("multiplication is: "+c); }
}
OUTPUT:- enter a number
3
enter other number
4
multiplication is: 12.
__________________

Q4.Write a java program to create a calculator using


switch case where two numbers and one operator
must be entered at the runtime.

->CODE:
import java.util.*;
class calci{
6

public static void main(String args[]){


Scanner sc=new Scanner(System.in);
System.out.print("enter the number");
int a= sc.nextInt();
System.out.print("enter the number");
int b= sc.nextInt();
System.out.print("Enter an num (1,2,3,4,5) ");
int num = sc.nextInt();

switch(num) {
case 1 : System.out.println("sum of two numbers is " +
(a+b));
break;
case 2 : System.out.println("difference of two numbers
is " +(a-b));
break;
case 3 : System.out.println("multi of two numbers is "
+(a*b));
break;
case 4 : System.out.println("division of two numbers is
" +(a/b));
break;
7

case 5 : System.out.println("remainder of two numbers


is " +(a%b));
break;
default: System.out.println("invalid");
break;
}
}
}
OUTPUT:- enter the number60
enter the number5
Enter an num (1,2,3,4,5) 4
division of two numbers is 12
__________________

Q5.Write a program to print the area and perimeter of


the circle.

->CODE:
import java.util.*;
class areaperiofcircle{
public static void main(String args[]){
8

Scanner sc=new Scanner(System.in);


System.out.println("enter the radius of circle");
double r=sc.nextDouble();
double pi=3.142;
double area=(pi)*(r*r);
double perimeter=2*(pi)*r;
System.out.println("area is: "+area);
System.out.println("perimeter is: "+perimeter);
}
}
OUTPUT:- enter the radius of circle
3
area is: 28.278
perimeter is: 18.852
__________________

Q6.write a java program to compare two numbers.

->CODE:
import java.util.*;
class compare{
9

public static void main(String args[]){


Scanner sc = new Scanner(System.in);
System.out.println("enter the value of x");
int x=sc.nextInt();
System.out.println("enter the value of y");
int y=sc.nextInt();
if(x>y){
System.out.print("outcome: " + x);
}else{
System.out.print("outcome: "+ y);
}
}
}
OUTPUT:- enter the value of x
3
enter the value of y
5
outcome: 5
__________________
10

Q7.write a java program to cheak whether java is


installed on your computer.

->CODE:
class installversion{
public static void main(String args[]){
System.out.println("\nJava Version: " +
System.getProperty("java.version"));
System.out.println("\nJava Runtime Version: " +
System.getProperty("java.runtime.version"));
System.out.println("\nJava Home: " +
System.getProperty("java.home"));
System.out.println("\nJava Vendor: " +
System.getProperty("java.vendor"));
System.out.println("\nJava Vendor URL: " +
System.getProperty("java.vendor.url"));
System.out.println("\nJava Class Path: " +
System.getProperty("java.class.path") + "\n");
}
}
OUTPUT:- C:\Users\Hp\Desktop\javaP>java
installversion
Java Version: 18.0.2.1
11

Java Runtime Version: 18.0.2.1+1-1


Java Home: C:\Program Files\Java\jdk-18.0.2.1
Java Vendor: Oracle Corporation
Java Vendor URL: https://java.oracle.com/
Java Class Path: .
__________________

Q8.write a java program that takes a number as input


and prints its multiplication table upto 10.

->CODE:
import java.util.*;
class table{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("enter the number");
int a=sc.nextInt(),i;
for(i=1;i<=10;i++){
System.out.println(a + " * " + i + " = " + a * i);
}
}
12

}
OUTPUT:- enter the number
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
__________________

Q9.Write a java program to cheak wether the entered


no. is Armstrong or not.

->CODE:
import java.util.*;
class armstrong{
public static void main(String args[]){
13

Scanner sc = new Scanner(System.in);


System.out.println("enter the number");
int n= sc.nextInt();
int rem,sum=0,check;
check=n;
while(check!= 0){
rem = check % 10;
sum = sum + (rem*rem*rem);
check = check/10;
}
if(sum==n){
System.out.println("the no is armstrong no");
} else{
System.out.println("the no is not armstrong");
}
}
}
OUTPUT:- C:\Users\Hp\Desktop\javaP>java armstrong
enter the number
134
the no is not armstrong
14

C:\Users\Hp\Desktop\javaP>java armstrong
enter the number
153
the no. is armstrong no.
__________________

Q10.Write a java program to compute the area of


hexagon.

->CODE:
import java.util.*;
class areaofhexagon{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("enter the length of hexagon");
Double s = sc.nextDouble();
Double area;
area =( Math.sqrt(3)*3*s*s)/2;
System.out.print("area is: "+area);
}
}
15

OUTPUT:- enter the length of hexagon 3


area is: 23.382685902179844
__________________

Q11.Write a program in java to convert temperature


from Celsius to Fahrenheit
using if else.

->CODE:
import java.util.*;
class conversiontemp{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the temperature");
double c = sc.nextDouble();
double f;
f=c*(1.8)+32;
System.out.print(f);
}
}
16

OUTPUT:- C:\Users\Hp\Desktop\javaP>java
conversiontemp
Enter the temperature 45
Temperature in farenheit: 113.0
__________________

Q12.Write a java program to calculate the factorial of


an integer.

->CODE:
import java.util.*;
class test{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("enter the number");
int n = sc.nextInt();
int factorial=1;
for(int i=1;i<=n;i++){
factorial = factorial *i;
}
17

System.out.println("factorial of number is:


"+factorial);
}
}
OUTPUT:- java -cp /tmp/ef6DNbyn7a test
enter the number6
factorial of number is: 720
__________________

Q13.Write a java program to compute the sum of the


digit of an integer.

->CODE:
import java.util.*;
class digitsum{
public static void main(String args[]){
int n,m,sum=0;
Scanner sc = new Scanner(System.in);
System.out.print("enter the number");
m = sc.nextInt();
while(m>0){
18

n = m % 10;
sum+=n;
m = m/10;
}
System.out.print("sum of digits is: "+ sum);
}
}
OUTPUT:- C:\Users\Hp\Desktop\javaP>java digitsum
enter the number 153
sum of digits is: 9
__________________

Q14.Write a java program to print the max value and


min value of integer data type.

->CODE:
class maxmin{
public static void main(String[] arg) {
System.out.println("Integer.MAX_VALUE = " +
Integer.MAX_VALUE);
19

System.out.println("Integer.MIN_VALUE = " +
Integer.MIN_VALUE);
}
}
OUTPUT:- Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483647
-------------------------------------------------------------
20

ASSIGNMENT-2
1.Write a program to print the following
pattern:
654321
65432
6543
654
65
6
Code:
public class Assignment2 {

public static void main(String a[]){


int a1;
Scanner s=new Scanner(System.in);
a1=s.nextInt();
for (int i=1;i<=a1;i++)
{ for(int j=a1;j>=i;j--)
{ System.out.print(j+" ");}
System.out.print("\n");
}
}
21

Output:

2.Write a program to print the following pattern:


*
* *
* * *
* *
*

Code:
import java.util.Scanner;
public class Assignment2 {
public static void main(String a[]){
Scanner s=new Scanner(System.in);
int a1= s.nextInt();
int star=1,spaces=a1/2;
for (int i=1; i<=a1 ;i++)
{ for (int j=1;j<=spaces;j++)
{
System.out.print(" ");
22

}
for (int k=1;k<=star;k++)
{
System.out.print('*'+" ");
}
if (i==(a1+1)/2 && a1%2==0)
{System.out.print("\n");continue;}
else if(i<(a1+1)/2)
{spaces=spaces-1;
star=star+1;}
else{ spaces=spaces+1;
star=star-1;}
System.out.print("\n");
}
} }
Output:

3. Write a program to display Fibonacci series


up to a given term.
Code:
import java.util.Scanner;
public class Assignment2 {

public static void main(String a[]){


23

Scanner s=new Scanner(System.in);


int a1=s.nextInt();
int first=0,second=1,third;
System.out.print(first+" "+second+” “);
for (int i=1;i<=a1-2;i++)
{ third=first+second;
System.out.print(third+" ");
first=second;
second=third;}
} }
Output:

4. Write a program to print the following pattern:


(a)
(a + b)
(a + b + c)
(a + b + c + d)
(a + b + c + d + e)
(a + b + c + d + e + f)

Code:
24

import java.util.Scanner;
public class Assignment2 {
public static void main(String a[]){
Scanner s=new Scanner(System.in);
int a1=s.nextInt();
for (int i=1;i<=a1;i++)
{ int x=97;
for(int j=1;j<=i;j++)
{ if (j==1){
System.out.print("(");
}
System.out.print((char)x);
x++;
if (j<i)
{
System.out.print("+");
}
if (j==i)
{
System.out.print(")");
}
}
System.out.print("\n");
}
}}

Output:
25

5. Write a program to print sum of series (i.e. 0, 1,


4, 9, 16…).
Code:
import java.util.Scanner;
public class Assignment2 {

public static void main(String a[]){


Scanner s=new Scanner(System.in);
int a1=s.nextInt();
int sum=0;
for(int i=0;i<a1;i++)
{sum=sum+(i*i);}
System.out.println(sum);
}}

Output:

6. Write a program to print sum of series (i.e. 1 +


1/1! + 2/2! + 3/3! + 4/4! +…..).
Code:
import java.util.Scanner;
public class Assignment2 {
public static void main(String a[]){
Scanner s=new Scanner(System.in);
int a1=s.nextInt();
26

float sum=1;
for(int i=1;i<a1;i++)
{sum=sum+(float)i/factorial(i);}
System.out.println(sum);
}
static int factorial(int n)
{ int f1=1;
for (int i=1;i<=n;i++)
{ f1=f1*i;}
return f1;
}
}
Output:

7. Write a program to demonstrate widening and


narrowing in java.
Code:
public class Assignment2 {
public static void main(String a[]){
//Widening
int x=20;
long y=x;
float z=y;
System.out.println(x);
System.out.println(z);
//Narrowing
double a1=65.34;
int i=(int)a1;
char c=(char)i;
27

System.out.println(i);
System.out.println(c);
}}

Output:

8. Write a program to find sum of natural numbers


from 1 to 100.
Code:
import java.util.Scanner;
public class Assignment2 {
public static void main(String a[]){
Scanner s=new Scanner(System.in);
int a1=s.nextInt();
int sum=0;
sum=a1*(a1+1)/2;
System.out.println("Sum upto first "+a1+"numbers is
"+ sum);}
}
Output:
28

9. Write a program to calculate the sum of numbers


entered by the user until user enters 0.
Code:
import java.util.Scanner;
public class Assignment2 {
public static void main(String a[]){
int a1,sum=0;
Scanner s=new Scanner(System.in);
do { a1=s.nextInt();
sum=sum+a1;
}while(a1!=0);
System.out.println("Sum is "+sum);
}}
Output:

10 .Write a program to find the size of a specified file.


Code:
import java.io.File;
public class filesize {
public static void main(String a[]){
File file = new File("C:\\Users\\varun\\
Desktop\\Java prog");
long bytes = file.length();
System.out.println("Size is "+bytes);
}
}
Output:
29

11. Write a program to display the current date time in


specific format.
Code:
import java.time.LocalDate;
public class DateTime {
public static void main(String a[]){
LocalDate myObj = LocalDate.now();
System.out.println(myObj);
}}
Output:

12. Write a program to calculate the sum of two


integers and return true if the sum is equal to a
third integer.
Code:
import java.util.Scanner;
public class IntegerSum {
public static void main(String a[]){
Scanner s=new Scanner(System.in);
int a1=s.nextInt();
int a2=s.nextInt();
int a3=s.nextInt();
int sum=a1+a2;
30

if (sum==a3)
{
System.out.println("True");
}
}}
Output:

13. Write a program to convert decimal to binary


equivalent.
Code:
import java.util.Scanner;
public class DecimalConversion {
public static void main(String a[]){
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int i=0,ans=0;
while (n>0)
{ int digit=n%2;
ans+=(int)(Math.pow(10,i++))*digit;
n/=2;}
System.out.println(ans);
}}
Output:
31

14. Write a program to convert binary to octal


equivalent.
Code:
import java.util.Scanner;
public class BinaryConversion {
public static void main(String a[]){
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int k=0,ans=0,digit,res=0;
while (n>0)
{ ans=0;
for (int j=0;j<3;j++)
{digit=n%10;
ans=ans+digit*(int)(Math.pow(2,j));
n/=10;}
res+=(int)(Math.pow(10,k++))*ans;
}
System.out.println(res);}
}

Output:

15. Write a program to find factorial of 60.


Code:
import java.util.Scanner;
public class factorial60 {
public static void main(String a[]){
32

Scanner s=new Scanner(System.in);


double a1= s.nextDouble();
double f1=1;
for (double i=1;i<=a1;i++)
{f1=f1*i;}
System.out.println("Factorial is "+f1);
}}
Output:

.
16 Write a program to check whether the
following number is prime or not:
21000254869723212850.
Code:
import java.util.Scanner;
public class factorial60 {
public static void main(String a[]){
Scanner s=new Scanner(System.in);
double a1= s.nextDouble();
for(double d=2;d*d<=a1;d++)
{if(a1%d==0)
{
System.out.println("Composite number");
break;
}}
}}

Output:
33

-------------------------------------------------------------
34

ASSIGNMENT -3
1.Create a “circle” class & a “point” class. The
coordinates of the circle are given and used within
the “circle” class as object of the “point” class.
Display the area of circle.
Code:
public class point {
private float x,y;

public point() {
x = 0f;
y = 0f;
}

public point(float x1, float y1) {


x = x1;
y = y1;
}

public void setX(int x) {


this.x = x;
}

public void setY(int y) {


this.y = y;
}

public void display() {


System.out.println("(" + x + "," + y + ")");
}

public class circle {


private point center = new point();
private point outer = new point();
float calculateArea()
{
float area = 0f;
float dis = center.distance(outer);
35

area = 3.14f*dis*dis;
return area;
}
void setCenter(int x, int y)
{
center.setX(x);
center.setY(y);
}
void setOuter(int x, int y)
{
outer.setX(x);
outer.setY(y);
}
public static void main(String args[])
{
circle c1 = new circle();
c1.setCenter(0,0);
c1.setOuter(4,3);
c1.outer.display();
System.out.println("AREA = " +
c1.calculateArea());
}
}
Output:

2.Create a class called Time, which has three


private instance variables- hour, min and sec. It
contains a method called add() which takes one
Time object as parameter and print the added
value of the calling Time object and passes Time
object. In the main method, declare two Time
36

objects and assign values using constructor and


call the add() method.
Code:
public class Time {
private int hours,minutes,seconds;
Time()
{ hours=0;
minutes=0;
seconds=0;
}
Time(int h,int m,int s)
{ hours=h;
minutes=m;
seconds=s;
minutes+=s/60;
seconds=s%60;
hours+=minutes/60;
minutes=minutes%60;
}
void setseconds(int s)
{seconds=s;
minutes+=s/60;
seconds=s%60;}
void setminutes(int m)
{minutes=m;
hours+=m/60;
minutes=m%60;}
void sethours(int h)
{hours=h;}
Time add(Time t)
{ Time obj=new Time();
obj.hours = hours + t.hours;
obj.minutes = minutes + t.minutes;
obj.seconds = seconds + t.seconds;
obj.minutes += obj.seconds / 60;
obj.seconds %= 60;
obj.hours += obj.minutes / 60;
obj.minutes %= 60;
System.out.println("ADDED VALUE =" +
obj.hours + ":" + obj.minutes + ":" + obj.seconds);
return obj;
37

}
void display()
{
System.out.println(hours + ":" + minutes +
":" + seconds);
}
public static void main(String a[])
{ Time t1 = new Time(14,61,80);
Time t2 = new Time(11,65,25);
t1.display();
t2.display();
t1 = t1.add(t2);
}
}
Output:

3.Create a class called complex ,which has three


private instance variables- real and imaginary. It
contains a method called add() which takes one
Complex object as parameter and print the added
value of the calling Complex object and passes
Complex object. In the main method, declare two
complex objects and assign values using
constructor and call the add() method.
Code:
public class complex {
private double real, imaginary;

complex() {
real = 0;
38

imaginary = 0;
}

complex(double r, double i) {
real = r;
imaginary = i;
}

void display() {
System.out.println(real + " + " + imaginary +
"i");
}

void setReal(double r)
{
real = r;
}
void setImaginary(double i)
{
imaginary = i;
}
double getReal()
{
return real;
}
double getImaginary()
{
return imaginary;
}
complex add(complex c1)
{
complex obj = new complex();
obj.real = real + c1.real;
obj.imaginary = imaginary + c1.imaginary;
System.out.println("ADDED VALUE = " +
obj.real + " + " + obj.imaginary + "i");
return obj;
}
public static void main(String args[])
{
complex c1 = new complex(3,4);
complex c2 = new complex(2,9);
c1.display();
c2.display();
39

c1 = c1.add(c2);
}
}
Output:

4.Write a program to define a class having one 3-


digit number, num as data member. Initialize and
display reverse of that number.
Code:
import java.util.Scanner;

public class reverse


{ private int num;
reverse(int n)
{
num=n;
}
void digitrev()
{ int n1=num;
int rev=0,rem;
while(n1!=0)
{ rem=n1%10;
rev=rem+rev*10;
n1=n1/10;}
System.out.println("REVERSE IS :"+rev);
}
public static void main(String a[])
{ Scanner s=new Scanner(System.in);
reverse r1=new reverse(s.nextInt());
r1.digitrev();
}
}
Output:
40

5.Write a program to define a class Student with


four data members such as name, roll no., sub1,
sub2. Define appropriate methods to initialize and
display the values of data members. Also calculate
total marks and percentage scored by student.
Code:
public class student {
private int roll_no, sub1, sub2;
private String name;
student(String name, int roll_no, int sub1, int
sub2)
{
this.name = name.toUpperCase();
this.roll_no = roll_no;
this.sub1 = sub1;
this.sub2 = sub2;
}
void setSub1(int sub1)
{
this.sub1 = sub1;
}
void setSub2(int sub2)
{
this.sub2 = sub2;
}
void setName(String n)
{
name = n;
}
double getPercentage()
{
return(sub1+sub2)/2.0;
}
void displayDetails()
41

{
System.out.println("NAME : " + name);
System.out.println("ROLL NO : " + roll_no);
System.out.println("MARKS IN EACH SUBJECT --
>");
System.out.println("SUBJECT 1: " + sub1 +
"/100");
System.out.println("SUBJECT 2: " + sub2 +
"/100");
System.out.println("TOTAL MARKS : " +
(sub1+sub2) + "/200");
System.out.println("PERCENTAGE : " +
getPercentage() + "%");
}
public static void main(String args[])
{
student s1 = new student("Abc",2145,88, 92);
s1.displayDetails();
}
}
Output:

6.Write a program to define a class Employee to


accept emp_id, emp_name, basic_salary from the
user and display the gross_salary.
Code:
public class employee{ private int emp_id;
private String emp_name;
private double basic_salary, gross_salary;
42

employee() {
emp_id = 00000;
basic_salary = 0;
gross_salary = 0;
emp_name = "New emp";
}
employee(String name, int id, double salary)
{ emp_name = name;
emp_id = id;
basic_salary = salary;
setGross_salary();
}

void setEmp_id(int id) {


emp_id = id;
}

void setEmp_name(String name) {


emp_name = name;
}

void setBasic_salary(double salary) {


basic_salary = salary;
}

void setGross_salary() {
gross_salary = basic_salary *2.4;
}

void displayDetails() {
System.out.println("EMPLOYEE DETAILS --
>");
System.out.println("NAME : " +
emp_name.toUpperCase());
System.out.printf("ID : %05d\n",emp_id);
System.out.printf("BASIC SALARY : %.2f\
n",basic_salary);
System.out.printf("GROSS SALARY : %.2f\
n",gross_salary);
}

public static void main(String args[])


{
employee e1 = new employee("Abc", 3748,
43

50000);
e1.displayDetails();
employee e2 = new employee();
e2.displayDetails();
}
}
Output:

7.Write a program to define a class Fraction


having data members numerator and
denominator. Initialize three objects using
different constructors and display its fractional
value.
Code:
public class fraction {
private int numerator, denominator;
fraction()
{
numerator = 0;
denominator = 1;
}
fraction(int num)
{
numerator = num;
denominator = 1;
}
44

fraction(int num, int den)


{
numerator = num;
denominator = den;
}
void setNumerator(int x)
{
numerator = x;
}
void setDenominator(int x)
{
denominator = x;
}
void displayFraction()
{
System.out.printf("THE NUMBER IN FRACTIONAL
FORMAT IS = %d/%d\n",numerator,denominator);
System.out.printf("THE NUMBER IN RATIONAL
FORMAT IS = %.4f\n",((float)numerator/denominator));
}
public static void main(String a[])
{
fraction f1 = new fraction();
fraction f2 = new fraction(8);
fraction f3 = new fraction(3,7);
f1.setNumerator(25);
f1.setDenominator(31);
f2.setDenominator(7);
f1.displayFraction();
System.out.println("---------------------------------
-------------------");
f2.displayFraction();
System.out.println("---------------------------------
-------------------");
f3.displayFraction();
}
}
45

Output:

-------------------------------------------------------------
46

ASSIGNMENT-4
1. Code and compile following :
public class Static {
private String name = "Static class";
public static void first() { }
public static void second() { }
public void third() { System.out.println(name); }
public static void main(String args[]) {
first();
second();
third();
}}
Observe the compilation error and try to fix the error.
Corrected code is to be included in file.
Output:

Corrected Code:
public class Static {
private static String name="Static class";
public static void first(){};
public static void second(){};
public static void third()
{System.out.println(name);};
public static void main(String a[])
{ first();
second();
third();
}
}
47

2. Code and test the following , NOTE the output and


justify it.
public class Percolate {
public static void main (String[] args) {
int[] dataSeq = {6,4,8,2,1};
printIntArray(dataSeq);
for (int index = 1; index < dataSeq.length; ++index)
if (dataSeq[index-1] > dataSeq[index])
swap(dataSeq, index-1, index);
printIntArray(dataSeq);
}
public static void swap(int[] intArray, int i, int j) {
int tmp = intArray[i]; intArray[i] = intArray[j];
intArray[j] = tmp;
}
public static void swap(int v1, int v2) {
int tmp = v1; v1 = v2; v2 = tmp;
}
public static void printIntArray(int[] array) {
for (int value : array)
System.out.print(" " + value);
System.out.println();
}
}
Output:

//Since array is passed as a parameter swap


function which swaps elements of an array is
48

called which is an example of function


overloading.

3. Write and test the following method that returns digit


number k of the positive integer n:
static int digit(long n, int k)
For example, digit ( 8 6 4 2 1 , 3 ) would return 6, and
digit ( 8 6 4 2 1 , 7 ) would return 0.
Code:
import java.util.Scanner;
public class digit {
static int digit(long n,int k)
{ long n1=n;
int i=0;
while (i<k)
{n1=n1/10;
i++;}
int rem=(int)(n1%10);
return rem;}
public static void main(String arg[])
{
Scanner s=new Scanner(System.in);
long n1=s.nextLong();
int n2=s.nextInt();
int a=digit(n1,n2);
System.out.println(a);
}

}
Output:

4. Write and test the following recursive method


that returns the nth triangular number:
49

static long t(int n)


The triangular numbers are 0, 1,3,6, 10,
15,21,28, ... . Note that t(n) = t(n-1) + n for n > 1.
Code:
import java.util.Scanner;
public class triangularNum {
static int number(int n)
{
if(n==1)
return 1;
if (n==0)
return 0;
else return number(n-1)+n;
}
public static void main(String arg[])
{
Scanner s=new Scanner(System.in);
int n1=s.nextInt();
int a=number(n1);
System.out.println(a);
}}
Output:

5. Write a program to multiply two matrices (the


rows and column of matrix must be entered at run
time).
Code:
import java.util.Scanner;
public class multiplication {
public static void main(String arg[])
{
System.out.println("Enter rows and columns");
Scanner s=new Scanner(System.in);
int r1=s.nextInt();
50

int c1=s.nextInt();
int r2=s.nextInt();
int c2=s.nextInt();
int a1[][]=new int[r1][c1];
int a2[][]=new int[r2][c2];
System.out.println("Enter matrix 1");
for (int i=0;i<r1;i++)
{for (int j=0;j<c1;j++)
{a1[i][j]=s.nextInt();}
}
System.out.println("Enter matrix 2");
for (int i=0;i<r2;i++)
{for (int j=0;j<c2;j++)
{a2[i][j]=s.nextInt();}
}

if (c1==r2)
{int i=0,j=0,a3[][]=new int[r1][c2];
for ( i=0;i<r1;i++)
{ int k=0;
for ( j=0;j<c2;j++)
{a3[i][j]=0;
for(int x=0;x<c1;x++)
{a3[i][j]=a3[i][j]+a1[i][x]*a2[x][j];}
}
}
System.out.println("Product matrix is ");
for (i=0;i<r1;i++)
{for(j=0;j<c2;j++)
{
System.out.print(a3[i][j]+" ");
}
System.out.println();}
}
}
}
Output:
51

6. Write a program to check whether the entered


matrix is identity matrix or not.
Code:
import java.util.Scanner;
public class identity_matrix {
public static void main(String arg[])
{ int r,c;
Scanner s=new Scanner(System.in);
r=s.nextInt();
c=s.nextInt();
int arr[][]=new int[r][c];
for (int i=0;i<r;i++)
{for(int j=0;j<c;j++)
{arr[i][j]=s.nextInt();}
}
loop:
for (int i=0;i<r;i++)
{for(int j=0;j<c;j++)
{if (i!=j && arr[i][j]!=0)
{System.out.println("Not an identity
matrix");
break loop;}
if (i==j && arr[i][j]!=1)
{System.out.println("Not an identity
matrix");
break loop;}
if (i==r-1 && j==c-1)
{
52

System.out.println("Identity matrix");
}
} } }
}
Output:

7. Write a program to print the reverse of array


element.
Code:
import java.util.Scanner;
public class array_reversal {
public static void main(String arg[])
{ int n;
Scanner s=new Scanner(System.in);
n=s.nextInt();
int arr[]=new int[n];
for (int i=0;i<n;i++)
{arr[i]=s.nextInt();}
int n1=n/2,temp;
for (int i=0;i<n1;i++)
{ temp=arr[i];
arr[i]=arr[n-1-i];
arr[n-1-i]=temp;
}
for (int value:arr)
{
System.out.print(value+" ");
}
}
}
Output:
53

8. Write a Java program to find the duplicate


values of an array of integer values.
Code:
import java.util.Scanner;
public class duplicate {
public static void main(String arg[]) {
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
for (int i=0;i<n;i++)
{for(int j=i;j<n;j++)
{if (i==j){continue;}
if (arr[i]==arr[j])
{System.out.print(arr[i]+" ");
continue;}
}
}
}
}
Output:
54

9. Write a Java program to find the number of


even and odd integers in a given array of integers.
Code:
import java.util.Scanner;
public class EvenOrOdd { public static void
main(String arg[]) {
int n,e=0;
Scanner s = new Scanner(System.in);
n = s.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
for (int i=0;i<n;i++)
{if (arr[i]%2==0)
e++;}
System.out.println("Number of even elements "+e);
System.out.println("Number of odd elements "+ (n-
e));}
}
Output:

10. Write a program to find the average of 5


numbers. (numbers should be entered at command
line.)
Code:
public class average {
public static void main(String arg[]) {
int sum=0;
for (int i = 0; i <arg.length; i++) {
sum+=Integer.parseInt(arg[i]);
55

}
System.out.printf("The average is %.4f",
(float)sum/5);
}
}

Output:

--------------------------------------------------------

You might also like