Programming In Java | Week 3

Programming In Java | Week 3

Course Link: https://onlinecourses.nptel.ac.in/noc23_cs74/course

Programming Assignment

1. This program is related to the generation of Fibonacci numbers.
For example: 0,1, 1,2, 3,5, 8, 13,… is a Fibonacci sequence where 13 is the 8th Fibonacci number.
A partial code is given and you have to complete the code as per the instruction given .

Solution:

if (n==1)     
    	return 0;
    else if(n==2)
    	return 1;
    return fib(n - 1) + fib(n - 2); 

2. Define a class Point with two fields x and y each of type double. Also, define a method distance(Point p1, Point p2) to calculate the distance between points p1 and p2 and return the value in double.

Solution:

class Point{
  double x;
  double y;

public static void distance(Point p1,Point p2)
	{
      double d;
	  d=Math.sqrt((p2.x-p1.x)*(p2.x-p1.x) + (p2.y-p1.y)*(p2.y-p1.y));
	  System.out.print(d);
    }
}

3. A class Shape is defined with two overloading constructors in it. Another class Test1 is partially defined which inherits the class Shape. The class Test1 should include two overloading constructors as appropriate for some object instantiation shown in main() method. You should define the constructors using the super class constructors. Also, override the method calculate( ) in Test1 to calculate the volume of a Shape.

Solution:

double height;
	Test1(double length,double h) {
    //base class constructor with one parameter is called
		super(length);
		height=h;
	}

	Test1(double length,double breadth,double h) {
    //base class constructor having two argument is called
		super(length,breadth);
		height=h;
	}

	double calculate()	{
		return length*breadth*height;
	}

4. This program to exercise the call of static and non-static methods. A partial code is given defining two methods, namely sum( ) and multiply ( ). You have to call these methods to find the sum and product of two numbers. Complete the code segment as instructed.

Solution:

QScope st = new QScope();
int result1=st.sum(n1,n2);
int result2=QScope.multiply(n1,n2);
System.out.println(result1);
System.out.print(result2);

5. Complete the code segment to swap two numbers using call by object reference.

Solution:

public static void swap(Question t)
    {
    	int temp = t.e1;
        t.e1 = t.e2;
        t.e2 = temp;
    }

* The material and content uploaded on this website are for general information and reference purposes only !

Please do it by your own first!

DMCA.com Protection Status

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments



0
Would love your thoughts, please comment.x
()
x