473,383 Members | 1,862 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Confused about functions

Hi. Our assignment was to creat a program that can find the average, median
& mode of a #of integers. Here's my program:

#include<stdio.h>

int main()
{
int item[100];
int a, b, t, mode;
int median_index;
float median, avg;

int count;
printf("How Many numbers do you want to enter? ");
scanf("%d", &count);
for(a=0; a<count; a++){
scanf("%d", &item[a]);
}
for(a=1; a<count; a++)
for(b=count-1; b>=a; --b){
if(item[b-1] > item[b]){
t=item[b-1];
item[b-1] = item[b];
item[b]=t;
}
}
/*median*/

median = count/2;
if(count%2 ==1){
printf("There are odd sets of numbers.\n");
median = item[count/2];
}

else {
median_index = count/2;

median = (item[median_index]+item[median_index-1])/2.0;
}
printf("The Median is %.1f\n", median);

/*average*/

avg = 0;
for(a=0; a<count; a++){
avg = avg+item[a];}
printf("Average is: %.1f\n", avg/count);

/*mode*/

for(a=0; a<count; a++){
if(item[a]== item[a+1]){
mode=item[a];
}
else{
mode=0;}
}

printf("Mode is: %d\n", mode);
return 0;
}

The problem is that I need to have the average, median & mode as 3 separate
functions. I don't know how to set those functions up. If anyone can show me
how this is possible, I would greatly appreciate it.

Thank You. : )

P.S. - I notice that there is a fault in my mode section of my program. If
the user enters 2 modes (ex. 1,2,2,4,4,5) my program will only display the
first. How could I correct this?

Nov 14 '05 #1
13 2153
agentxx04 wrote:
Hi. Our assignment was to creat a program that can find the average, median
& mode of a #of integers. Here's my program:

#include<stdio.h>
insert
#define NUMITEMS (100) int main() make that int main (void) {
int item[100]; make this NUMITEMS; int a, b, t, mode;
int median_index;
float median, avg; C does not give any guarantees about the relative integer ranges
of floating point variables, but if sizeof(float)==sizeof(int)
then there exist ints (for example INT_MAX from <limits.h>)
which cannot represented exactly by floats. So, I would suggest
to use either double or long double for median and avg.

int count;
printf("How Many numbers do you want to enter? ");
scanf("%d", &count); Check whether count <=NUMITEMS -- otherwise I would
just try and enter NUMITEMS+1... for(a=0; a<count; a++){
scanf("%d", &item[a]); scanf() returns the number of input items read, so to be
sure you should check whether scanf returns 1 in your case. }
Sorting: You essentially need the information
_what_ to sort, that is the array item and the type of the
array elements,
_how_many_ elements there are to sort.
You expect no value from this for(a=1; a<count; a++)
for(b=count-1; b>=a; --b){
if(item[b-1] > item[b]){
t=item[b-1];
item[b-1] = item[b];
item[b]=t;
}
}
Determination of the median: You need a sorted array and
the size of the array (and have to know the array type.
You expect a float/double/long double value out of this. /*median*/

median = count/2; This is unnecessary. if(count%2 ==1){
printf("There are odd sets of numbers.\n");
median = item[count/2];
}

else {
median_index = count/2;

median = (item[median_index]+item[median_index-1])/2.0; count = 3 => median_index = 1 => you are looking at item[0]
and item[1]. Make it median_index+1. }
printf("The Median is %.1f\n", median);

Determination of average: You need array, type of array
members and number of array elements. array has not to be
sorted.
You expect a float/double/long double value out of this. /*average*/

avg = 0;
for(a=0; a<count; a++){
avg = avg+item[a];}
printf("Average is: %.1f\n", avg/count);
Mode: I do not understand in the least what mode should
be but I guess the above holds here, too. It seems that you
assume a sorted array. /*mode*/

for(a=0; a<count; a++){ You have an off-by-one error here: if a==count-1
then the next line will access item[count] which
is out of bounds. Make it run as long a<count-1
or start at a=1 and look at item[a-1] and item[a]. if(item[a]== item[a+1]){
mode=item[a];
}
else{
mode=0;}
} This effectively sets in every iteration of the
loop mode to either 0 or item[a]. If
item[count-1]==item[count] then mode=item[count-1],
otherwise 0 after the loop. This does not require a
loop at all.
printf("Mode is: %d\n", mode);
return 0;
}

The problem is that I need to have the average, median & mode as 3 separate
functions. I don't know how to set those functions up. If anyone can show me
how this is possible, I would greatly appreciate it.

