#include /* Directive to compiler: include standard input/output header file*/ #define CARBON 12 /* Macro definition for a constant CARBON; it can be used in the program */ #define PI 3.14 /* we define yet another constant PI */ /* The following are examples of function declarations */ int mySum(int n, int k); double myProduct(double x, double y); int factorial(int f); /* This is a sample comment. It can take any number of lines. But it starts with forward-slash-followed-by-star and it must end with a star-followed-by-forward-slash. */ int main( void ) { /* We start our program with declaring and initializing a set of local variables */ int n=4, k=7, sum; /* We group declarations of variables according to their purposes for mnemonic reasons */ int argument, fct; double x=2.0, y=5.0, product; /* The following declares that variable outp points to a file. Note that the word FILE must be uppercase. Pointers are to be discussed later. */ FILE * outp; /* Call the function mySum to compute a sum of the given arguments n and k */ sum = mySum(n,k); /* Call function myProduct to multiply the given arguments x and y */ product = PI * myProduct(x,y); /* Ask a program user to enter an argument for the factorial function */ printf("Type argument for factorial (a positive integer less than 13) and press Enter = "); /* Ampersend preceeding a variable argument is required here to convert a variable into a pointer. This operation will be discussed later. */ scanf("%d", &argument); fct = factorial(argument); /* Print the computed values on the screen - the standard output for programs */ printf("sum= %d\n",sum); printf("factorial= %d\n",fct); printf("product= %lf\n",product); /* Print the computed values of all variables to a file named results.txt */ outp = fopen("results.txt", "w"); /* open a file for reading/writing */ fprintf(outp,"sum= %d\n",sum); fprintf(outp,"factorial= %d\n",fct); fprintf(outp,"product= %lf\n",product); /* Now, we have to close file and thereby release memory */ fclose(outp); /* This just a statement to end our program when a program returns normally. */ return(0); } int mySum(int n, int k) { int s; s = n+k; return(s); } double myProduct(double x, double y) { double p; p = x*y; return(p); } int factorial(int f) { int previous; if (f < 1) { /* We use the curved braces to enclose a consecutive pieces of code to be executed together. */ printf("Error: wrong value of argument f=%d. Argument must be an integer between 1 and 12.\n",f); return(0); } if (f > 13) { printf("Error: wrong value of argument f=%d. Argument must be an integer between 1 and 12.\n",f); return(0); } if (f == 1) return(1); if (f==2) return(2); else { previous = f -1; /* decrement value of f */ /* We compute factorial recursively and return the resulting value. Recall that factorial is defined as n! = n*(n-1)! */ return( f * factorial(previous) ); } }