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.*;
import java.util.Scanner;
class clPaperA
{
void fnLinkA()
{
Scanner sc = new Scanner(System.in);
System.out.print(" Enter the number of elements :");
int n = sc.nextInt();
int LA[ ] = new int [n];
for(start = 0; start < n; start++)
{
max = LA[start];
position = start;
for(range = start + 1; range < n; range++)
{
if(max > LA[range])
{
max = LA[range];
position = range;
{
}
}
tmp = LA[start]; //swapping
LA[start] = LA[position];
LA[position] = tmp;
System.out.println(" The elements in Ascending Order ...");
for(r = 0; r < n; r++)
{
System.out.print(LA[r] + " ");
}
}
}Code Writing
Advertisements
Solution
Syntax Errors: java.util.* has not been imported, but scanner class has been used. Many variables have not been declared before use. The array limits are wrong.
Logical Errors: The array has not been filled. The swap should have been inside the 'for' loop of start.
The corrected program is:
import java.util.*;
class clPaperA
{
void fnLinkA()
{
Scanner sc = new Scanner(System.in);
System.out.print(" Enter the number of elements: ");
int n = sc.nextInt();
int LA[ ] = new int [n];
for(int s = 0; s < n; s++)
{
System.out.print("Enter element " + s+ " : ");
LA[s] = sc.nextInt();
}
for(int start = 0; start <n; start++)
{
int max = LA[start];
int position = start;
for(int range = start+1; range < n; range++)
{
if(max > LA[range])
{
max = LA[range];
position = range;
}
}
int tmp = LA[start]; //swapping
LA[start] = LA[position];
LA[position] = tmp;
}
System.out.println(" The elements in Ascending Order...");
for(int r = 0; r <n; r++(
{
System.out.print(LA[r] +" ");
}
}
}
Output:
Enter the number of elements: 5
Enter element 0 : 99
Enter element 1 : 22
Enter element 2 : 88
Enter element 3 : 33
Enter element 4 : 66
The elements in Ascending Order... 22 33 66 88 99
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?
