3. printf() will print formatted output to the screen.
To print a message:
printf("This is a messagen");
How do we print the value of a variable?
Answer: Use special format specifiers depending on the type of
the variable
this is a string literal
Printing Output: printf()
Compiled By: Kamal Acharya
5. int degreesF = 68;
printf("The temperature is %d degrees.", degreesF);
Specifier for
“print an integer value”
“and the value of
that number is read
from this variable”
> The temperature is 68 degrees.
Output:
Compiled By: Kamal Acharya
6. int a = 1;
int b = 2;
int c = 3;
printf(“%d plus %d is equal to %d", a, b, c);
1 plus 2 is equal to 3
Output:
Compiled By: Kamal Acharya
7. Format specifiers:
%c for single characters
%d for integers
%f for float/double (fractions): 1234.56
%g for float/double (scientific): 1.23456E+3
%s for phrases or ‘strings’
Compiled By: Kamal Acharya
8. Output:
A 65 41 101
Example:
char a='A';
printf("%c %d %x %0", a, a, a, a);
Compiled By: Kamal Acharya
9. Format specifier can be used with modifiers
Example :
%-6d, %5d, %6.2f
Modifier
digit
Description
Allocate minimum width (in characters).
.digit Number of floating-points
- left justified
l Print the data as a long integer.
Compiled By: Kamal Acharya
12. Control Characters (Escape Sequences)
Character
'n'
't'
'v'
'r'
'x41'
'101'
'0'
'''
'"'
''
'b'
'f'
'a'
Description
newline
horizontal tab
vertical tab
carriage return
hexadecimal number, 0x41
octal number 101
null character - indicates the end of a string
single quatation mark (')
double quatation mark (")
backslash mark ()
backspace
formfeed - next page (used for printer)
alert - produce a beep sound
Compiled By: Kamal Acharya
13. Figure: Output specification for inventory report
printf (“Part NumbertQty On HandtQty On OrderttPricen”);
t t tt n
Compiled By: Kamal Acharya
14. Keyboard input: scanf()
scanf() will scan formatted input from the keyboard.
It uses the same format specifiers as printf()
To read an integer:
int num_students;
scanf("%d", &num_students);
Specifier for
“reading an integer value”
VERY IMPORTANT
special symbol
“Place value into this
variable”
Compiled By: Kamal Acharya
16. Format specifiers for scanf()
Format specifiers:
%c for single characters
scanf(" %c", &some_character);
%d for integers
scanf ("%d", &some_integer);
%f for float
scanf ("%f", &some_float);
%lf for double
scanf ("%lf", &some_double);
always put a space between " and % when reading characters
Compiled By: Kamal Acharya