Skip to main content
Logo image

Section 11.1 Formatted Input and Output

We have already seen and used the printf() and the scanf() statements. Both have additional options that come in handy when trying to produce nicely formatted output.
Figure 11.1.

Check Your Understanding Check Your Understanding

1.

    How do you print the sentence She said "yes" to my suggestion. using the printf() command? Feel free to use the window below to try out some commands.

    admin.....open in new window

  • printf("She said \"yes\" to my suggestion.");
  • Correct
  • printf("She said "yes" to my suggestion.");
  • Not quite. Try again!
  • printf("She said ""yes"" to my suggestion.");
  • Not quite. Try again!
  • printf("She said 'yes' to my suggestion.");
  • Not quite. Try again!

2.

    What happens when you don’t have enough variables to match the number of format specifiers in your format string? For example, what happens when you type:
    int age = 34;
    printf("I am %d years old and weight %f pounds.", age);
    
    Feel free to quickly write a program to try this out.

    admin.....open in new window

  • The compiler will give a warning, but the program will run and print something.
  • Correct
  • The program will compile but crash at runtime.
  • Not quite. Try again!
  • The compiler automatically substitutes the correct value for the missing variable.
  • Not quite. Try again!
  • The compiler will abort with an error message.
  • Not quite. Try again!
Sometimes it is useful to use additional formatting options that are available for format specifiers in order to control the output more precisely.

Check Your Understanding Check Your Understanding

1.

    What is the output of
    printf("a = %05d\n", 35);
    You should first think about this and try to figure out the answer by hand. Then feel free to use the window below to write a program to verify your answer. This time you have to write the entire program by yourself (hint: get started by copying and pasting from a previous program.)

    admin.....open in new window

  • a = 00035
  • Correct
  • 35
  • Not quite. Try again!
  • 00035
  • Not quite. Try again!
  • a = 0535
  • Not quite. Try again!

2.

    What happens when you use the format specifier %f to print out an integer? (feel free to write a short C program to try this out).

    admin.....open in new window

  • The compiler will give a warning and output will most likely be incorrect.
  • Correct
  • No answer text provided.
  • Not quite. Try again!
  • The compiler will notice and abort the compilation with an error message.
  • Not quite. Try again!
  • The integer is automatically converted to a float and printed out correctly.
  • Not quite. Try again!