Q. Write a program to compute the area of rectangle, square and circle using overloading function. get area(int, int), get area(int) and get area(double a)
Solution:
import java.io.*;
public class AreaCalc // Class started
{
int l,b,s,ar1;
double r,ar2;
int area(int a) // Area of Square
{
s=a;
ar1=s*s;
return ar1;
}
int area(int x,int
y) // Area of Rectangle
{
l=x;
b=y;
ar1=l*b;
return ar1;
}
double area(double
x) // Area of Circle
{
r=x;
ar2=Math.PI*r*r;
return ar2;
}
public static void
main(String args[])throws IOException
{
int a;
double ar;
AreaCalc
ob=new AreaCalc();
a=ob.area(10);
System.out.println("Area Of Square="+a);
a=ob.area(10,5);
System.out.println("Area
Of Rectangle="+a);
ar=ob.area(5.5);
System.out.println("Area Of Circle="+ar);
}
} // end of class
Output:
Area Of Square=100
Area Of Rectangle=50
Area Of Circle=95.03317777109123
Q2. Write a program
to accept a number from user and check whether the number in Peterson or not,
using a function (int n). A Peterson number is a number whose sum of factorial
of all the digit is the number itself E.g., 145 = 1! + 4! + 5! = 1 + 24 +120 =
145
Solution:
import java.io.*;
/**
* class PetersonNumber
*/
public class PetersonNumber
{
// instance
variables
private int n;
private int f;
public int
peterson(int x)
{
f=1;
n=x;
for(int i=1;
i<=n; i++)
{
f=f*i;
}
return f;
}
public static void
main(String args[])throws IOException
{
// Local
variable
int a, b, n,
m, s=0;
PetersonNumber
ob=new PetersonNumber ();
InputStreamReader in=new InputStreamReader (System.in);
BufferedReader br=new BufferedReader(in);
System.out.print("Enter a number: ");
n =
Integer.parseInt(br.readLine());
m=n; // Store the n value to m
while(n!=0)
{
a = n %
10;
b =
ob.peterson(a);
s = s + b;
n = n /
10;
}
if(m == s)
{
System.out.println ("PetersonNumber");
}
else
{
System.out.println ("Not PetersonNumber");
}
}
} // end of class
Output:
Enter a number: 145
PetersonNumber
Enter a number: 273
Not PetersonNumber
Q3. Write a program
to design a method called void sumEven(int start, int end) to take start and
end limit from the main(). The function will display the number of even number
and the sum of all the even number between start and end (both inclusive)
Solution:
import java.io.*;
public class SumEven
{
int s,i,start,end;
void sumEven(int s
,int e)
{
start=s;
end=e;
s=0;
for(i=start;i<=end;i++)
{
if(i%2==0)
{
s=s+i;
System.out.print(i+" ");
}
}
System.out.println("\n Sum even="+s);
}
public static void
main(String args[])throws IOException
{
// Local
variable
int a, b;
SumEven ob=new
SumEven ();
InputStreamReader in=new InputStreamReader (System.in);
BufferedReader
br=new BufferedReader(in);
System.out.print("Enter start and end:
");
a =
Integer.parseInt(br.readLine());
b =
Integer.parseInt(br.readLine());
ob.sumEven(a,b);
}
}
Output:
Enter start and end: 5
30
6 8 10 12 14 16 18 20 22 24 26 28 30 Sum even=234