Thank You. : )

P.S. - I notice that there is a fault in my mode section of my program. If
the user enters 2 modes (ex. 1,2,2,4,4,5) my program will only display the
first. How could I correct this?


Example: Sorting:
In: array, size
Out: Nothing
void sort_it (int size, int array[])
{
int a, b; /* loop counters, type like size */
int tmp; /* temp. storage, type like array[0] */

for (a=1; a<size; a++)
for (b=size-1; b>=a; --b) {
if (array[b-1] > array[b]) {
tmp = array[b-1];
array[b-1] = array[b];
array[b] = t;
}
}
}
Example: Median:
In: array, count
Out: float/double/long double; in keeping with your program,
I will use float but disadvise its use.
float array_median (int size, int array[])
{
int index; /* index, type like size */
float median; /* median variable, type like return type */

index = size/2;
if ( (size%2) == 1 ) {
printf("There are odd sets of numbers.\n");
median = array[index];
}
else {
median = (array[index]+array[index+1])/2.0; /* (*) Mark */
}

return median;
}

Rest left to reader as exercise.

Notes:
- For array indices, it is better to use the type size_t
(instead of int), as size_t ist guaranteed to work for all
possible indices. (If you have 16-Bit integers and 2GB
memory and use an array with more than pow(2,15)-1 elements
(e.g. 33000), then int cannot used any longer as index
whereas size_t can.)
- (*): If array[index]+array[index+1]>INT_MAX, you run into
trouble. If you demand that one of the two is converted to
double or long double prior to addition then the sum will
be done in (long) double:
median = ((double)array[index]+array[index+1])/2.0;
suffices.
- Your sorting algorithm is the worst possible. Look for
insertion sort or selection sort for (marginally) better
"simple" algorithms and for Shell sort or quicksort for
more sophisticated algorithms able to deal quickly (in
comparison with the former) with large arrays.
- There are some more issues but I suggest you work on
your code and come back then.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2
agentxx04 wrote:
Hi. Our assignment was to creat a program that can find the average, median
& mode of a #of integers. Here's my program:


Try something like this (but don't try turning this in unless you can
justify every line):

#include <stdio.h>
#include <stdlib.h>

int qsort_dblcmp(const void *, const void *);
int qsort_cntcmp(const void *, const void *);
double get_median(int n, double x[n]);
double get_average(int n, double x[n]);
void get_modes(int n, double x[n], int *nm, double m[n]);

int main(void)
{
double *item, *modes;
int ndx, nmode;
double median, average;

int count;
printf("How Many numbers do you want to enter? ");
scanf("%d", &count);
if (count < 1)
exit(EXIT_SUCCESS);
if (!(item = malloc(count * sizeof *item))) {
fprintf(stderr, "I could not get space for %d numbers.\n"
"quitting ...\n", count);
exit(EXIT_FAILURE);
}
if (!(modes = malloc(count * sizeof *modes))) {
fprintf(stderr, "I could not get space for %d possible modes.\n"
"quitting ...\n", count);
exit(EXIT_FAILURE);
}
for (ndx = 0; ndx < count; ndx++) {
scanf("%lf", &item[ndx]);
}
qsort(item, count, sizeof *item, qsort_dblcmp);
median = get_median(count, item);
average = get_average(count, item);
printf("The Median is %g\n", median);
printf("Average is: %g\n", average);
get_modes(count, item, &nmode, modes);
printf("There are %d nodes. They are: \n", nmode);
for (ndx = 0; ndx < nmode; ndx++)
printf("%g\n", modes[ndx]);

free(item);
free(modes);

return 0;
}

int qsort_dblcmp(const void *p1, const void *p2)
{
return *(double *) p1 - *(double *) p2;
}

double get_median(int n, double x[n])
{
if (n % 2)
return x[n / 2];
return (x[n / 2] + x[n / 2 - 1]) / 2;
}

double get_average(int n, double x[n])
{
double sum = 0;
int i;
for (i = 0; i < n; i++)
sum += x[i];
return sum / n;
}

typedef struct
{
double v;
int n;
} Cnt;

