C: For Beginners - Working with Numbers
(Page 3 of 4 )
The printf function described above is used to print text or strings to the screen. If we typed in the code:
#include <stdio.h>
int main (void)
{
printf("2+2= ");
return 0;
}
It would simply print:
2+2=
and not solve the math. To get the program to perform our math for us, we would write the following:
#include <stdio.h>
int main (void)
{
printf("2+2= %d", 2+2);
return 0;
}
The result:
2+2= 4
The way this code works is it creates a placeholder (in this instance %d) that will hold a value, which we defined after the comma (,): 2+2 (or 4). There are many placeholders (or format specifiers) in C, and we will discuss them more later on. But for now, here is a basic set of them in an awe-inspiring table:
Placeholder | What it Holds |
%i and %d | Integer |
%f | Float |
%If | Double |
%s | String |
%x | Hexadecimal |
%c | Character |
We will discuss the various data types in a different article. I just wanted to show you these here to give you an idea of how placeholders operate. An example of another way to use a placeholder is to define where your text will appear. Suppose I wanted to print some text to the left and then some text to the right. I could do so this way:
#include <stdio.h>
int main (void)
{
printf("%40s","Hey! Where are you?!?n");
printf("%-40s","I'm over here!");
printf("%400s","Oh! Now I see you!");
return 0;
}
The %40s tells the program to move the text 40 spaces to the right. The %-40s moves the text to the left. And the %400s moves the text 400 spaces to the right; however, there aren't 400 spaces on a line, so it moves it down a few more lines until four hundred spaces have been entered, then it prints the text. Here is the result:
Hey! Where are you?!?
I'm over here!
Oh! Now I see you!
Next: Putting on the Puts() >>
More BrainDump Articles
More By James Payne