C examples for Function:Function Definition
The general form of a function looks like this:
Return_type Function_name( Parameters - separated by commas ){
// Statements...
}
The general form for calling a function is the following expression:
Function_name(List of Arguments - separated by commas)
The return Statement
In its simplest form, the return statement is just this:
return;
The more general form of the return statement is:
return expression;
Calculating an average using functions
#include <stdio.h> #define MAX_COUNT 50/* ww w . j av a2s . com*/ double Sum(double x[], int n) { double sum = 0.0; for (int i = 0; i < n; ++i) sum += x[i]; return sum; } double Average(double x[], int n) { return Sum(x, n) / n; } int GetData(double *data, int max_count) { int nValues = 0; printf("How many values do you want to enter (Maximum %zd)? ", max_count); scanf("%zd", &nValues); if (nValues > max_count) { printf("Maximum count exceeded. %zd items will be read.", max_count); nValues = max_count; } for (int i = 0; i < nValues; ++i) scanf("%lf", &data[i]); return nValues; } int main(void) { double samples[MAX_COUNT] = { 0.0 }; int sampleCount = GetData(samples, MAX_COUNT); double average = Average(samples, sampleCount); printf("The average of the values you entered is: %.2lf\n", average); return 0; }