473,721 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2197
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(co nst void *, const void *);
int qsort_cntcmp(co nst 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_SUCCE SS);
if (!(item = malloc(count * sizeof *item))) {
fprintf(stderr, "I could not get space for %d numbers.\n"
"quitting ...\n", count);
exit(EXIT_FAILU RE);
}
if (!(modes = malloc(count * sizeof *modes))) {
fprintf(stderr, "I could not get space for %d possible modes.\n"
"quitting ...\n", count);
exit(EXIT_FAILU RE);
}
for (ndx = 0; ndx < count; ndx++) {
scanf("%lf", &item[ndx]);
}
qsort(item, count, sizeof *item, qsort_dblcmp);
median = get_median(coun t, item);
average = get_average(cou nt, 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(co nst 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(co nst 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<std io.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**********@i nvalid.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

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

Similar topics

9
4613
by: jfj | last post by:
Hi. Suppose this: ######################## def foo (x): print x f = classmethod (foo)
29
4396
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 reffers in all objects of this class to the same data Or in other word by using the static keyword all objects of one class can share data. (This is what I want)
8
1788
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 read functions. -Siliconwafer
18
1872
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 MsgBox(i) Dim j As Integer = 11 / 2
10
1583
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
2169
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 for a member variable of a Python object. It has to be given a value when defined, or set within a method. But what is the difference between an Attribute of a Class, a Descriptor in a Class, and a Property in a Class?
6
2911
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 two different libraries, they both choose to
7
2070
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 one of the member functions that I am trying to use is not a member of that class. The sad irony is that when I type the name of an object of that class, followed by a dot, the IDE helpfully displays
7
3087
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 item 7 for why this is virtual ...
0
8730
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9131
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9064
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6669
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5981
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4484
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3189
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2130
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.