void get_modes(int n, double x[n], int *nm, double m[n])
{
int i, this = 0;
Cnt cnt[n];
if (n < 1) {
*nm = 0;
return;
}
for (i = 0; i < n; i++) {
cnt[i].v = 0;
cnt[i].n = 0;
}
cnt[0].v = x[0];
cnt[0].n = 1;
for (i = 1; i < n; i++) {
if (x[i] != cnt[this].v) {
this++;
cnt[this].v = x[i];
}
++cnt[this].n;
}
qsort(cnt, this + 1, sizeof *cnt, qsort_cntcmp);
*nm = 0;
m[0] = cnt[0].v;
for (i = 1; i <= this && cnt[i].n == cnt[i - 1].n; i++) {
++*nm;
m[*nm] = cnt[i].v;
}
++*nm;

}

int qsort_cntcmp(const void *p1, const void *p2)
{
return ((const Cnt *) p2)->n - ((const Cnt *) p1)->n;
}
Nov 14 '05 #3
> double get_median(int n, double x[n]);
double get_average(int n, double x[n]);


I had a couple questions regarding the above function prototypes:

1. Is the 'n' in 'double x[n]' related to the first parameter 'int n'? I'm
assuming it's not.
2. Does adding 'n' to 'double x[n]' mean anything in a function declaration?
I'm assuming it doesn't.

If my assumptions are correct, I'd think it's more clear to write 'double
x[]' or just 'double[]' as your parameter.
Nov 14 '05 #4

Method Man wrote:
[Attribution inserted:] Martin Ambuhl wrote
double get_median(int n, double x[n]);
double get_average(int n, double x[n]);

I had a couple questions regarding the above function prototypes:

1. Is the 'n' in 'double x[n]' related to the first parameter 'int n'? I'm
assuming it's not.
2. Does adding 'n' to 'double x[n]' mean anything in a function declaration?
I'm assuming it doesn't.

If my assumptions are correct, I'd think it's more clear to write 'double
x[]' or just 'double[]' as your parameter.


Martin wrote C99 code; there, 1. is answered with yes and 2. is answered
with x is a VLA of n doubles.
Cheers
Michael
--
E-Mail: Mine is a gmx dot de address.

Nov 14 '05 #5
Michael Mair wrote:

agentxx04 wrote:
Hi. Our assignment was to creat a program that can find the average, median
& mode of a #of integers. Here's my program:

#include<stdio.h>

insert
#define NUMITEMS (100)
int main()

make that int main (void)
{
int item[100];

make this NUMITEMS;
int a, b, t, mode;
int median_index;
float median, avg;

C does not give any guarantees about the relative integer ranges
of floating point variables, but if sizeof(float)==sizeof(int)
then there exist ints (for example INT_MAX from <limits.h>)
which cannot represented exactly by floats. So, I would suggest
to use either double or long double for median and avg.


I would suggest type int for the median.

--
pete
Nov 14 '05 #6


pete wrote:
Michael Mair wrote:
agentxx04 wrote:

Hi. Our assignment was to creat a program that can find the average, median
& mode of a #of integers. Here's my program:

#include<stdio.h>

insert
#define NUMITEMS (100)
int main()


make that int main (void)
{
int item[100];


make this NUMITEMS;
int a, b, t, mode;
int median_index;
float median, avg;


C does not give any guarantees about the relative integer ranges
of floating point variables, but if sizeof(float)==sizeof(int)
then there exist ints (for example INT_MAX from <limits.h>)
which cannot represented exactly by floats. So, I would suggest
to use either double or long double for median and avg.

I would suggest type int for the median.


The OP defines the median for an even number of array elements as
average of the two in the middle. For a difference of 1 between the
two we cannot find an int value to replace the average.

This is consistent with, e.g, the definition on
http://www.shodor.org/interactivate/dictionary/m.html
(note: this is the first I came across when googling for definition
of median) :
|"Middle value" of a list. The smallest number such that at least half
|the numbers in the list are no greater than it. If the list has an odd
|number of entries, the median is the middle entry in the list after
|sorting the list into increasing order. If the list has an even number
|of entries, the median is equal to the sum of the two middle (after
|sorting) numbers divided by two. The median can be estimated from a
|histogram by finding the smallest number such that the area under the
|histogram to the left of that number is 50% (cf Mean, Median and Mode
|Discussion).
so I think double is the right thing.

However, we are doing C, not statistics, so I leave it to the OP
which definition he wants :-)
Cheers
Michael
--
E-Mail: Mine is a gmx dot de address.

Nov 14 '05 #7
Michael Mair wrote:
I would suggest type int for the median.
The OP defines the median for an even number of array elements as
average of the two in the middle. For a difference of 1 between the
two we cannot find an int value to replace the average.

However, we are doing C, not statistics, so I leave it to the OP
which definition he wants :-)


