Homework Help on "C" #2

Discussion in 'Programmer's Corner' started by DanTheMan, Jul 28, 2009.

  1. DanTheMan

    Thread Starter Member

    Nov 16, 2008
    10
    0
    Hi, I have hit a brick wall with my lab assignment.
    The source code bellow is all included in main(), however, we are suppose to use functions as much as possible.
    My first headache is...how do you call infinite parameters in a function.

    The goal is to write a program that reads a list of integers(no limit) from the keyboard and return the followings.
    #of integers, sum of integers, average of integers, smallest & largest integers, and print boolean (T/F) if at least one # is largest)
    {code}
    #include <stdio.h>
    #include <stdlib.h>
    #include <limits.h>
    #define TRUE 1
    #define FALSE 0

    int main(void)
    [ int sum=0, count=0, nums;
    int smallest = INT_MAX;
    int largest = INT_MIN;
    float avg;
    bool belowTwenty = FALSE;
    bool btwnTenNinty = TRUE;

    printf("Enter numbers with <return> (99999 to stop)\n");
    scanf("%d",&nums);
    while(nums != 99999)
    [ sum += nums;
    count++;
    // scanf("%d",&nums);

    if (nums < smallest)
    smallest = nums;

    if (nums > largest)
    if(nums!=99999)
    ]
    largest = nums;
    ]

    scanf("%d",&nums);

    ]
    avg = (sum /count);
    belowTwenty = (nums < 20);
    btwnTenNinty = (10<= nums && nums >= 90) ;

    printf("\nThe number of integers is:\t%3d\n",count);
    printf("The sum of the integers is:\t%4d\n",sum);
    printf("The average of the integers is:\t%03.2f\n",avg);
    printf("The smallest integer is:\t%d\n", smallest);
    printf("The largest integer is: %d\n", largest);{/code}
     
    Last edited: Jul 28, 2009
  2. Mark44

    Well-Known Member

    Nov 26, 2007
    626
    1
    The term is variable parameter list, not infinite parameters. Several of the C standard library have variable parameter lists, such as printf. You'll need to include <stdarg.h> for the macros that you use when you declare a function to have a variable param list.

    You'll need to use the va_list type, as well as the va_start() and va_end() macros. Holler if you need more help.
     
  3. someonesdad

    Senior Member

    Jul 7, 2009
    1,585
    141
    As mentioned before, use {code}{/code} tags (replace { with [ and } with ]) to make your code easier to read. One of the first lessons a programmer has to learn the hard way is no one will help them if they make it too much work for the helper. Make your code pretty and easy to read -- it makes a big difference. I personally won't waste my time trying to read ugly code.

    A variable number of parameters in a function call is not the answer. The size of the parameter list is determined at compile time, not run time. Besides, you could always make it break by calling it with a big enough parameter list -- you'd run out of stack space and wouldn't know it until run time.

    You're supposed to read integers from the keyboard, so that means reading stdin with things like the getchar macro, scanf, etc. Then, you've got to do something with that integer. You don't need to e.g. make a big array and store all the integers -- that would be an inelegant solution for this problem. But, fortunately, you can keep a running total of sum, largest, smallest, number of integers entered, etc. When the last integer is entered (you have to devise some way for the user to indicate that), then you calculate and print out the desired numbers.
     
  4. DanTheMan

    Thread Starter Member

    Nov 16, 2008
    10
    0
    Thank you Mark44 and someonesdad for your responses!
    I have edited my code above, so hopefully it is easier to read. For some reason only partial of the code was posted even though I copy& pasted the whole thing.
    I am using scanf in a while loop to read integers entered.
    Now, I need to replace some of the statements with functions.
    For example, a function to get the smallest number.

    int getSmallest ( int nums) --> I would like to use "nums"(integers entered) as parameter
    [
    int smallest = INT_MAX;
    if (nums < smallest)
    smallest = nums;
    return smallest;
    ]

    Is there a different way to express this or Is my coding incorrect?
     
  5. Mark44

    Well-Known Member

    Nov 26, 2007
    626
    1
    Yes (to both).

    Can you explain in words what it is that the function above is supposed to do? Be sure to include what value(s) the parameter should have.

    The purpose of this exercise is to convince you of the value of having an algorithm before you start typing in code.

    someonesdad,
    You are correct that a variable argument list is the wrong way to go. I didn't understand well enough what the OP was trying to do.
     
  6. DanTheMan

    Thread Starter Member

    Nov 16, 2008
    10
    0
    The "smallest" function will read each integers entered by the user and compare it with INT_MAX. If the integer is less than INT_MAX then return the integer.
    The parameters will have ALL of the integers entered.
    Does this make sense?
     
    Last edited: Jul 28, 2009
  7. someonesdad

    Senior Member

    Jul 7, 2009
    1,585
    141
    No, Dan, it doesn't make sense. I think I know what you're trying to do here, but your function's code will almost always return the number you call it with. Hint: you may want to take a look at the storage type of smallest.

    I agree with Mark44 that you should be doing your algorithm design first -- this problem is straightforward to do with pencil and piece of paper. Once you have an algorithm that works, it's usually easy to convert it to code. Coders are a dime a dozen, but good software designers are rarer birds.

    I like to use a pseudo code to design my algorithms with. Often, I design an algorithm in python because python can be made to look a bit like pseudocode and I then have the advantage of being able to test the algorithm easily.

    Here's an example of some pseudocode that might be written for your problem.
    Code ( (Unknown Language)):
    1.  
    2. Initialize variables
    3. while not done
    4.     get integer from keyboard
    5.     if integer == sentinel value:
    6.         done = true
    7.         continue
    8.     if integer < min:  min = integer
    9.     if integer > max:  max = integer
    10.     count += 1
    11.     sum += integer
    12. Print results
    13.  
    You can read through this quickly and see and test if it does what you want.

    Here's the pseudocode turned into a working python program with not a heck of a lot of extra work. This demonstrates why high level languages like python are popular -- they're almost like writing pseudocode. If I need to develop a program, I always start with python and it's almost always fast enough. If not, I can usually anticipate the problems and write the python code with an eye towards translatng it into C++ or C. This lets me get the algorithm right; then C/C++ lets me get the speed.

    Just read main(), as you don't need to understand the details of getting input from the keyboard.
    Code ( (Unknown Language)):
    1.  
    2. from __future__ import division
    3. from sys import maxint
    4.  
    5. def GetIntegerFromKeyboard():
    6.     # User needs to know to hit return key with no input to end data entry
    7.     ok = False
    8.     while not ok:
    9.         string = raw_input("Integer?  ")
    10.         if not string: return 0, True
    11.         number = 0
    12.         try:
    13.             number = int(string)
    14.             ok = True
    15.         except:
    16.             print "'%s' is not a recognizable number" % string
    17.     return number, False
    18.  
    19. def main():
    20.     #Initialize variables
    21.     sum = 0
    22.     count = 0
    23.     largest_integer = -maxint
    24.     smallest_integer = maxint
    25.     done = False
    26.  
    27.     # Main program loop
    28.     while True:
    29.         integer, done = GetIntegerFromKeyboard()
    30.         if done:
    31.             break
    32.         count += 1
    33.         if integer > largest_integer:
    34.             largest_integer = integer
    35.         if integer < smallest_integer:
    36.             smallest_integer = integer
    37.         sum += integer
    38.  
    39.     # Done; print results
    40.     if count > 0:
    41.         print
    42.         print "Number of integers read =", count
    43.         print "Sum =", sum
    44.         print "Average =", sum/count
    45.         print "Minimum =", smallest_integer
    46.         print "Maximum =", largest_integer
    47.     else:
    48.         print "No numbers were entered"
    49.  
    50. main()
    51.  
    Of course, you gotta test it:
    Code ( (Unknown Language)):
    1.  
    2. Integer?  1
    3. Integer?  2
    4. Integer?  3
    5. Integer?
    6.  
    7. Number of integers read = 3
    8. Sum = 6
    9. Average = 2.0
    10. Minimum = 1
    11. Maximum = 3
    12.  
    It wouldn't be hard to change this code to use more function calls as you're apparently being asked to. I didn't do this because I'd do some funky things for call-by-reference and it would only confuse you.
     
  8. Mark44

    Well-Known Member

    Nov 26, 2007
    626
    1
    Not very much. Let's compare what you've said here with the code you wrote earlier.
    Code ( (Unknown Language)):
    1.  
    2. int getSmallest ( int nums)
    3. {
    4.   int smallest = INT_MAX;
    5.   if (nums < smallest)
    6.     smallest = nums;
    7.   return smallest;
    8. }
    9.  
    You have said that your "smallest" function (actually named getSmallest) will "read each integers..." How can it do that? There are no input functions such as scanf in your function. And does this mean "read each integer" or "read all integers"?

    Your getSmallest function takes a single int as its parameter, not ALL integers entered. nums is misleadingly named: its name implies (incorrectly) that it somehow contains a sequence of numbers. It does not. To pass several numbers in as a parameter, you need to know about arrays (and pointers) and how to pass them as arguments to a function. As someonesdad already mentioned, this function will almost always return the number that was passed as a parameter when getSmallest is called. The only exception is if you happen to pass INT_MAX in the call.

    It is very important to give clear and accurate names to your variables and functions since they are a form of documentation that helps you and anyone looking at your code understand what their roles are. If you give them names that are unclear or misleading, you and anyone else reading them will have a more difficult time understanding how to use them correctly. This becomes all the more important when you are working on some code and set it aside for a few days, weeks, or months.
     
  9. dgoadby

    New Member

    Jul 28, 2009
    1
    0
    Since the input list has no limit then why no create a linked list of the inputs? As you are merely adding entries then this is fairly trivial matter and there are many simple examples to refer to.

    You would then pass a pointer to the start of the list to the functions to process the max, min, sum, average etc.

    Depending on your C Libraries you may already have what you need but creating your own linked list code will be a much more valuable exercise.


    Regards David
     
  10. Mark44

    Well-Known Member

    Nov 26, 2007
    626
    1
    The OP is a beginning C programmer and is struggling with argument passing and the difference between scalar and vector types, so IMO, this is terrible advice.
     
  11. DanTheMan

    Thread Starter Member

    Nov 16, 2008
    10
    0
    someonesdad, your example of the pseudocode and python program were logical and easy to understand.
    I agree that algorithms was my biggest problem. I was too caught up in details.
    I guess I was seeing the trees not the forest.
    Thank you Mark44 as well for your advice!
    I am very grateful that you guys are putting up with a newbie like myself.
    It is very encouraging! I will return to step 1 and review my source code.
    Thanks again!
     
Loading...