PDA

View Full Version : arrays




jamesapp
Apr 7, 2008, 04:52 PM
trying to do exercise from chapter 13 of a book on programming with objective-c
1. write a function that calculates the average of an array of 10 floating-point values and returns the result.

i have the function to get the average i think?
i tried to put 10 elements into an array, and then tried to print the average at the end of the program. here is the function for my program.


float average (float data[])
{
int i;
float sum, average;

for (i = 0; i < 10; ++i)
sum += data[i];

average = sum / 10;

return average;
}

here are the error messages i am getting when i try to run my test program which i called exc1chap13.m

exc1chap13.m:5: error: syntax error before ‘}’ token
exc1chap13.m: In function ‘average’:
exc1chap13.m:19: error: nested functions are disabled, use -fnested-functions to re-enable
exc1chap13.m:23: error: syntax error at end of input

and here is my test program


#import <stdio.h>


float data [10] = { 10, 5, -3, 17, 82, 9, 0, 0, 8, -7 };
}
float average (float data[])
{
int i;
float sum, average;

for (i = 0; i < 10; ++i)
sum += data[i];

average = sum / 10;

return average;

int main (int argc, char *argv[])
{

printf ("the average of the array is %i\n", average);

}



error messages

exc1chap13.a.m: In function ‘main’:
exc1chap13.a.m:7: error: syntax error before ‘{’ token
exc1chap13.a.m:10: error: conflicting types for ‘average’
exc1chap13.a.m:7: error: previous definition of ‘average’ was here
exc1chap13.a.m:12: error: syntax error before ‘for’

test program:


#import <stdio.h>

int main (int argc, char *argv[])


float average (float data[])
{
int x[10] = {3, 7, -9, 3, 6, -1, 7, 9, 1, -5);
int i;
float sum, average;

for (i = 0; i < 10; ++i)
sum += data[i];

average = sum / 10;

printf ("the average of the array is %i\n", average);

return average;
}



Cromulent
Apr 7, 2008, 05:00 PM
First off, a float is not an integer so you should stop using %i in your printf() statements when printing average.

I don't think you can call a function and a variable the same name (although I'm not entirely sure I've never tried). You never actually call you average() function in main anyway, at the moment it does nothing. You also have an extra } after the global declaration of the average array (are you sure you want that to be global, you have the functions setup to accept it as an argument which should negate the need for a global declaration).

Sbrocket
Apr 7, 2008, 05:03 PM
This is really hard to read. What's all this code you have? I see two different "test programs" in the first place. Can you fix the [code][/ code] tags, please?

toddburch
Apr 7, 2008, 09:30 PM
You need a closing curly brace between these two statements:

return average;
}
int main (int argc, char *argv[])