Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
603 B

  1. #include <stdio.h>
  2. #include <limits.h>
  3. int getNumber(void);
  4. int main(void) {
  5. int count = 0;
  6. int sum = 0;
  7. int end = getNumber();
  8. if (end >= 0) {
  9. while (count++ < end) {
  10. if (INT_MAX / count < count || (INT_MAX - sum) < count * count) {
  11. printf("Integer overflow\n");
  12. return 1;
  13. } else {
  14. sum = sum + count * count;
  15. }
  16. }
  17. printf("sum = %d\n", sum);
  18. }
  19. return 0;
  20. }
  21. int getNumber(void) {
  22. int number;
  23. printf("How far should we add: ");
  24. if (!scanf("%d", &number) || number < 0) {
  25. number = -1;
  26. }
  27. return number;
  28. }