2.3 Placeholders



Placeholders are used both to print something to the screen and to take input from the user. They quite literally “hold the place” of the variable in printf() and scanf() statements. Below are the placeholders for the data types we have introduced thus far:
  • %f → float
  • %g → double
  • %c → char
  • %s → string
  • %d → int
  • %li → long
  • %hi → short
Let’s see these placeholders used in action!
Here is an example of a placeholder used in a printf() statement:
int number = 8; printf(“The value of number is %d”, number);
There are several new components worth talking about that make up the above code. The first line is where we created a variable called “number” of type int and assigned it the value 8. In the second line, we have our printf() statement, in which we have quotation marks with text we want to display to the user. In addition to just the text, though, we also have a placeholder inside the quotation marks.
Recall that %d is the placeholder for an int value. After the quotation marks, we have a comma and then the name of the variable that %d is holding a place for. This is how the computer knows that we want to display the value of our variable, “number”, to the user. The above code would print out the following:
The value of number is 8



In my code, I use the same name (Anika) and number (15) over and over again! To help me, can you create a variable and replace all occurrences of the number with the variable?
#include <stdio.h> int main(void) { printf("My name is Anika and I am 15 years old. "); printf("My twin sister, also named Anika, is 15 years old. "); printf("Our friend, Anika, is also 15 years old. "); printf("Together, we all have 15 toy bears, all named Anika. "); }
Example answer
#include <stdio.h> int main(void) { char name[] = "Anika"; int age = 15; /* match the %s or the %d to each of the variables 1st %s is for name 2nd %s is for " and I am " %d is for age last %s is for " years old" */ printf("My name is %s %s %d %s", name, "and I am", age, "years old."); printf("My twin sister, also named %s %s %d %s", name, ", is", age, "years old."); printf("Together, we all have %d %s %s", age, "toy bears, all named", name); }

Previous Section

Next Section

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.