Printing Variables

Let me remind you: we had our variables, price and count, and calculated the amount, first, without making a separate function, and then with the function. Now let's print the result.

The way how printf works in C is interesting. Its first parameter is always a text in double quotes, but if that text contains special sequences – placeholders, officially called format specifiers, they get replaced with the second, third, and subsequent parameters. f in printf means "formatted" output.

So, we can do this:

printf("The amount to pay is %d dollars\n", amount);

Here all characters of the line will be printed as is, until it reaches %d (d means "decimal"), when it takes the next parameter amount and will insert it in the output, so if amount is 15, the result would be

The amount to pay is 15 dollars

Want to try that? Here is the full program. This is a good time to introduce you to the coding exercises. The first one is really simple, just to show you how the "tests" work. Change the program to calculate the amount one would need to pay for 15321 bananas if each costs 443 dollars. Make the program print the result, and press the Run Tests button to see if it works!

#include <stdio.h>

int main() {
  int price, count, amount;

  price = 3; /* change me */
  count = 5; /* change me */

  amount = price * count;

  printf("The amount to pay is %d dollars\n", amount);

  return 0;
}

By the way, have you noticed the /* ... */ line above? That's a comment, it's ignored by the compiler, and this is how we can add some notes to the code.