Thread: Homework Help - Use of Functions in Top/Down Approach

  1. #1
    Registered User
    Join Date
    Mar 2014
    Posts
    27

    Homework Help - Use of Functions in Top/Down Approach

    I'm getting a bit lost in calling functions correctly and was hoping someone had some time to steer me in the right direction. The assignment says to,

    Referencing programming Assignment #2, reprogram this assignment using functions and include the additional features identified below -
    Design your program so the main function invokes/calls functions to perform the following tasks:

    4) sort the arrays in ascending order by student ID number
    Here's what I've got thus far and I'm confused cuz I might be calling my function incorrectly. Thanks for any help y'all can give.

    Code:
    #include <stdio.h>
    #define MAX_ENTRIES 50
    
    void s_ID (int student_ID[], int test_score[], char char_val[]);
    int main (void)
    {
        /*I need to set my array to allow for up to 50 students and their
        test scores and set my "count" variable as well as the i. There will
        also need to be a variable for average test score, highest score,
        and the corresponding grade values. */
        int student_ID[MAX_ENTRIES];                                //student ID counter
        int test_score[MAX_ENTRIES];                                //test score counter
        int count = 0;                                        /*number of elements in ID, score
                                                        and grade arrays*/
        char char_val;                                        //A, B, C, D, F
        //Start to fill my Array with Student IDs and test scores
        while (count < MAX_ENTRIES && student_ID[count] != 0)
        {
            printf("Enter a student's ID: ");
            scanf("%i", &student_ID[count]);
                   if ( student_ID[count] == 0 )
                       break;
                   printf("Enter the student's test score: ");
                   scanf("%i", &test_score[count]);
                       while ( test_score[count] < 0 || test_score[count] > 100 )
                           printf("The test score you entered is invalid. Please re-enter.\n");
                           printf("Enter the student's test score: ");
                           scanf("%i", &test_score[count]);
                ++count;
        }
    
        s_ID(student_ID[], test_score[]; char_val[]);                //sort student_ID low --> high
    
        return 0;
    }    //end main
    
    void s_ID (int student_ID[], int test_score[], char char_val[], int count)    //array to sort student_ID l --> h
    {
        int i, j, temp;
        for (i = 0; i < count - 1; ++i)
            for (j = i + 1; j < count; ++j)
                    if ( student_ID[i] > student_ID[j])
                    {
                        temp = student_ID[i];
                        student_ID[i] = student_ID[j];
                        student_ID[j] = temp;
                    }
    //sort test_score array to match the student_ID array sort
                    if ( test_score[i] > test_score[j])
                    {  //sort test_score to match the student_ID sort
                        temp = test_score[i];
                        test_score[i] = test_score[j];
                        test_score[j] = temp;
                    }
    //sort char_val array to match the student_ID array sort
                    if ( char_val[i] > char_val[j])
                    {
                        temp = char_val[i];
                        char_val[i] = char_val[j];
                        char_val[j] = temp;
                    }
    
    }    //end function s_ID

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Good work on getting a proper main declaration, having reasonable comments and using a constant (MAX_ENTRIES). I have two complaints/concerns:
    1. Why not call your function something like sort_by_ID? You should never sacrifice clarity and readability to save a few keystrokes.
    2. Your indentation is a bit off. C is not Python, so indentation does not affect flow control. Use curly braces everywhere, even if there is just one line of code in a loop or if/else statement.

    The second point may be part of your issue. Use the auto-indent feature of your editor if it has one. Your code does not line up right in your sort_by_ID function.

    Also, you are calling the function incorrectly, since char_val is a single char, but the parameter to sort_by_ID is a char array. If this is the letter grade for each student, then it should be declared as an array in main, so each student can have their own grade. Also, you shouldn't have the [ ] brackets when you pass arrays to a function (they're only in the declaration of the function), and you have a ; where you should have a , when you call sort_by_ID.

    Note, your title mentions a top-down approach. Basically that means you start at a high level, describing the major steps of your program. Each of those would become a function. You do the same in each of those functions: describe it's major steps. Each of those becomes a function. Repeat until you have sufficient granularity, that is, until you are writing small, maintainable functions that each do one thing only, and do it very well. For example, I would start with
    Code:
    int main(void)
    {
        count = get_input(student_IDs, test_scores);
        sort_by_ID(student_IDs, test_scores, count);
        print_output(student_IDs, test_scores, count);
        return 0;
    }
    ...
    sort_by_ID(student_IDs, test_scores, count)
    {
        for i from 0 to count-1
            for j from i+1 to count
                if out of order
                    swap(student_IDs at i and j)
                    swap(test_scores at i and j)
    }
    Note, swap in this case would be it's own function, as would get_input and print_output.

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    top down approach
    This could mean that you're supposed to implement a top down sort algorithm, such as quick sort or a top down merge sort. What sort algorithms have been presented in your class?

  4. #4
    Registered User
    Join Date
    Mar 2014
    Posts
    27
    I'm going to address this out of order. Sorry. @rcgldr: I think what the instructor means by "top/down" is using the Bubble Sort method. I'm going to use it twice: once to sort ascending order by student_ID[] and once for descending order by test_score[]. If I can get the ascending order straight, all I do is switch a less-than symbol to greater-than and I've got my descending order, correct?

    @anduril462: Thanks for the input. I'm getting some interesting error messages. (I use Eclipse Kepler on OpenSUSE 12.3 kde, if that helps any.)
    Description Resource Path Location Type
    conflicting types for ‘sort_by_ID’ Assignment3_v2-build.c /Assignment3_v2-build/src line 42 C/C++ Problem
    make: *** [src/Assignment3_v2-build.o] Error 1 Assignment3_v2-build C/C++ Problem

    Description Resource Path Location Type
    previous declaration of ‘sort_by_ID’ was here Assignment3_v2-build.c /Assignment3_v2-build/src line 19 C/C++ Problem
    If these issues are more eclipse-related than C, I'll figure that out elsewhere.

    Additionally, I've tried to make adjustments per your suggestions of more curly brackets, removing the ";" and "[]" when not needed. I didn't use the "swap" method you suggested b/c we haven't learned it yet, but I will be using a switch/case statement later on. If I forgot anything, it was unintentional. Again, thanks for helping. Here's the updated code which is still giving issues:

    Code:
    /*********************************************
    Student Name: Nick Hardesty
    Course Number: 90.267-001
    Program Assignment Number: Assignment 3
    Date: 01 Apr 2014
    Program Objective: The purpose of this
    programming assignment is to reinforce the use
    of functions, including the “passing” of
    arrays to a function, the return of a value
    from a function and the return of an array
    index from a function. The use of functions in
    the top/down and modular approach to program
    design and development is stressed.
    **********************************************/
    
    #include <stdio.h>
    #define MAX_ENTRIES 50
    
    void sort_by_ID (int student_ID[], int test_score[], char char_val[]);
    int main (void)
    {
        /*I need to set my array to allow for up to 50 students and their
        test scores and set my "count" variable as well as the i. There will
        also need to be a variable for average test score, highest score,
        and the corresponding grade values. */
        int student_ID[MAX_ENTRIES];                            //student ID counter
        int test_score[MAX_ENTRIES];                            //test score counter
        int count = 0;                                            /*number of elements in ID, score
                                                                    and grade arrays*/
        char char_val[MAX_ENTRIES];                                //A, B, C, D, F
    
        //Start to fill my Array with Student IDs and test scores
        while (count < MAX_ENTRIES && student_ID[count] != 0)
        {
            printf("Enter a student's ID: ");
            scanf("%i", &student_ID[count]);
                   if ( student_ID[count] == 0 )
               {
                       break;
               }
                   printf("Enter the student's test score: ");
                   scanf("%i", &test_score[count]);
                       while ( test_score[count] < 0 || test_score[count] > 100 )
               {
                           printf("The test score you entered is invalid. Please re-enter.\n");
                           printf("Enter the student's test score: ");
                           scanf("%i", &test_score[count]);
               }
                ++count;
        }
    
        sort_by_ID(student_ID, test_score, char_val);                //sort student_ID low --> high
    
        return 0;
    }    //end main
    
    void sort_by_ID (int student_ID[], int test_score[], char char_val[], int count)    //array to sort student_ID l --> h
    {
        int i, j, temp;
        for (i = 0; i < count - 1; ++i)
            for (j = i + 1; j < count; ++j)
            //sort student_ID array lowest --> highest
                    if ( student_ID[i] > student_ID[j])
                    {
                        temp = student_ID[i];
                        student_ID[i] = student_ID[j];
                        student_ID[j] = temp;
                    }
            //sort test_score array to match the student_ID array sort
                    if ( test_score[i] > test_score[j])
                    {
                        temp = test_score[i];
                        test_score[i] = test_score[j];
                        test_score[j] = temp;
                    }
            //sort char_val array to match the student_ID array sort
                    if ( char_val[i] > char_val[j])
                    {
                        temp = char_val[i];
                        char_val[i] = char_val[j];
                        char_val[j] = temp;
                    }
    
    }    //end function s_ID

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by boygenuis View Post
    I'm going to address this out of order. Sorry. @rcgldr: I think what the instructor means by "top/down" is using the Bubble Sort method. I'm going to use it twice: once to sort ascending order by student_ID[] and once for descending order by test_score[]. If I can get the ascending order straight, all I do is switch a less-than symbol to greater-than and I've got my descending order, correct?
    Well, if that's what the assignment asks of you, then that would be the correct thing to do. But more typical sorting terms are ascending, descending, increasing or decreasing. Top-down usually refers to the design/implementation method I spoke of: starting at the "highest" or top level of design, the biggest steps, working to a successively smaller steps until the program is done. It is what is referred to in the "Program Objective" section in the comment on lines 6-13. I really think having a get_grades() function and print_grades() function would be a good idea -- even if it's not required, it's still good design, and wont hurt anything. Imagine, if you want to print the grades several times, after sorting by ID, then score, grade, etc. You don't want to have to copy-paste the whole print code each time when you could just repeat a simple one-line function call.

    Quote Originally Posted by boygenuis View Post
    @anduril462: Thanks for the input. I'm getting some interesting error messages. (I use Eclipse Kepler on OpenSUSE 12.3 kde, if that helps any.)

    If these issues are more eclipse-related than C, I'll figure that out elsewhere.
    Those errors are definitely C related:

    How you declare your function (prototype, line 19), define it (lines 57-84) and call it (line 52) must all match in: return type, number of parameters and types of corresponding parameters. Your prototype does not reflect the actual function. The compiler works from the first line of your file to the last, in order. It does not look ahead. It sees the prototype taking 3 arguments and thinks that when you call it, you should call it with 3 arguments, which you do. So line 19 and 52 match. But the actual function takes 4 arguments, hence the "conflicting types". Either update your prototype to match the actual function or move sort_by_ID above main(). Then the compiler will complain that you are not passing enough arguments to sort_by_ID on line 52, and you can fix that.

    Two minor nits, your end function s_ID comment should reflect the new function name. Also, I think letter_grade would be a better, more descriptive name than char_val. Describe the purpose or the variable at a high level. How would you describe that data to another human? If you told me "here is your student ID, test score and char value", I would be confused. "Student ID, test score and letter grade" makes sense.


    Quote Originally Posted by boygenuis View Post
    I didn't use the "swap" method you suggested b/c we haven't learned it yet,
    It is not a built-in function you would learn. It is a function you would write. Again, this is good modular design. Your swap function is a reusable, modular unit. It would swap any two ints you pass in. Write, test and debug your swap code once, call it a million times:
    Code:
    void swap(int *a, int *b);
    // call it like so
    swap(&student_ID[i], &student_ID[j]);
    You would write that function, which would do the whole swap two values using a temp variable thing. Then, you would call it with each array you want to swap elements of: student_ID, test_score, char_val.

    Imagine you had 1000 arrays to swap, and you wrote out separate swap code for each, as you did above. Now imagine you made a mistake that you copy-pasted 999 times. That's 1000 fixes to make instead of 1 in the swap function. And you're likely to miss at least one spot out of the 1000, causing you more grief, debugging, etc. This is why functions, modular design, etc is considered such good practice.

    Quote Originally Posted by boygenuis View Post
    but I will be using a switch/case statement later on. If I forgot anything, it was unintentional. Again, thanks for helping. Here's the updated code which is still giving issues:
    You forgot to fix the curly bracket issues in sort_by_ID. You're only sorting one array, the other two are outside the loops. But you don't simply want to move them inside the loop. They're not quite right...

    Think carefully about this: when you are sorting by student ID values, if you want to swap two student IDs, you must also swap the corresponding scores and letter grades or else the data gets out of sync. I think you understand this, but your code does not reflect this. You should only have one condition for swapping here, when student IDs are out of order (line 63). If they are out of order, you swap corresponding elements from all 3 arrays. That is, one if statement with 3 swaps inside it. You do not want separate conditions for when to swap test_score and char_val.

    Last note: Eclipse is an integrated development environment (IDE). It's software that bundles code editors, debuggers, compilers and other tools into a single interface to manage projects. The compiler you're using (which is what produces those errors) does not look like GCC, but I don't recognize it. Clang perhaps? The compiler is the more relevant tool when discussing compiler errors/warning, though which one, version, etc doesn't matter for the errors you see -- they're easy enough to figure out once you grok the slightly technical language. A mis-configured project in your IDE can cause problems, though that does not seem to be the case here.

  6. #6
    Registered User
    Join Date
    Mar 2014
    Posts
    27
    Thanks for all the input. I'm still working on building the rest so I'll have more questions later, but the beginning code works.

    Code:
      	 	 	 	   #include <stdio.h>
    
     #define MAX_ENTRIES 50
     
    
     int fill_array (int student_ID[], int test_score[]);
     void sort_by_ID (int student_ID[], int test_score[], int grade_count[], int count);
     int main (void)
     {
         /*I need to set my array to allow for up to 50 students and their
         test scores and set my "count" variable as well as the i. There will
         also need to be a variable for average test score, highest score,
         and the corresponding grade values. */
    
         int student_ID[MAX_ENTRIES];                                                    //student ID counter
    
         int test_score[MAX_ENTRIES];      	                                              						//test score counter
    
         int grade_count[MAX_ENTRIES];                                                							//total number of grades
    
         int count = 0;                                                                                      										/*number of elements in ID, score
    
                                                                                                                                      and grade arrays*/
    
     
    
         count=fill_array(student_ID, test_score);                                     							//invoke the function to fill my arrays
    
     	
     	sort_by_ID(student_ID, test_score, grade_count, count);         //sort student_ID low --> high
    
     
    
         return 0;
     }    //end main
     
    
     int fill_array (int student_ID[], int test_score[])
     {
          	int count = 0;
    
     	
         //Start to fill my Array with Student IDs and test scores
           while (count < MAX_ENTRIES && student_ID[count] != 0)
    
              {
    
                               printf("Enter a student's ID: ");
    
                               scanf("%i", &student_ID[count]);
    
                                      if ( student_ID[count] == 0 )
    
                      	       		{
    
                                                      break;
    
                      	       		}
    
                       printf("Enter the student's test score: ");
    
                       scanf("%i", &test_score[count]);
    
                                         if ( test_score[count] < 0 )
    
                                        {
    
                                                		printf("The test score you entered is invalid. Please re-enter.\n");
    
                                                 	printf("Enter the student's test score: ");
    
                                                 	scanf("%i", &test_score[count]);
    
                                       }
    
                                       else if ( test_score[count] > 100 )
    
                    		   			{
    
                   	 	   				printf("The test score you entered is invalid. Please re-enter.\n");
    
                                         	printf("Enter the student's test score: ");
    
                                         	scanf("%i", &test_score[count]);
    
                 }
                                ++count;
    
              }
    
     
    
              return count;
    
     }
     
    
     void sort_by_ID (int student_ID[], int test_score[], int grade_count[], int count)    //array to sort student_ID l --> h
     {
              int i, j, temp;
    
              for (i = 0; i < count - 1; ++i)
    
                  for (j = i + 1; j < count; ++j)
    
     		//sort student_ID array lowest --> highest
                          if ( student_ID[i] > student_ID[j])
    
                          {
    
                              temp = student_ID[i];
    
                              student_ID[i] = student_ID[j];
    
                              student_ID[j] = temp;
    
                     //sort test_score array to match the student_ID array sort
    
                              temp = test_score[i];
    
                              test_score[i] = test_score[j];
    
                              test_score[j] = temp;
    
                     //sort grade_count array to match the student_ID array sort
    
                              temp = grade_count[i];
    
                              grade_count[i] = grade_count[j];
    
                              grade_count[j] = temp;
    
                          }
    
     
    
     }    //end function s_ID

  7. #7
    Registered User
    Join Date
    Mar 2014
    Posts
    27
    I seem to be stuck on my switch/case statement and my binary search for highest test score. I sort the test scores high-to-low before I do the binary search, but it just returns a high score of 70, student ID of 70 and a grade of F when they should be 92, 1955, and A, respectively. Additionally, the switch/case statement just gives me one count for each grade letter and not the 2 As, 2 Bs, 3 Cs, 1 D, and 3 Fs I expect. Can someone provide a nudge? Thanks.
    Input data:
    1653

    77

    1945
    72
    1020
    50
    1955
    92
    1030
    40
    1200
    72
    1500
    91
    1100
    90
    1900
    81
    1005
    95
    1790

    43

    1800

    85

    0



    Code:
    #include <stdio.h>
    #define MAX_ENTRIES 50
    
    int high_score_search (int test_score[], int student_ID[], int count);
    
    char char_val_func (char grade[], int count);
    int main (void)
    {    
        /*I need to set my array to allow for up to 50 students and their
        test scores and set my "count" variable as well as the i. There will
        also need to be a variable for average test score, highest score,
        and the corresponding grade values. */
        int student_ID[MAX_ENTRIES];                //student ID counter
        int test_score[MAX_ENTRIES];                //test score counter
        int count = 0;                        /*number of elements in ID, score
                                      and grade arrays*/
        int high_score;                                //one test score to rule them all
        int high_stud_ID;                            //you're the best around. Nothin's gonna keep you down
        int A, B, C, D, F;                            //the number of each grade letter
        
        char grade[MAX_ENTRIES];                    //total number of grades
        char high_grade;                            //you're the tops
    
        count=fill_array(student_ID, test_score);            //invoke the function to fill my arrays
        high_score=high_score_search(test_score, student_ID, count);        //display the highest score...
        high_stud_ID=high_score_search(test_score, student_ID, count);                //the corrosponding student ID...
        high_grade=high_score_search(test_score, student_ID, count);                //and with highest grade letter
             printf("The highest test score is %i.\n", high_score);
             printf("The student ID with the highest test score is %i.\n", high_stud_ID);
             printf("The highest letter grade is %c.\n", high_grade);
         
         A=char_val_func(grade, count);                                                //Print the number of each grade letter from the char_val_func function...
             printf ("The number of As is: %2i\n", A);
        B=char_val_func(grade, count);
            printf ("The number of Bs is: %2i\n", B);
        C=char_val_func(grade, count);
            printf ("The number of Cs is: %2i\n", C);
        D=char_val_func(grade, count);
            printf ("The number of Ds is: %2i\n", D);
        F=char_val_func(grade, count);
            printf ("The number of Fs is: %2i\n", F);
    
        return 0;
    }
    
    int high_score_search (int test_score[], int student_ID[], int count)
    {
       int i;
       int first = 0;
       int last = count - 1;
       int middle;
       int high_score = 0;
       int high_stud_ID = 0;
       char high_grade;
       
        high_score = test_score[0];
        for(i = 0; i < count; ++i)
        {
            if( test_score[i] > high_score )
            {
                high_score = test_score[i];
                   high_stud_ID = student_ID[i];
           
               return high_stud_ID;
            }
            if ( high_score >= 90 )
                high_grade = 'A';
            else if ( high_score >= 80 )
                    high_grade = 'B';
            else if
                ( high_score >= 70 )
                    high_grade = 'C';
            else if 
                ( high_score >= 60 )
                    high_grade = 'D';
            else if
                (high_score <= 59 )
                    high_grade = 'F';
            
            return high_grade;
        }
       
       while (first <= last)
       {
          middle = (first + last) / 2;
    
          if (high_score == test_score[middle])
          {
             return high_score;
          }
          else (high_score > test_score[middle]);
          {
             first = middle + 1;
          }
       }
       return high_score;
       
    }    //end high_score_search
    
    char char_val_func (char grade[], int count)
    {
        int i = 0;
        int A;
        int B;
        int C;
        int D;
        int F;
        
        while (i < count)
        {
            switch (grade[i])
            {
                case 'A':
                            ++A;
                            return A;
                case 'B':
                            ++B;
                            return B;
                case 'C':
                            ++C;
                            return C;
                case 'D':
                            ++D;
                            return D;
                case 'F':
                            ++F;
                            return F;
            }
        }
    }

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Why are you doing a binary search if everything is already sorted by test score? Shouldn't the highest score just be at the beginning/end of the array?

    Your char_val_func is broken. You have a return right after the ++A, ++B, etc. So your function returns right away. What happened to your grade_count array? Why did you get rid of it?

    You need to put the keyboard aside for a moment, and figure this out with paper and pencil, in your own language. How would you do this if you just had a list of student ID/score/grade? If you had to go through and count all the A's, B's, etc? If you can't describe the process clearly in your native language, how can you instruct a computer to do it in a foreign language like C?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 08-02-2011, 12:30 PM
  2. homework help wanted - Class member functions
    By DHart07 in forum C++ Programming
    Replies: 16
    Last Post: 09-29-2010, 12:43 AM
  3. entry level homework help: Passing Arrays into functions.
    By DHart07 in forum C++ Programming
    Replies: 8
    Last Post: 04-21-2010, 09:11 AM
  4. Replies: 8
    Last Post: 04-19-2006, 09:07 AM
  5. Homework Help Using Functions
    By Trekkie in forum C++ Programming
    Replies: 10
    Last Post: 11-21-2005, 02:42 AM

Tags for this Thread