1

I have a task to do and I'm struggling with it:

Write a BASH script that reads student names and grades from a file into an array. Prompt the user for a student name. Using the binary search method, find the name in the array and display the grade. If the student does not exist, print a message stating that.

And here is the data in the file:

Ann:A
Bob:C
Cindy:B
Dean:F
Emily:A
Frank:C
Ginger:D
Hal:B
Ivy:A
Justin:F
Karen:D

So, what I did first was to create a file in my Linux OS called "students" in my home directory with the structure above. Then in my BASH script I created the following script:

#!/bin/bash

#Store from a file called "students" the first field before " : " into array
names=( $( cut -d: -f1 students ) )

#Store from a file called "students" the second field after " : " into array
grades=( $( cut -d: -f2 students ) )

echo "Enter the Student Name:"
read inputname

for i in "${names[@]}"; do
    echo $i;
done

for j in "${grades[@]}"; do
    echo $j;;
done

With that information I can now see when each array is "co-related" (like for example in the "names array" we have Ann, in the "grades array" we have her score of "A", and so on)

My problem is how can I "link" these two informations? When for example someone inputs Bob, it will automatically output "Bobs grade is C" or stuffs like that? Is it possible to "link" two array values (like in the namesarray[0] equivalent to gradesarray[0], namesarray[1] equivalent to gradearray[1] and so on) in BASH ? Or am I doing something wrong here that I'm missing?

Thank you for your help!

1 Answers1

1

Think of it as the following: you enter a student into your "students" array, lets say it is the very first name so you are at array index 0. Now, you immediately enter that students grade into another array, at index 0. You already have a "link" from one array to another. So what you need to do when you are searching for a student, is to count the index and pass that number into a function which goes through your "grades" array and use that parameter in your for loop.

psudo code

count = 0;
for(...){ ..
//student not found yet, keep going
count ++;
//student found! cool now find the grade.
gradeFind(count);
}

gradeFind(int count){
     for(i=0; i<grades_size; i++){
         if (i == count) { return the grade}
}
binjamin
  • 123
  • 1
  • 13
  • Hi @Leonardo have the answers you've got fully answered your question? If they have [comment above] or if not can you edit your question to clarify why they haven't and include any missing information. If they have, consider marking the answer as "accepted". – binjamin Nov 02 '19 at 18:38
  • 1
    THANK YOU!!!! Now everything makes sense for me haha I was doing a linear search and I forgot to use the count to find the student, then find the grade. (I used a While loop instead of For, but worked fine). – Leonardo Barbosa Nov 05 '19 at 00:23
  • No problem! glad you figured it out – binjamin Nov 05 '19 at 00:30