English

Write a program for the following. Create a String array FC[ ] and a numeric array FP[ ] of size 10, to store the names of 10 Food Crops and their annual production in corresponding cells.

Advertisements
Advertisements

Question

Write a program for the following.

Create a String array FC[ ] and a numeric array FP[ ] of size 10, to store the names of 10 Food Crops and their annual production in corresponding cells. Sort the arrays in ascending order of their annual production. [Apply Selection Sort].[Suggestion : Take data from Geography Textbook].

Code Writing
Advertisements

Solution

import java.util.Scanner;
public class FoodCropSorter 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);       
        String FC[] = new String[10];
        double FP[] = new double[10];         
        System.out.println("Enter 10 Food Crops and their Annual Production (in million tons):");
        for (int i = 0; i < 10; i++) {
            System.out.print("Enter name of crop " + (i + 1) + ": ");
            FC[i] = sc.nextLine();
            System.out.print("Enter annual production for " + FC[i] + ": ");
            FP[i] = sc.nextDouble();
            sc.nextLine(); // Consume the leftover newline character
        }        
        for (int start = 0; start < 10; start++) 
        {
            double minProduction = FP[start];
            int minPosition = start;            
            for (int range = start + 1; range < 10; range++) {
                if (FP[range] < minProduction) {
                    minProduction = FP[range];
                    minPosition = range;
                }
            }
            double tempProduction = FP[start];
            FP[start] = FP[minPosition];
            FP[minPosition] = tempProduction;            
            String tempCrop = FC[start];
            FC[start] = FC[minPosition];
            FC[minPosition] = tempCrop;
        }        
        System.out.println("\nSorted Crops in Ascending Order of Annual Production:");
        System.out.println("---");
        System.out.printf("%-15s | %s\n", "Food Crop", "Annual Production (Million Tons)");
        System.out.println("---");
        for (int i = 0; i < 10; i++) {
            System.out.printf("%-15s | %.1f\n", FC[i], FP[i]);
        }        
        sc.close();
    }
}
shaalaa.com
  Is there an error in this question or solution?
Chapter 8: Arrays - Sort & Search - Exercises [Page 200]

APPEARS IN

Rupa Pandit Computer Applications [English] Class 10 ICSE
Chapter 8 Arrays - Sort & Search
Exercises | Q 4. (v) | Page 200
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×