/**************************************************************************** * sigma1.c * * Computer Science 50 * David J. Malan * * Adds the numbers 1 through n. * * Demonstrates iteration. ***************************************************************************/ #include #include /* prototype */ int sigma(int); int main(int argc, char * argv[]) { int answer, n; /* ask user for a positive int */ do { printf("Positive integer please: "); n = GetInt(); } while (n < 1); /* compute sum of 1 through n */ answer = sigma(n); /* report answer */ printf("%d\n", answer); } /* * int * sigma(int m) * * Returns sum of 1 through m; returns 0 if m is not positive. */ int sigma(int m) { int i, sum = 0; /* avoid risk of infinite loop */ if (m < 1) return 0; /* return sum of 1 through m */ for (i = 1; i <= m; i++) sum += i; return sum; }