C - Function Function Defining

Introduction

The general form of a function looks like this:

Return_type  Function_name( Parameters - separated by commas )
{
   // Statements...
}

If there are no statements in the body of a function, the return type must be void.

The general form for calling a function is the following expression:

Function_name(List of Arguments - separated by commas)

The name of a function can be any legal name in C that isn't a reserved word and isn't the same as the name of another function.

Function parameters are defined within the function header and are placeholders for the arguments specified when the function is called.

The Return_type specifies the type of the value returned by the function.

The return statement provides the means of exiting from a function.

In its simplest form, the return statement is just this:

return;

This form of the return statement is used in a function where the return type has been declared as void.

The more general form of the return statement is:

return expression;

The following shows how to calculate an average using functions.

Demo

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#define MAX_COUNT 50//from  w  w  w . j a v a  2  s.c  o  m

// Function to calculate the sum of array elements
// n is the number of elements in array x
double Sum(double x[], size_t n)
{
  double sum = 0.0;
  for (size_t i = 0; i < n; ++i)
    sum += x[i];

  return sum;
}

// Function to calculate the average of array elements
double Average(double x[], size_t n)
{
  return Sum(x, n) / n;
}

// Function to read in data items and store in data array
// The function returns the number of items stored
size_t GetData(double *data, size_t max_count)
{
  size_t nValues = 0;
  printf("How many values do you want to enter (Maximum %zd)? ", max_count);
  scanf_s("%zd", &nValues);
  if (nValues > max_count)
  {
    printf("Maximum count exceeded. %zd items will be read.", max_count);
    nValues = max_count;
  }
  for (size_t i = 0; i < nValues; ++i)
    scanf_s("%lf", &data[i]);

  return nValues;
}

// main program - execution always starts here
int main(void)
{
  double samples[MAX_COUNT] = { 0.0 };
  size_t sampleCount = GetData(samples, MAX_COUNT);
  double average = Average(samples, sampleCount);
  printf("The average of the values you entered is: %.2lf\n", average);

  return 0;
}

Result

Related Topics

Exercise