By breaking large computing tasks into smaller ones, you can debug the each component (more manageable).
e.g., You have already used useful functions, such as printf(), drand48(). These functions are included in libraries, and reusable. You can also make your reusable functions by yourself.
#include <stdio.h> /* function prototype */ int Power(int x, int y); int main (void) { int i, answer; for (i = 0; i < 32; i++) { answer = Power(2, i); printf("%d -th power of 2 = %d\n", i, answer); } return 0; } /* function definition */ /* * raise base to the n-th power, n >= 0 */ int Power (int base, int n) { int i, result; result = 1; for (i = 0; i < n; i++) { result = result * base; } return result; }
Copy /home/progClass/src/logistic/power.c to your home directory, compile and run it, and see the results.
return_type function_name( arg_type name1,...,arg_type nameN);
e.g., all of the followings can be substitued in the above code.
int Power(int, int); int Power(int dummy1, int dummy2);
The function definition contains the code which will be executed.
return_type function_name(arg_type name1, ..., arg_type nameN)
{
/* declaration of variables used in the function */
/* statements; */
/* return variable */
}
#include <stdlib.h> double NegRand(void); int main (void) { double x; srand48(20303); x = NegRand(); printf("%f\n", x); return 0; } double NegRand(void) { double retVal = -drand48(); return retVal; }
int CoinFlip (void) { if (drand48() < 0.5) { return 1; /* head */ } else { return 0; /* tail */ } }
void JustPrintNewline (void) { printf ("\n"); return; }
int SomeFunction (int x, int y) { int sum, result; sum = x + y; result = AnotherFunction(sum); return (result); } int AnotherFunction (int z) { return z * z; }
int SomeFunction (int x, int y) { int sum, result; sum = x + y; int AnotherFunction (int z) { return z * z; } result = AnotherFunction(sum); return (result); }
The naming rules for variables apply.
Make a function which takes 2 integers as the arguments, and return the larger integer.