Homework Help on "C" #2

Thread Starter

DanTheMan

Joined Nov 16, 2008
10
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:

Mark44

Joined Nov 26, 2007
628
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.
 

someonesdad

Joined Jul 7, 2009
1,583
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.
 

Thread Starter

DanTheMan

Joined Nov 16, 2008
10
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?
 

Mark44

Joined Nov 26, 2007
628
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.
Rich (BB code):
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?
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.
 

Thread Starter

DanTheMan

Joined Nov 16, 2008
10
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:

someonesdad

Joined Jul 7, 2009
1,583
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?
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.
Rich (BB code):
Initialize variables
while not done
    get integer from keyboard
    if integer == sentinel value:
        done = true
        continue
    if integer < min:  min = integer
    if integer > max:  max = integer
    count += 1
    sum += integer
Print results
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.
Rich (BB code):
from __future__ import division
from sys import maxint

def GetIntegerFromKeyboard():
    # User needs to know to hit return key with no input to end data entry
    ok = False
    while not ok:
        string = raw_input("Integer?  ")
        if not string: return 0, True
        number = 0
        try:
            number = int(string)
            ok = True
        except:
            print "'%s' is not a recognizable number" % string
    return number, False

def main():
    #Initialize variables
    sum = 0
    count = 0
    largest_integer = -maxint
    smallest_integer = maxint
    done = False

    # Main program loop
    while True:
        integer, done = GetIntegerFromKeyboard()
        if done:
            break
        count += 1
        if integer > largest_integer:
            largest_integer = integer
        if integer < smallest_integer:
            smallest_integer = integer
        sum += integer

    # Done; print results
    if count > 0:
        print
        print "Number of integers read =", count
        print "Sum =", sum
        print "Average =", sum/count
        print "Minimum =", smallest_integer
        print "Maximum =", largest_integer
    else:
        print "No numbers were entered"

main()
Of course, you gotta test it:
Rich (BB code):
Integer?  1
Integer?  2
Integer?  3
Integer?

Number of integers read = 3
Sum = 6
Average = 2.0
Minimum = 1
Maximum = 3
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.
 

Mark44

Joined Nov 26, 2007
628
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?
Not very much. Let's compare what you've said here with the code you wrote earlier.
Rich (BB code):
int getSmallest ( int nums) 
{
  int smallest = INT_MAX;
  if (nums < smallest)
    smallest = nums;
  return smallest;
}
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.
 

dgoadby

Joined Jul 28, 2009
1
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
 

Mark44

Joined Nov 26, 2007
628
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.
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.
 

Thread Starter

DanTheMan

Joined Nov 16, 2008
10
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!
 
Top