Skip to main content

Output of printf statements

Short answer

The three printf calls produce one line: a=5.789100 and b=6789 from first linea=5.79 and b=0006789 from second linea=5.79 and b=6789 from third line.

Write down the output of printf() function for the following sections of statements.

float a = 5.7891;
int b = 6789;
printf("a=%4f and b=%-7d from first line",a,b);
printf("a=%-7.2f and b=%07d from second line",a,b);
printf("a=%.2f and b=%2d from third line",a,b);

Running the statements (the calls have no newline, so everything appears on one line):

#include <stdio.h>
int main(void)
{
    float a = 5.7891;
    int b = 6789;
    printf("a=%4f and b=%-7d from first line",a,b);
    printf("a=%-7.2f and b=%07d from second line",a,b);
    printf("a=%.2f and b=%2d from third line",a,b);
    return 0;
}

Output:

a=5.789100 and b=6789    from first linea=5.79    and b=0006789 from second linea=5.79 and b=6789 from third line

Reason

  • %4f: width 4 is smaller than needed, and the default precision is 6 decimals, so 5.789100. %-7d prints 6789 left aligned in 7 columns (3 trailing blanks).
  • %-7.2f: 2 decimals (5.79, rounded from 5.7891), left aligned in width 7 (3 trailing blanks). %07d pads with zeros to width 7: 0006789.
  • %.2f gives 5.79; %2d has width 2, but 6789 has 4 digits, so it prints in full as 6789.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 4 questions →