|
|
FunctionsHow can large programs be written in a highly systematic and organized manner?All programming languages offer mechanisms to break down a large program into manageable blocks. Functions, processes, threads, head files, libraries, are certain mechanisms to break down a program. What do you mean by function? A program purpose is to compute a task. You are familiar with the mathematical idea of a function, where you input certain parameters and the function produces certain outputs, and C function is similar. A function can be considered as a small program performing a specific task. A function can be called or used many times and only need to be defined once. How exactly do we write a function in C? There are three steps in writing and using a function. In declaring you have to specify Note that the variables declared inside a function are local to the function and cannot be used outside the function. There are two ways to pass the values of variables from one function to another. One way is to use return variablename; command. The second method is to use pointers. We will discuss how pointers are used to reference variables inside functions later, now just follow the syntax. What if want to return more than one value, how do we refer to the values? As stated above, pointers can be used to reference values inside functions, and can be used to return more than one value. Consider the example below.
/* Project: Lab4 */
/* File: funct.C */
/* Aim: Learn how to write C functions */
/* Keywords: none */
/* Declaring the functions or function prototypes */
void input(int *va1, int *va2, int *va3);
float average(int value1, int value2, int value3);
void output(float aver);
void main()
{
int num1, num2, num3;
float aver;
/* Calling or using the functions */
input(&num1, &num2, &num3);
aver=average(num1, num2, num3);
output(aver);
}
/* The actual functions */
void input(int *va1, int *va2, int *va3)
{
int num1, num2, num3;
scanf ("%d%d%d", &num1, &num2, &num3);
*va1 = num1;
*va2 = num2;
*va3 = num3;
}
float average(int value1, int value2, int value3)
{
float aver;
int sum;
sum=value1 + value2 + value3;
aver=((float)sum/3);
return aver;
}
void output(float aver)
{
printf("This is the average %f \n", aver);
}
|