Quiz 2
Quiz 2
Question 1.
Show the steps that are involved in sorting the string SORTME using the quicksort
algorithm given below.
#include <iostream.h>
void quicksort(char *a, int l, int r);
main() {
char str[8] = "9SORTME"; // 9 is a sentinel.
quicksort(str, 1, 6);
}
char v = a[r];
Answer:
int i = l - 1;
int j = r;
S O R T M E
while (1) {
quicksort(a, l, i-1);
quicksort(a, i+1, r);
}
}
Question 2.
Show how you would translate the bold portions of the following C++ code into Java.
#include <iostream.h>
class Shape {
private:
float x, y;
public:
Shape(float a, float b) {
x = a;
y = b;
public:
Circle(float a, float b, float r) : Shape(a, b) {
radius = r;
} Answer:
float compute_area() {
void print() {
Shape::print();
}
};
void main() {
Circle a(3,4,2);
a.print();
}
Question 3.
In the following C++ program, the outputData() function can handle callbacks such as
plot() and print(). How would you complete the given Java code to implement a similar
capability?
#include <iostream.h>
class Point {
private:
int x, y;
public:
Point(int a = 0, int b = 0) {
x = a;
y = b;
void print() {
cout << x << " " << y << endl;
}
};
void plot(Point &p) { // Assume that this plots the point p on the screen.
cout << "In plot:" << endl;
p.print();
}
void print(Point &p) { // Assume that this prints out the coordinates of p.
cout << "In print:" << endl;
p.print();
}
void main() {
Point a[2];
a[0] = Point(2,3);
a[1] = Point(4,5);
outputData(plot, a, 2);
outputData(print, a, 2);
}
Answer:
class Point {
private int x, y;
x = a;
y = b;
void print() {
class Plotter
class Printer
class Main {
static void outputData( ){
Question 4.
Show how you would complete the given Java code, so that it achieves the effect shown
in the Figure below.
Answer:
import java.awt.*;
import javax.swing.*;
class Main {
public static void main(String args[]) {
JFrame f = new JFrame();
f.setSize(250,250);
f.setVisible(true);
}
}
Question 5.
How you would you change the background color of the panel when the mouse moves
over the application’s window?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Main {
public static void main(String args[]) {
Answer:
f.setContentPane(p);
f.setSize(250,250);
f.setVisible(true);
}
}
Question 6.
The following applet contains several errors. Explain what changes you would make to
correct the code, so that the applet displays the current frame number.
Answer:
/*
<APPLET CODE=MyApplet.class WIDTH=250 HEIGHT=100>
</APPLET>
*/
import java.awt.*;
import javax.swing.*;
Thread t = null;
int count = 0;
getContentPane().add(new JPanel() {
});
t = new Thread();
t.start();
count++;
repaint();
Thread.sleep(100);
Question 7.
What is double buffering and why is it important in animation? How do the Swing
classes differ from the AWT classes in this respect?
Answer:
Question 8.
Show how you would extract the number 1.124 from the string "Hello 1.124 World!" and
then store it in a float variable.
Answer: