Like Tree2Likes
  • 1 Post By laserlight
  • 1 Post By std10093

Need some guidance with an assignment please - arrays and functions

This is a discussion on Need some guidance with an assignment please - arrays and functions within the C Programming forums, part of the General Programming Boards category; Hi, Im hoping someone can give me some guidance point me in the right direction with an assignment I have. ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    5

    Need some guidance with an assignment please - arrays and functions

    Hi, Im hoping someone can give me some guidance point me in the right direction with an assignment I have.

    I have done the first part, i think??, which is to allow the user to enter up to 10 numbers in total with a choice of yes or no if they want to continue entering up to that point. They are to be stored in an array.

    Now the bit I am struggling with is, once the numbers have been entered the program should work out the total value, smallest number, largest number, the average, display the numbers in ascending order and also show the range, all to be displayed on screen. I've used bubblesort to reorganise the numbers but Im not really sure how it works.

    I feel completly lost and it needs to be finished for next week.

    heres what I have done so far:
    ·

    Code:
    #include<stdio.h>
    Code:
      
      int obtainNumber(int numbers[]);
      
      void displaynumbers(int numbers[10], int lastIndex);
      void bubbleSort(int numbers[], const int arrayLength);
      void swap(int *p, int *q);
      
      int main()
      {
      
       const int arraySize = 10;
       int numbers[arraySize];
       int lastIndex;
          lastIndex; obtainNumber(numbers);
      
       int lastIndex = 10;
      
          printf ("starting array contents  \n");
          displayNumbers (numbers, lastIndex);
      
          bubbleSort (numbers, lastIndex + 1);
      
          printf (" \n After sorti8ng array\n");
          displayNumbers (numbers, lastIndex);
      
      
          system("pause");
       return 0;
      }
      
      int obtainNumber(int numbers[])
      {
       int index = -1;
       char option = 'y';
       while(option == 'y' || option == 'Y')
            {
               index = index + 1;          
               printf("Enter a number: ");
               scanf("%i", &numbers[index]);
               _flushall();
       if (index < 9)
               {
                  printf("Do you want to enter another number?('y' for yes 'n' for no) ");
                  scanf("%c", &option);
                 _flushall();
               }
       else
               {
                   option = 'n';
               }
            }
       return index;
      }
      
      
      
                  printf ("starting array contents  \n");
                  displayNumbers (numbers, lastIndex);
      
                  bubbleSort (numbers, lastIndex + 1);
      
                  printf (" \n After sorti8ng array\n");
                  displayNumbers (numbers, lastIndex);
      
                  system ("pause");
       return 0;
      
                  }
      
       void displayNumbers (int numbers[], int lastIndex)
                  {
                       printf ("The contents of the array is:\n");
       int i = 0;
       while (i <= lastIndex)
      
                       {
                            printf ("%i\n", numbers [i]);
                            i++;
      
                            }
                       }
      
      
      
      void bubbleSort (int numbers [], const int arrayLength)
      {
      int i, sorted = 0;
      while (sorted == 0)
      {
      sorted = i;
      
      i = 1; 
      
      while (i < arrayLength)
      {
      
      if (numbers [i - 1] > numbers [i])
      {
      
      swap (&numbers[i - 1], &numbers[i]);
      sorted = 0;
      
      }
      i++;
      }
      }
      }
      
      void swap(int *p, int *q)
      {
      
      int temp; 
      temp = *p;
      *p = *q;
      *q = temp;
      }
    Thanks for looking, hope someone has time to help me out!

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    1,624
    What is the value of "i" before the loop is run?
    Code:
    int i, sorted = 0;
      while (sorted == 0)
      {
      sorted = i;
      
      i = 1;
    EDIT: About what bubblesort does, it's quite simple. "While numbers with smaller index are bigger than those with bigger index, keep looping".
    Last edited by GReaper; 01-05-2013 at 08:03 AM.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,058
    Quote Originally Posted by Andrew Webb View Post
    Now the bit I am struggling with is, once the numbers have been entered the program should work out the total value, smallest number, largest number, the average, display the numbers in ascending order and also show the range, all to be displayed on screen. I've used bubblesort to reorganise the numbers but Im not really sure how it works.
    Unless there is a reason to use bubble sort (for example, if the purpose of the assignment is actually to learn how to implement a bubble sort), why not use the standard C qsort? I searched a minute ago for "C qsort example" and found this short example:

    Example 3 - Using qsort to sort Ints

    EDIT: The above example is not quite correct - parameters to the COMPAR function should be `const void *'. If you use the example, use the following COMPAR function instead:

    Code:
    int comp(const void *avoid, const void *bvoid) {
        const int *a = avoid;
        const int *b = bvoid;
        return (*a - *b);
    }
    Last edited by c99tutorial; 01-05-2013 at 10:32 AM.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,630
    I like c99tutorial's suggested comp function, and in fact it seemed obvious to me that that was the intention behind the way the comparison function's return value worked (i.e., positive and negative, rather than strict -1 and 1). Unfortunately, the (*a - *b) method has a weakness in that it results in undefined behaviour for certain values of *a and *b. If that is of concern to you, then I suggest an alternative such as:
    Code:
    int comp(const void *lhs, const void *rhs) {
        const int *a = lhs;
        const int *b = rhs;
        return (*a < *b) ? -1 : (*a == *b);
    }
    c99tutorial likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    @tutorial..
    I think that your post is really a confusing one for a beginner than a helpful one.

    How do you assume that he knows what a function pointer is, when he is struggling to do something like this? Propably he is in ip course, or something like that.

    Let alone the fact, that the possibility to use a ready implementation into a homework that has as purpose to learn using arrays , has such a small value. I don't even know if that value can be positive!

    Oh and as for the fact that the example does not use const is considered by you as a mistake? I agree that it should be there, but for a start it is just fine to use it without const! I mean, the main theme of using qsort is the function pointer, not the const keyword!
    But yes, If I see code by a 3rd year student without the const keyword in the compar function, I would suggest him to use it.

    Moreover, I do not really know a university that students use qsort in their first steps, except if they are learning about function pointers.

    And what next? Should we talk about space and time complexity? Should we say that it might be a better idea to use heapsort?
    Of course, the point is to learn!

    Maybe I sound a bit angry, but been a student, I hate such answers, that are actually not helpful, but confusing! It is just like a show off or something like that. If I was that guy, who seems not to follow the post ( this I claim happened before you posted ), I would really be confused. I mean if someone posts, it means he needs help. Help him, don't give him a hard time!

    Been a beginner myself in many things, I do mistakes. Been a "small" member in this forum, I do mistakes. I like when they correct me, because from our mistakes we learn (you know that, you are coding ). Hope that this will help you answer in a more appropriate way, depending on the experience of the person that asked for help ( well you can not really know about that, but you can make a guess ).

    I want to write so many things, but I think I should stop here.
    Even laserlight likes this suggestion, but I already stated my opinion.

    EDIT: And as for the compar I would go like this
    Code:
    int comp_int(const void *a, const void *b) {
        return *(int*)a-*(int*)b;
    }
    Last edited by std10093; 01-05-2013 at 12:40 PM.
    Crossfire likes this.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  6. #6
    Registered User
    Join Date
    Nov 2012
    Posts
    1,058
    Quote Originally Posted by laserlight View Post
    Unfortunately, the (*a - *b) method has a weakness in that it results in undefined behaviour for certain values of *a and *b.

    Code:
    int comp(const void *lhs, const void *rhs) {
        const int *a = lhs;
        const int *b = rhs;
        return (*a < *b) ? -1 : (*a == *b);
    }
    Thanks for the tip. You are right about the undefined behavior. But shouldn't your return statement be:

    Code:
    return (*a < *b) ? -1 : (*a != *b);
    Then it returns 0 if *a and *b are the same.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,630
    Yes.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    Quote Originally Posted by c99tutorial View Post
    Then it returns 0 if *a and *b are the same.
    True.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  9. #9
    Registered User
    Join Date
    Nov 2012
    Posts
    1,058
    Quote Originally Posted by std10093 View Post
    How do you assume that he knows what a function pointer is, when he is struggling to do something like this?
    If you learn C++ as a first language, you're likely to be using namespaces and classes before you know what they really are. Same for any other language feature. Personally I remember being confused on what the actual use of function pointers were until I saw the comparison example. Is getting the notation right really harder than implementing a sorting algorithm by hand?

    But like I said, if the purpose of the assignment is to learn to do a sorting algorithm, then by all means... it's definitely a valid assignment.

    Also I wasn't complaining about the "const" keyword. The link I saw defined the compar function to use "const int *" rather than "const void *", which is a problem. To explain each and every point correctly might seem involved, but why not just take the same route as to why main is written as "int main(int argc, char *argv[])". In other words, "just trust me for now... we'll explain the details later."

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,630
    Anyway...
    Quote Originally Posted by Andrew Webb
    heres what I have done so far:
    Good that you posted what you have done, but you need to indent your code properly. For example, I might have formatted your obtainNumber function like this:
    Code:
    int obtainNumber(int numbers[])
    {
        int index = -1;
        char option = 'y';
        while (option == 'y' || option == 'Y')
        {
            index = index + 1;
            printf("Enter a number: ");
            scanf("%i", &numbers[index]);
            _flushall();
            if (index < 9)
            {
                printf("Do you want to enter another number?('y' for yes 'n' for no) ");
                scanf("%c", &option);
                _flushall();
            }
            else
            {
                option = 'n';
            }
        }
        return index;
    }
    At the moment, your code is a mess, making it hard to trace the flow of control through your code.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Jan 2013
    Posts
    5
    Thanks for all the help. The reason Im using bubblesort is because thats the example our tutor gave us to use. I think Il stick with that because I don't want to get myself even more confused so close to the deadline. I'll work on this tomorrow, doing proper indentation. I'm still unclear on how I would get the program to find and give the values -like the range, highest number etc. I think you have to get the numbers from the array once it is sorted but I'm not sure how to.

    I've been doing this computing course for 3 months now and tutor gives the shortest/confusing lecture and even the people who have programming experience says he makes it really confusing.

    thanks again for your help so far

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Welcome to the forum, Andrew!

    Let's take a peek at your bubbleSort and swap. Swap() looks good. Bubblesort, I'd change to optimize it (and this is a common format, so it's not "out there on the fringe".

    I'd change your program around a bit.

    Code:
    #include <stdio.h>
    
    
    void bubbleSort (int numbers [], int n);
    void swap(int *p, int *q);
    
    
    int main(void) {  
       int i,n;
       int numbers[10] = {3,1,9,5,7,6,4,2,8,0};
    
       printf("The unsorted array:\n");
       for(i=0;i<10;i++)
          printf("%d ",numbers[i]);
    
       n=sizeof(numbers)/sizeof(numbers[0]);
    
       bubbleSort(numbers, n); //the const array length isn't what you want. 
       //Show you why in bubblesort().
    
       printf("The sorted array:\n");
       for(i=0;i<10;i++)
          printf("%d ",numbers[i]);
       
       /*
       get the lowest and highest, here
       subtract low from high to get the range
       add up your numbers into sum
       and divide by n to get the average
       
       and print it all up: %d for int's, 
       %f for doubles and floats (numbers with a decimal point)
       */
    
    
       return 0;
    }
    void bubbleSort (int numbers [], int n) //we'll use n instead of a const 
    {
       int i, sorted = 0;
       while (sorted == 0)
       {
    
          // Sorted is usually a 1 or 0 value, so let's simplify it to that.
          sorted = 1; 
          i = 1; 
      
          while (i < n)  //
          {
             if (numbers [i - 1] > numbers [i])
             {
                swap (&numbers[i - 1], &numbers[i]);
                sorted = 0;
             }
             i++;
          }
          n--;    //there it is! Bubblesort "sorts" the last unsorted 
                  //element of the array, every time it loops, so we
                  //don't need to go that far, any more.
       }
    }
      
    void swap(int *p, int *q)
    {
      
       int temp; 
       temp = *p;
       *p = *q;
       *q = temp;
    }
    Of course, you have to have other requirements, so this is not something you can just turn in.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C programming assignment (with arrays)
    By COG92 in forum C Programming
    Replies: 59
    Last Post: 10-16-2011, 11:20 PM
  2. Replies: 16
    Last Post: 08-02-2011, 12:30 PM
  3. Replies: 1
    Last Post: 05-24-2011, 07:15 PM
  4. Replies: 26
    Last Post: 06-11-2009, 11:27 AM
  5. Assignment of two char arrays
    By moemen ahmed in forum C++ Programming
    Replies: 4
    Last Post: 07-07-2002, 12:44 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21