C Programming

In the following example, the function accepts a single data variable, but does not return any information.

	/* Program to calculate a specific factorial number  */
	#include <stdio.h>

	void calc_factorial( int );    /* ANSI function prototype */

	void calc_factorial( int n )
		int  i, factorial_number = 1;
		for( i = 1; i <= n; ++i )
			factorial_number *= i;
		printf("The factorial of %d is %d\n", n, factorial_number );

		int  number = 0;
		printf("Enter a number\n");
		scanf("%d", &number );
		calc_factorial( number );

	Sample Program Output
	Enter a number
	The factorial of 3 is 6

Lets look at the function calc_factorial(). The declaration of the function

	void calc_factorial( int n )

indicates there is no return data type and a single integer is accepted, known inside the body of the function as n. Next comes the declaration of the local variables,

	int  i, factorial_number = 0;

It is more correct in C to use,

	auto int  i, factorial_number = 0;

as the keyword auto designates to the compiler that the variables are local. The program works by accepting a variable from the keyboard which is then passed to the function. In other words, the variable number inside the main body is then copied to the variable n in the function, which then calculates the correct answer.

ęCopyright B Brown. 1984-1999. All rights reserved.