ProgrammingModerate
n <= 10^5 values, each up to 10^9, must be summed. Which declaration is correct for the total?
- A. long long total = 0;
- B. int total = 0;
- C. short total = 0;
- D. unsigned int total = 0; with a cast on every addend
Correct answer: A. long long total = 0;
The sum can reach 10^14, far above INT_MAX, so the total needs at least a 64-bit type. unsigned int is also too small, and wrapping would give a wrong answer.
More C Programming questions
- To test whether n = 10^12 is prime by trial division up to sqrt(n), which loop is correct?
- A middle index of a range [lo, hi] is needed for hi near INTMAX. Which expression is safe?
- A scanf loop reads integers until the end of input. Which loop is correct when the input may end with a non-numeric token?
- A character loop reads bytes with char c = getchar() and tests while (c != EOF). Why can this loop be wrong?
- To count occurrences of values up to 10^6 in O(n), which code is correct and fast enough?
- A recursive depth-first search could recurse 10^6 levels deep on a path-shaped graph. Which approach is correct and safe?