Sorry.
I realize my suggestion was off topic too.

--
pete
Nov 14 '05 #8
"agentxx04" writes:
Hi. Our assignment was to creat a program that can find the average,
median
& mode of a #of integers. Here's my program:

#include<stdio.h>

int main()
{
int item[100];
int a, b, t, mode;
int median_index;
float median, avg;


double mean(int* arr, int n);
double median(int* arr, int n);
int mode(int* arr, int n);

Write the matching functions. arr is item (it's already a pointer), and n
is the number of valid items in arr. I think the instructor asssumes that
there *is* a mode and that n is at least 3 or so. It is customary to use
double in C where common sense would lead you to use float. Float is
usually treated as a poor relation.
<snip>


Nov 14 '05 #9
Michael Mair <Mi**********@invalid.invalid> wrote:
Method Man wrote:
Martin Ambuhl wrote
double get_median(int n, double x[n]);
double get_average(int n, double x[n]);


1. Is the 'n' in 'double x[n]' related to the first parameter
'int n'? I'm assuming it's not.
2. Does adding 'n' to 'double x[n]' mean anything in a
function declaration? I'm assuming it doesn't.


Martin wrote C99 code; there, 1. is answered with yes and 2. is answered
with x is a VLA of n doubles.


If so, then why would he have bothered with the first parameter?

The n in x[n] means exactly the same in C99 as it did in C89
(ie. nothing). You can't pass VLAs by value any more than
you can pass regular arrays by value. So the answers
are 'no' and 'no'.
Nov 14 '05 #10

"agentxx04" <ag*******@hotmail.com> wrote
Hi. Our assignment was to creat a program that can find the average, median & mode of a #of integers. Here's my program:
The problem is that I need to have the average, median & mode as 3
separate functions. I don't know how to set those functions up.


Your file goes like this.

#include <stdio.h>
#include <stdlib.h>
/* plus anything else you call */

/* prototypes */
double mean(int *vals, int N);
double median(int *vals, int N);
int mode(int *vals, int N);

int main(void)
{
/* code to input an array of integers */
/* we will assume that a pointer called array points to the input list,
and N is the number of values entered */

printf("Mean %g\n", mean(array, N));
printf("Median %g\n", median(array, N));
printf("Mode %d\n", mode(array, N));

/* free array and clean up here */
}

/*
mean - return the mean of a list of intergers
Params: vals - the values
N - number of values
Returns: the arithemtical mean;
*/
double mean(int *vals, int N)
{
int i;
double answer = 0;

for(i=0;i<N;i++)
answer += vals[i];

return answer/N;
}

double median(int *vals, int N)
{
/* write this yourself. You need to sort the input (use qsort()) and take
the middle value or the average of the two middles if N is even */
}

int mode(int *vals, int N)
{
/* this one is similar, except that mode is always integral. Sort the
values, and
then count runs of equal values. Do not be tempted to optimise the
program
by sorting once and using the sorted values for both median and mode.
This
will speed it up but destroy modularity.
There is no easy answer if there is no mode (eg all values are unique).
Just
return the value of one of the largest runs. */
}
Nov 14 '05 #11
Old Wolf wrote:
Michael Mair <Mi**********@invalid.invalid> wrote:
Method Man wrote:
Martin Ambuhl wrote
double get_median(int n, double x[n]);
double get_average(int n, double x[n]);

1. Is the 'n' in 'double x[n]' related to the first parameter
'int n'? I'm assuming it's not.
2. Does adding 'n' to 'double x[n]' mean anything in a
function declaration? I'm assuming it doesn't.

Martin wrote C99 code; there, 1. is answered with yes and 2. is answered
with x is a VLA of n doubles.

If so, then why would he have bothered with the first parameter?


1) Because the *first* parameter is the array size, needed whether you
use VLAs or not. I believe you are confused
2) Because I have a consistent policy of declaring all functions with
array arguments with the size information, no matter what the
dimensionality.
The n in x[n] means exactly the same in C99 as it did in C89
(ie. nothing).
But, you silly twit, the *first* parameter, which you feel is
unnecessary has nothing to do with that (reason 1). And the fact that
x[] and x[n] behave the same is irrelevent when a consistent style is
adopted and including it costs nothing (reason 2).
You can't pass VLAs by value any more than
you can pass regular arrays by value. So the answers
are 'no' and 'no'.


