Thread: Need help with Functions and Arrays

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    33

    Need help with Functions and Arrays

    Good evening folks. I was just assigned a task by my professor. I'm starting to find it becoming harder and harder as my professor isn't improving his teaching skills and he prefers to tell lame jokes about faulty programming rather than teach properly. not to mention his heavy accent makes it harder :/ . We've just got into arrays and I don't even understand how to do functions. (we are not covering string yet).

    heres the question I received.


    Programming Problems on Arrays


    1. Write a C program that asks the user for many integers until a ZERO is
    entered. All the integers except ZERO will be stored in an array. The
    program will print out the smallest integer, the largest integer and
    a table of all the integers (except ZERO). The program must make sure
    that the user will not enter more than 50 integers (including ZERO).
    Here is a sample ouptut:


    smallest integer: -20
    largest integer: 99
    11
    98
    3
    -1
    -4
    -20
    35
    67
    99
    75
    *I have completed question 1*



    2. Redo Question 1 by building two functions and one main program.
    The main program should produe the same sample output as in Question 1.


    /* This function will get no more than 50 integers from the user.
    It will stop asking the user for another integer if stopper is entered.
    All integers (except stopper) are stored in the array (num).
    The function returns the total number of integers that are stored in
    the array. */
    Code:
     int get_numbers( int num[ ], int stopper );
    /* This function finds the smallest and the largest integers in
    the array (z). size is the total number of integers stored in
    the array. */
    Code:
       void find( int z[ ], int size, int * min, int * max );

    i've already completed part one with a little help from a tutor who is only available 1 hour a week and if you manage to even get in the time slot.

    Here is my code for question 1:

    Code:
    /*Quiz Submitted by Umeed Malik: Student Number 32109076*/
    #include <stdio.h>
    #define SIZE 50
    #define INVALID 0
    
    
    main () {
    
    
            int Nums[SIZE];
            int Smallest=0, Largest=0, entry, counter=-1, i;
    
    
            do{
                    printf("Please enter an integer(enter 0(ZERO) to exit): ");
                    scanf("%d", &entry);
    
    
                    counter += 1;
    
    
                    if (entry != INVALID){
                            if (entry > Largest){
                                    Largest = entry;
                                    Nums[counter] = entry;
                            } else if (entry < Smallest) {
                                    Smallest = entry;
                                    Nums[counter] = entry;
                            } else {
                                    Nums[counter] = entry;
                            }
                    }
    
    
            }while (entry != INVALID && counter != SIZE);
    
    
            printf("\n\nSmallest integer: %d", Smallest);
            printf("\nLargest integer: %d\n", Largest);
    
    
            for (i=0; i<counter; i++){
                    printf("%d\n", Nums[i]);
            }
    thanks to you guys for explaining the importance of clean and well formatted coding I've begun to understand what I'm doing more lol. However I have no clue as how to add a function to this array.


    The only thing i really understand about functions is it helps to avoid writing the same code over and over.

    I do appreciate the help, thanks in advance.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    You should always try to simplify your code after you get it working...
    Code:
                     if (entry != INVALID){
                            if (entry > Largest){
                                    Largest = entry;
                                    Nums[counter] = entry;
                            } else if (entry < Smallest) {
                                    Smallest = entry;
                                    Nums[counter] = entry;
                            } else {
                                    Nums[counter] = entry;
                            }
                    }
    Notice how you have the same assignment to Nums in every branch of the if statement?
    You can do this...

    Code:
                    if (entry != INVALID)
                      {
                          Nums[counter] = entry;
    
                          if (entry > Largest)
                            {
                               Largest = entry;
                            }
                          else if (entry < Smallest) 
                            {
                              Smallest = entry;
                            }
                     }
    There are a couple of other things you can do as well....

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    oh wow i can do that? I thought the counter had to be in every line haha ahhh man. That looks so much more cleaner.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by ShadowBoss View Post
    oh wow i can do that? I thought the counter had to be in every line haha ahhh man. That looks so much more cleaner.
    ...of course you can do that...

    Like I said, you should make a practice of getting it to work, then simplifying it as much as possible. Sometimes the simplifications will bomb on you but that's good information too. It's just as important to know what does not work as what does.

    Now... can you think of any other simplifications you could use here?
    I see 2 more...

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    hmm, i tried fiddling with the

    Code:
     }while (entry != INVALID && counter != SIZE);
    but didn't seem to work lol.

    as for my issue with function

    after going through some notes, ive figured out that my function would be

    for (i = 0; i < counter; i++)
    {
    if (int z[i] > *max)
    {
    *max = int z[i];
    }
    else if (z[i] < *min)
    {
    *min = int z[i];
    }
    }


    my problem is i don't know how to implement it into my current code.
    Last edited by ShadowBoss; 11-17-2011 at 01:17 PM.

  6. #6
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Well, main() is function, and any other function you define would have similar structure. A function exists as intrinsic, self-contained code. In short, they exist outside of other functions. Unlike main(), your functions must be declared in the global declarations before main() or within main() before it is used. Within main() you will 'call' the function by name and parameters, if any. (In point of fact, any function can be the 'calling' function if it 'knows' about the 'called' function, i.e. it's declaration or prototype is visible to the function).

    A declaration consists of
    -return type- name ( -formal parameter list- ) ;

    where return type is void, int, char, float, pointer etc. and parameter list is void or one or more data types.

    The definition begins with a 'header' the same as your prototype, only the parameters must have identifiers (names) and there is no semicolon. The 'header' is followed by your code in braces.

    Your instructor has given you the prototypes, so your program will look something like...
    Code:
    /*Quiz Submitted by Umeed Malik: Student Number 32109076*/
    #include <stdio.h>
    #define SIZE 50
    #define INVALID 0
     
    int get_numbers( int num[ ], int stopper );
    
    void find( int z[ ], int size, int * min, int * max );
    
    
    
    
    
    
    main () 
    {
    ...
       size = get_numbers( Nums, INVALID ) ;
    
       find( Nums, size, &Smallest, &Largest ) ;
    ...
    }
    
    
    int get_numbers( int num[ ], int stopper )
    {
        //code to read in integers from user goes here
    }
    
    
    void find( int z[ ], int size, int * min, int * max )
    {
         // code to assign min and max to your variables Smallest and Largest goes here
    }

  7. #7
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    wow i totally understand that. Ok my question now is because i have "INVALID" set to as 0, should i assign int stopper to INVALID? because the stopper is suppose to set to 0 so when the user hits 0 (zero) it'll end the program (at least that is what i think it says) and then it'll print their results.

  8. #8
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    When you call a function, the actual parameters must match in type, number, and order (until you get into more advanced programming). The names used for parameters in the definition of the function are completely local to that function.
    Also, remember that #define statements replace identifier with the definition, i.e. INVALID is replaced with 0, BEFORE compiling.
    So when you call get_numbers and pass INVALID as a parameter, 0 is passed to the function and that is the value that stopper is assigned.
    stopper is therefore intended as the value your function should match to user input to determine when to stop reading integers (that OR reaching the end of the array).

    I guess I should mention that you use a "return" statement to 'send' a value back that matches -return type- to the calling function. The entire get_numbers() function call is replaced by it's return value, which gets assigned to size or whatever int variable you want to declare. You can have multiple conditional return statements, but only one will ever execute. Function execution ends on a return statement.
    Last edited by Tclausex; 11-17-2011 at 02:46 PM.

  9. #9
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    ohhh okay. That's awesome man. Thank you so much for the help guys. I think I've got this now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. arrays, functions, HELP
    By beginner1 in forum C Programming
    Replies: 4
    Last Post: 05-20-2009, 03:29 PM
  2. functions using arrays
    By trprince in forum C Programming
    Replies: 30
    Last Post: 11-17-2007, 06:10 PM
  3. 2-d arrays and functions
    By Faceoff49 in forum C++ Programming
    Replies: 3
    Last Post: 03-19-2002, 09:14 PM
  4. functions and arrays
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 03-14-2002, 09:57 AM
  5. arrays and functions help
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 03-02-2002, 08:05 AM