Advertisements
Advertisements
Question
The following code may contain some errors. Identify the errors, modify the program by underlining the changes made, and write the aim of the program.
import java.io.*;
class clPaperB
{
int TY[];
clPaperB(int n)
{
TY = new int [n];
{
void fnInputB()
{
Scanner sc = new Scanner(System.in);
int s = TY.length;
for(int j = 0; j <= s − 1; j++)
{
System.out.print("Enter value for cell num " + j +" : ");
TY[j] = sc.nextInt();
}
}
void fnWorkB()
{
for(int p = 0; p<=s; p++)
{
for(int q = 0; q<=sp; p++)
{
if(TY[q+1]> TY[q])
{
tmp = TY[p];
TY[p] = TY[p +1];
TY[p + 1] = tmp;
}
}
}
}
void fnShow()
{
System.out.println(" The elements in Descending Order ...")
for(int j = 0; j<=s - 1; j++)
System.out.print(" TY[j] ");
}
}Code Writing
Advertisements
Solution
Syntax errors: Variable s is local to method fnInputB(). It should be made of member data. Variable 'tmp' has not been declared.
Logical Error: in bubble sort, elements are printed inside quotes as string.
importjava.util.*;
class clPaperB
{
int TY[]; int s;
clPaperB(int n)
{
TY = new int [n];
}
void fnInputB()
{
Scanner sc = new Scanner(System.in);
s = TY.length;
for(int j = 0; j <= s - 1; j++)
{
System.out.print("Enter value for cell num" + j +" : ");
TY[j] = sc.nextInt();
}
}
void fnWorkB()
{
for(int p =0; p<s; p++)
{
for(int q = 0; q<=s-p-2; q++)
{
if(TY[q + 1]> TY[q])
{
int tmp = TY[q];
TY[q] = TY[q+1];
TY[q+1] = tmp;
}
}
}
}
void fnShow()
{
System.out.println(" The elements in descending-Order ...");
for (int j = 0; j <= s - 1; j++)
System.out.print(TY[j] + " "
}
}
Output:
Enter elements: 55 22 88 66 44
The elements in descending order...
88 66 55 44 22
Aim: The aim of this programme is to arrange the data in ascending order.
shaalaa.com
Is there an error in this question or solution?
Chapter 8: Arrays - Sort & Search - Exercises [Page 198]
