/* A program to print a table showing the numbers 1..10 and their factorials, then the sum of these numbers and the sum of the factorials. */ #include /*** global variables ***/ int next_number, /* The next number to be processed */ sum_numbers; /* progressive sum */ long factorial, /* factorial of latest number to process */ sum_factorials; /* sum of the factorials */ /*** function declarations ***/ void print_heading (void); void update_totals_and_factorial (void); /*** Function definitions ***/ main () { /* Output the column headings */ print_heading(); /* Set totals and factorial variables to initial values. */ factorial = 1; /* factorial(0) is 1 */ sum_factorials = sum_numbers = 0;/* sum of nothing is zero. (This statement shows how you can assign a value (0, here) to two or more variables in one statement.) */ /* In a loop, print the detail lines in the table */ next_number = 1; /* first number to process */ while (next_number <= 10) { /* Keep going while the next_number is within the range we require. */ /* At this point: * factorial == (next_number-1)! (! is factorial fn) * sum_numbers == sum of 1..(next_number-1) * sum_factorials == sum of 1! .. (next_number-1)! */ update_totals_and_factorial(); /* Print a detail line for the number prepared */ printf("%4d%11ld\n", next_number, factorial); next_number = next_number + 1; /* update loop counter */ } /* End of the while loop */ /* After the loop: * factorial == 10! * sum_numbers == sum of 1..10 * sum_factorials == sum of 1! .. 10! */ /*** Now print the grand totals. ***/ printf ( "================\nSum of 1..%d: %d\n", 10, sum_numbers ); printf("Sum of factorials: %ld\n", sum_factorials); } /* of main */ void print_heading (void) { /* prints the headings over the columns in the table */ printf("Number Factorial\n====== =========\n"); } void update_totals_and_factorial (void) { /* Updates factorial and sum for the next number in ascending order. * On entry: factorial and sums are correct for 1..(next_number-1). * On exit: factorial and sums are correct for 1..next_number. */ factorial = factorial * next_number; sum_numbers = sum_numbers + next_number; sum_factorials = sum_factorials + factorial; }