/** * @file sum.c * @brief Example of sums using with function prototypes. * * This file contains three sum functions showing basic functionality. It also * uses forward declarations, separating the declaration and the definition of * the "sum" functions. Note how the functions are declared above main() and * defined below main. * * @author Michael J. Bannister * @author Peter Mawhorter * @date 10 Nov 2015 * @date 10 Nov 2016 */ #include #include #include // Forward declaration of functions. // Functions need to be declared before their first use. int sum_one(int n); int sum_two(int n); int sum_three(int n); // Program entry point. int main() { fputs("Please enter a number: ", stdout); int n = 0; fscanf(stdin, "%d", &n); fprintf( stdout, "The sum of the number from 1 to %d is %d.\n", n, sum_one(n) ); fprintf( stdout, "The sum of the number from 1 to %d is %d.\n", n, sum_two(n) ); fprintf( stdout, "The sum of the number from 1 to %d is %d.\n", n, sum_three(n) ); return EXIT_SUCCESS; } // Function definitions below this point. // Functions are defined here after they are used. int sum_one(int n) { assert(n > 0); int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; } int sum_two(int n) { assert(n > 0); int A[n]; for (int i = 0; i < n; i++) { A[i] = i + 1; } int sum = 0; for (int i = 0; i < n; i++) { sum += A[i]; } return sum; } int sum_three(int n) { assert(n > 0); if (n == 1) { return 1; } return n + sum_three(n - 1); }