Demonstrating C function: calculating the cube volume for the given side

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Calculate the cube volume for the given side read  from the standard input

To show: A very simple C user defined function demonstrating how to calculate cube volume for the given side

 

 

// Demonstrates a simple user defined function

#include <stdio.h>

 

// function prototype needed by standard before defining and using the function

long cube(long);

 

void main(void)

{

long input, answer;

printf("\n--Calculating cube volume--\n");

printf("Enter a positive integer, for cube side (meter): ");

/* scanf("%d", &input); */

scanf_s("%d", &input, 1);

// calling cube function

answer = cube(input);

// %ld is the conversion specifier for a long decimal integer

printf("\nCube with side %ld meter, is %ld cubic meter.\n", input, answer);

}

 

// function definition, define what the function will do, receive long, return long

long cube(long x)

{

// local scope (to this function) variable

long x_cubed;

// do some calculation

x_cubed = x * x * x;

// return a result to the calling program

return x_cubed;

}

 

Output example:

 

--Calculating cube volume--

Enter a positive integer, for cube side (meter): 10

Cube with side 10 meter, is 1000 cubic meter.

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index