LearnFrenzy
Sign in Take a free test

Variable Number of Arguments · Predict the Output · Question 7

Two passes over the arguments with va_copy Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following C program?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links