What crap.
Nov 14 '05 #12
Old Wolf wrote:
Michael Mair <Mi**********@invalid.invalid> wrote:
Method Man wrote:
Martin Ambuhl wrote
double get_median(int n, double x[n]);
double get_average(int n, double x[n]);

1. Is the 'n' in 'double x[n]' related to the first parameter
'int n'? I'm assuming it's not.
2. Does adding 'n' to 'double x[n]' mean anything in a
function declaration? I'm assuming it doesn't.


Martin wrote C99 code; there, 1. is answered with yes and 2. is answered
with x is a VLA of n doubles.

If so, then why would he have bothered with the first parameter?

The n in x[n] means exactly the same in C99 as it did in C89
(ie. nothing). You can't pass VLAs by value any more than
you can pass regular arrays by value. So the answers
are 'no' and 'no'.


Err... You are right. Thanks for pointing that out.
Major brainfart by me.
The difference comes out in

#include <stdio.h>
#include <stdlib.h>

void vlatest(int m, int vla[m][m])
{
printf("%zu %zu\n", sizeof vla[0][0], sizeof vla[0]);
}

int main (int argc, char **argv)
{
int size;
if (argc>=2) {
size = atoi(argv[1]);
int array[size][size];
printf("%zu %zu\n", sizeof array[0][0], sizeof array[0]);
vlatest(size, array);
}
return 0;
}

Even if using %lu and using
int arr[4][4];
vlatest(4, arr);
instead of what I do in main(), a C89 compiler won't be happy :-)
See also 6.7.5.2, especially # 10 (Array declarators, Example 4)
in the C99 standard.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #13
On 9 Nov 2004 12:53:35 -0800, ol*****@inspire.net.nz (Old Wolf) wrote:
Michael Mair <Mi**********@invalid.invalid> wrote:
Method Man wrote:
Martin Ambuhl wrote
>double get_median(int n, double x[n]);
>double get_average(int n, double x[n]);

1. Is the 'n' in 'double x[n]' related to the first parameter
'int n'? I'm assuming it's not.
2. Does adding 'n' to 'double x[n]' mean anything in a
function declaration? I'm assuming it doesn't.


Martin wrote C99 code; there, 1. is answered with yes and 2. is answered
with x is a VLA of n doubles.


If so, then why would he have bothered with the first parameter?

The n in x[n] means exactly the same in C99 as it did in C89
(ie. nothing). You can't pass VLAs by value any more than
you can pass regular arrays by value. So the answers
are 'no' and 'no'.


Not quite. In C89 the array bound must either be omitted -- double x[]
-- or a constant expression, which n is not. The (topmost) bound of an
array function parameter is ignored in rewriting to pointer, so in C99
T x[n] and T x[] both mean the same as T*x; in C89 only the latter is
permitted and it does mean the same.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: jfj | last post by:
Hi. Suppose this: ######################## def foo (x): print x f = classmethod (foo)
29
by: Alexander Mahr | last post by:
Dear Newsgroup, I'm somehow confused with the usage of the static keyword. I can see two function of the keyword static in conjunction with a data member of a class. 1. The data member...
8
by: siliconwafer | last post by:
Hi All, If I open a binary file in text mode and use text functions to read it then will I be reading numbers as characters or actual values? What if I open a text file and read it using binary...
18
by: Stefan | last post by:
Have a look at the follwoing VB-code. The first MsgBox shows the number 2 while the second one 6. WHY? How come 2.5 is rounded off to 2 and 5.5 is rounded off to 6?? Dim i As Integer = 5 / 2 ...
10
by: Xiaoshen Li | last post by:
Dear All, I am confused with prototypes in C. I saw the following code in a C book: void init_array_1(int data) { /* some code here */ }
3
by: redefined.horizons | last post by:
I've been reading about Python Classes, and I'm a little confused about how Python stores the state of an object. I was hoping for some help. I realize that you can't create an empty place holder...
6
by: pookiebearbottom | last post by:
Let's say I have headers Sal.h with this class class Sal { public: int doit() { return 1;} }; now I know that the compilier can choose NOT to inline this function. So if I include this in...
7
by: Leszek L. | last post by:
Hello, I am new to this group; if my question is OT then please excuse me and tell me where to go. I am using MS Visual C++ with some of its graphics libraries. Now the compiler tells me that...
7
by: eric | last post by:
hello i'm confused by an example in the book "Effective C++ Third Edition" and would be grateful for some help. here's the code: class Person { public: Person(); virtual ~Person(); // see...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.