Selection in Array
Table of Content:
An array allows selection of an element for a given (random) index. Therefore, the array is also called random access data structure. The selection operation is useful in a situation wherein the user wants query about the contents of a list for a given position.
Example: Write a program that stores a merit list in an array called ‘Merit’. The index of the array denotes the merit position, i.e., 1st, 2nd, 3rd, etc. whereas the contents of various array locations represent the percentage of marks obtained by the candidates. On user’s demand, the program displays the percentage of marks obtained for a given position in the merit list as per the following format:
Position: 4
Percentage: 80
Solution: An array called ‘Merit’ would be used to store the given merit list. Two variables pos and percentage would be used to store the merit position and the percentage of a candidate, respectively. A do-while loop would be used to iteratively interact with the user through following menu displayed to the user:
Menu:
Query----1
Quit------2
Enter your choice
Note: As per the demand of the program, we will leave the zeroth location as unused and fill the array from index 1.
The required program is given below:
/* This program illustrates the random selection operation allowed by array data structures */ #include void main() { float Merit[30]; int size; int i; int pos; float percentage; int choice; printf ("\n Enter the size of the list"); scanf ("%d", &size); printf ("\n Enter the merit list one by one"); for (i = 1; i <= size; i++) /* Read Merit */ { printf ("\n Enter data:"); scanf ("%f", &Merit[i]); } /* display menu and start session */ do { printf ("\n Menu"); printf ("\n Query--------1"); printf ("\n Quit--------2"); printf ("\n Enter your choice: "); scanf ("%d", & choice); /* use switch statement for determining the choice*/ switch (choice) { case 1: printf("\n Enter Position"); scanf("%d", &pos); percentage = Merit[pos]; /* the random selection */ printf ("\n position = %d", pos); printf ("\n percentage = %4.2f",percentage); break; case 2: printf ("\n Quitting"); } printf ("\n press a key to continue…"); } while (choice != 2); }
Output
Enter the size of the list 5 Enter the merit list one by one Enter data:65 Enter data:70 Enter data:75 Enter data:80 Enter data:90 Menu Query--------1 Quit--------2 Enter your choice: 1 Enter Position4 position = 4 percentage = 80.00 press a key to continue… Menu Query--------1 Quit--------2 Enter your choice: 2 Quitting press a key to continue…