printf
Functionprintf
FunctionIt is very useful for programs to display an output!
We can use the printf
function to do this!
printf
Function
printf(FMT,arg1,arg2,...);
FMT
- Format stringThe format string (FMT) instructs the function on how to display the information.
For example, printf("Hello")
will display Hello.
To show numbers, we can use the %d
format specifier.
printf("A day has %d hours", 24);
$> ./program
A day has 24 hours
To show single letters, we can use the %c
format specifier.
printf("Dog starts with a %c", 'd');
$> ./program
Dog starts with a d
To print out a '%'
, we put %%
in the format specifier.
printf("The percentage sign is %%.");
$> ./program
The percentage sign is %.
There are many other format specifiers!
%f | Floating Point Number |
%s | String |
%x | Hexadecimal Number |
%p | Point |
etc… |
\n
If we run the following program.
#include <stdio.h>
int main(void){
printf("Hello");
printf("How are you?");
return 0;
}
We will see this
HelloHow are you?
This is because printf does not start on a new line!
To show each sentence separately, we need to put a new line character - represented by \n
.
#include <stdio.h>
int main(void){
printf("Hello\n");
printf("How are you?\n");
return 0;
}
We will now see
Hello
How are you?
Write a program to print “My name is …”, followed by your name. Use an appropriate format specifier.
#include <stdio.h>
int main(void) {
// WRITE YOUR CODE HERE
return 0;
}
Write a program to print out a bird
__
<(o )___
( ._> /
`---'