Question 7
Back to Exercise
What is the output of the following C program?
#include <stdarg.h>
#include <stdio.h>
void percent(int n, ...) {
va_list ap, ap2;
va_start(ap, n);
va_copy(ap2, ap);
int sum = 0;
for (int i = 0; i < n; i++)
sum += va_arg(ap, int);
for (int i = 0; i < n; i++)
printf("%d%% ", va_arg(ap2, int) * 100 / sum);
va_end(ap2);
va_end(ap);
printf("\n");
}
int main(void) {
percent(3, 1, 1, 2);
return 0;
}
- A 1% 1% 2%
- B 33% 33% 66%
- C 25% 25% 50% Correct
- D 0% 0% 0%
Correct Answer: Option C
The first pass computes the sum (4); the copy, made before that pass, starts again at the first argument for the second pass.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!