C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
half (int i) // Recieves the value of i
{
i = i / 2;
printf("Your value halved is %d.\n", i);
return; // Returns to main
}

Here is a sample of the program’s output:


Click here to view code image


Please enter an integer... 28
Your value halved is 14.
In main(), i is still 28.

Study this first line of the half() function:


Click here to view code image


half(int i) /* Receives value of i */

Notice that you must put the data type (int) inside the receiving function’s parameter list. As Figure
31.2 shows, the contents of i are passed to half(). The i in main() is never changed because
only a copy of its value is passed.


FIGURE 31.2 The value of i is passed, not the variable i.

If you passed more than one variable separated by commas, all would have to have their data types
listed as well, even if they were all the same type. Here is a function that receives three variables: a
floating point, a character array, and an integer:


Click here to view code image


aFun(float x, char name[15], int age) /* Receives three arguments */
Free download pdf