SlideShare a Scribd company logo
1 of 21
This presentation includes custom animations.
To view the animations, you must view the presentation in Slide Show mode
and activeX controls must be allowed.
If you have opened this lesson in PowerPoint, use the PowerPoint menus to
view it in slide show mode.
If you have opened this lesson in a browser and see a bar similar to that below,
click on the Slide Show icon
A notice similar to the one below may appear warning that ActiveX or
other scripts are disabled. Enable the controls for this website in order
to see the animations.
printf
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
This lesson describes the syntax and use of the printf library functions:
printf()
fprintf()
sprintf()
Vocabulary:
To use printf, fprintf, or sprintf, you must #include <stdio.h>Click
Tip
ASCII
conversion specifier
file name extension
FILE pointer
flag
fprintf()
placeholder
precision
printf()
result
sprintf()
stdout
text file
unicode
width
3
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
The printf functions are used to produce formatted output.
printf sends the output to stdout.
stdout is a predefined macro
that represents the standard
output and is typically the
computer monitor although
this can be changed by the
end user.
Click
Tip
Click
Tip
A text file is one in which
every byte is a character from
the ASCII, Unicode, or other
character set. The extension
can be anything the
programmer chooses.
sprintf sends the output to a string variable.
Click
Tip
fprintf sends the output to a text file.
/* VARIABLE DECLARATIONS */
char Message[81];
The target string must be
long enough to hold the
entire output + 1 byte for
the null.
4Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
syntax diagrams for the printf cousins from Appendix B of the text
All 3 include, for each placeholder, an argument that specifies the value
to be used in place of the placeholder.
All 3 include an output string that specifies what to output expressed as:
literals + escape sequences + placeholders.
All 3 return the number of bytes (characters) written to output.
Although the square brackets indicate that the arguments at the end
are optional, that is a bit misleading. They are required if there are
any placeholders in the output string. There must be one argument
(value) provided for each placeholder.
Click
Tip
int printf (const char *format [, argument, …]);
int fprintf (FILE *stream, const char *format [, argument, …]);
int sprintf (char *buffer, const char *format [, argument, …]);
5Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
The syntax of the cousins varies only in the required arguments.
sprintf has 2 required arguments. The first argument in sprintf identifies
the destination string variable and the 2nd argument is the output string.
fprintf has 2 required arguments. The first argument in fprintf identifies
the file pointer for the destination file and the 2nd argument is the output
string.
printf has 1 required argument. That required argument is the output
string.
stdout is treated like a file pointer in C so the following 2
constructions produce the same result:
printf("Hello");
fprintf(stdout, "Hello");
Click
Tip
int printf (const char *format [, argument, …]);
int fprintf (FILE *stream, const char *format [, argument, …]);
int sprintf (char *buffer, const char *format [, argument, …]);
6
int printf (const char *format [, argument, …]);
All 3 of the printf functions return a result with a data type of int.
The result is a count of the number of characters in the output.
Example:
NumLetters = printf(“Hello”);
NumLetters == 5
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
7
It is not necessary to assign the result to a value – but if the result is
assigned, then the variable on the left of the assignment operator
MUST be an int.
Example:
int NumLetters;
printf(“Goodbye”);
NumLetters = printf(“Hello”);
If assigned, the
result must be
stored in an int
It is OK to call a
function without
assigning its value
to a variable.
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
8
int printf (const char *format [, argument, …]);
const char *format means that you must include an output string that is a set of
characters that are to be displayed on the screen along with escape
sequences and conversion specifiers (placeholders).
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
printf("First name: ");
printf("Thank you. Please visit again.");
printf("Please enter a number"); Please enter a number
First name:
Thank you. Please visit again.
printf("Report Menu"); Report Menu
What is the result of each of the following statements?
(Click each button to check your answer.)
9Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
Escape sequences are used to express output that cannot be represented on
the keyboard or to express output that might be mistaken for C code.
Examples of output that cannot be represented on the keyboard:
r Carriage Return (move cursor to beginning of current line)
f Form Feed (new page)
a Audible Alert (bell)
Examples of output that might be mistaken for C code.
n Newline
t Horizontal Tab
v Vertical Tab
b Backspace
 Backslash
? Question mark
' Single quote
" Double quote
%% Percent sign (honorary escape sequence)
int printf (const char *format [, argument, …]);
10
What is the result of each of the following statements?
(Click each button to check your answer.)
printf("acd");
printf("abc");
printf("atbtc");
printf("acd");
printf("a"b");
printf("a"b");
printf("anbnc");
abc
a b c
a
b
c
syntax error!!!
a"b
acd
acd
printf("anbtc");
a
b c
c and d are not defined
escape sequences so the
 is ignored.
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
printf("a%%cd"); a%cd
11
int printf (const char *format [, argument, …]);
Conversion specifiers are placeholders for values are not known at the time the
code is written.
Some common conversion specifiers:
for data type use placeholder
int %d
float %f
char %c
string %s
int (base 10) %i
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
http://www.cplusplus.com/reference/clibrary/cstdio/printf.html
See the full list of conversion specifiers at:
type%
12
printf(“The answer is %d”, 3);
printf(“She is %d years old.”, age);
printf(“%d + %d = %d”, numA, numB, numA + numB);
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
For each placeholder, there must be a value in the argument list.
The data type of the value must match or be cast as the value indicated by the
format specifier.
The order in which the placeholders appear in the output string must exactly
match the order of the values in the argument list.
1 placeholder 1 value
1 placeholder 1 value
3 placeholder 3 values
13
Assume the following code appears before the statements below:
int answer;
int age;
int numA;
int numB;
answer = 3;
age = 22;
numA = 14;
numB = 12;
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
printf("%d + %d = %d", numA, numB, numA + numB);
printf("She is %d years old.", age);
printf(“The answer is %d”, 3); The answer is 3
14 + 12 = 26
She is 22 years old.
What is the result of each of the following statements?
(Click each button to check your answer.)
printf("%d + %d = %d", numA, numB, numA + numA); 14 + 12 = 28
Understand why the computer displays a falsehood.
14
Assume the following code appears before the statements below:
double classAvg = 78.5;
char AvgLetter = 'B';
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
printf(“pi can be expressed as %c, %d, or %f”, PI, 3, 22/7.0);
printf(“The average letter grade was %c”, AvgLetter);
printf(“The class average was %f”, classAvg);
The class average was 78.500000
pi can be expressed as π, 3, or 3.142857
The average letter grade was B
What is the result of each of the following statements?
(Click each button to check your answer.)
PI is a predefined keyword in C.
Click
Tip
15
Notice that the arguments can be literals, variables, or any expression that
returns a value with the appropriate data type.
printf(“%d %d %d”, 5, NumClients, 6 + 3);
literal variable expression
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
16
As in all C code – you must sweat the details!
Sweat it that there is a comma between every pair of arguments - including the
output string if it is followed by another argument.
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
Sweat it that the closing double quote is after the output string - NOT after the
last argument!
Sweat it that there is a semicolon at the end of the statement.
printf(“pi can be expressed as %c, %d, or %f” , PI, 3, 22/7.0);
printf("Hello World");
printf(“The average letter grade was %c”, AvgLetter);
17
Sweat it that printf does not automatically add spaces around the inserted
arguments. The programmer must include the spaces in the output
string.
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
printf("She is%dyears old.", 23); She is23years old.
printf("She is %d years old.", 23); She is 23 years old.
18
Sweat it that the programmer must code every character that should appear on
the screen,
… to get commas in a list of values, include the commas at the
appropriate place inside the format string
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
printf(“%d %d %d”, 5, NumClients, 6 + 3); 5 123 9
printf(“%d, %d, %d”, 5, NumClients, 6 + 3); 5, 123, 9
The DOS window uses a non-proportional font. Each
character uses the exact same amount of horizontal space.
Courier New is an example of a non-proportional font.
Click
Tip
19
The printf placeholders may include formatting options.
Required
type%
Optional
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
[flags] [width] [.prec] [hlL] type%
20
http://www.cplusplus.com/reference/clibrary/cstdio/printf.html
In your textbook, see Table 12.2 "Placeholders for printf format strings"
The following link is also very helpful.
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
[flags] [width] [.prec] [hlL]% type
[flags] The most common flag is the minus sign, -. It reverses the normal
left/right alignment. Normal for text is left aligned, normal for numeric
data is right aligned.
[width] The width specifies the MINIMUM number of characters to be
displayed. If the value requires fewer characters, the width is
padded with blank spaces. If the value requires more characters, all
the characters are output using a greater width. The specified width
is a MINIMUM.
For numeric types, the width specifer includes space for the digits
(both right and left of the decimal point) and the decimal point itself.
[.prec] The precision option specifies the exact number of digits to display to
the right of the decimal point. These digits count as part of the width.
[hlL] Also referred to as the length option, this indicates a modification of
the data type as short or long.
21
Christine S. Wolfe
Ohio University Lancaster
2008-Aug-01
printf(“Average cost: %-8.3f !” , 3.4);
printf(“ ***%-10.4f***”, 12.333);
printf(“ ***%10.1f***”, 12.333); *** 12.3***
Average cost: 3.400 !
***12.3330 ***
printf(“%5s%10sn”, "ID","Amount");
printf(“n%5d%10.2f”, 1,12.15);
printf(“n%5d%10.2f”, 2,1.6);
printf(“n%5d%10.2f”, 3,4500.5);
printf(“n%5d%10.2f”, 4,1234567890.0123);
printf(“n%5d%10.2f”, 5,16.367);
ID Amount
1 12.15
2 1.60
3 4500.50
41234567890.01
5 16.37
What is the result of each of the following statements?
(Click each button to check your answer.)
Make sure you understand why the row for ID 4
is out of line with the others.
Send me an email telling me how you would
correct the problem.

More Related Content

What's hot

Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’eShikshak
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C ProgrammingKamal Acharya
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 
1584503386 1st chap
1584503386 1st chap1584503386 1st chap
1584503386 1st chapthuhiendtk4
 
Input and output in c
Input and output in cInput and output in c
Input and output in cRachana Joshi
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and OutputSabik T S
 
C Prog. - Decision & Loop Controls
C Prog. - Decision & Loop ControlsC Prog. - Decision & Loop Controls
C Prog. - Decision & Loop Controlsvinay arora
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingSabik T S
 
C Programming basics
C Programming basicsC Programming basics
C Programming basicsJitin Pillai
 

What's hot (20)

C tutoria input outputl
C tutoria input outputlC tutoria input outputl
C tutoria input outputl
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
1584503386 1st chap
1584503386 1st chap1584503386 1st chap
1584503386 1st chap
 
Input and output in c
Input and output in cInput and output in c
Input and output in c
 
UNIT-II CP DOC.docx
UNIT-II CP DOC.docxUNIT-II CP DOC.docx
UNIT-II CP DOC.docx
 
CPU INPUT OUTPUT
CPU INPUT OUTPUT CPU INPUT OUTPUT
CPU INPUT OUTPUT
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
 
C Prog. - Decision & Loop Controls
C Prog. - Decision & Loop ControlsC Prog. - Decision & Loop Controls
C Prog. - Decision & Loop Controls
 
Basic Input and Output
Basic Input and OutputBasic Input and Output
Basic Input and Output
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
COM1407: Input/ Output Functions
COM1407: Input/ Output FunctionsCOM1407: Input/ Output Functions
COM1407: Input/ Output Functions
 
01 Jo P Jan 07
01 Jo P Jan 0701 Jo P Jan 07
01 Jo P Jan 07
 
Introduction to Input/Output Functions in C
Introduction to Input/Output Functions in CIntroduction to Input/Output Functions in C
Introduction to Input/Output Functions in C
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Assignment7
Assignment7Assignment7
Assignment7
 
C Programming basics
C Programming basicsC Programming basics
C Programming basics
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 

Similar to miniLesson on the printf() function

Chap 2 input output dti2143
Chap 2  input output dti2143Chap 2  input output dti2143
Chap 2 input output dti2143alish sha
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Functionimtiazalijoono
 
Unit 5 Foc
Unit 5 FocUnit 5 Foc
Unit 5 FocJAYA
 
Concepts of C [Module 2]
Concepts of C [Module 2]Concepts of C [Module 2]
Concepts of C [Module 2]Abhishek Sinha
 
ภาษาซีพื้นฐาน
ภาษาซีพื้นฐานภาษาซีพื้นฐาน
ภาษาซีพื้นฐานKrunee Thitthamon
 
Input output functions
Input output functionsInput output functions
Input output functionshyderali123
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input OutputBharat17485
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)SURBHI SAROHA
 
Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer OverflowsSumit Kumar
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures Pradipta Mishra
 
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);Joel Porquet
 

Similar to miniLesson on the printf() function (20)

Chap 2 input output dti2143
Chap 2  input output dti2143Chap 2  input output dti2143
Chap 2 input output dti2143
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Unit 5 Foc
Unit 5 FocUnit 5 Foc
Unit 5 Foc
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
Concepts of C [Module 2]
Concepts of C [Module 2]Concepts of C [Module 2]
Concepts of C [Module 2]
 
C Basics
C BasicsC Basics
C Basics
 
2 data and c
2 data and c2 data and c
2 data and c
 
ภาษาซีพื้นฐาน
ภาษาซีพื้นฐานภาษาซีพื้นฐาน
ภาษาซีพื้นฐาน
 
Input output functions
Input output functionsInput output functions
Input output functions
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
CHAPTER 4
CHAPTER 4CHAPTER 4
CHAPTER 4
 
Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer Overflows
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
input
inputinput
input
 
Unit 2- Module 2.pptx
Unit 2- Module 2.pptxUnit 2- Module 2.pptx
Unit 2- Module 2.pptx
 
What is c
What is cWhat is c
What is c
 
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
 

Recently uploaded

Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 

Recently uploaded (20)

Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 

miniLesson on the printf() function

  • 1. This presentation includes custom animations. To view the animations, you must view the presentation in Slide Show mode and activeX controls must be allowed. If you have opened this lesson in PowerPoint, use the PowerPoint menus to view it in slide show mode. If you have opened this lesson in a browser and see a bar similar to that below, click on the Slide Show icon A notice similar to the one below may appear warning that ActiveX or other scripts are disabled. Enable the controls for this website in order to see the animations.
  • 2. printf Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 This lesson describes the syntax and use of the printf library functions: printf() fprintf() sprintf() Vocabulary: To use printf, fprintf, or sprintf, you must #include <stdio.h>Click Tip ASCII conversion specifier file name extension FILE pointer flag fprintf() placeholder precision printf() result sprintf() stdout text file unicode width
  • 3. 3 Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 The printf functions are used to produce formatted output. printf sends the output to stdout. stdout is a predefined macro that represents the standard output and is typically the computer monitor although this can be changed by the end user. Click Tip Click Tip A text file is one in which every byte is a character from the ASCII, Unicode, or other character set. The extension can be anything the programmer chooses. sprintf sends the output to a string variable. Click Tip fprintf sends the output to a text file. /* VARIABLE DECLARATIONS */ char Message[81]; The target string must be long enough to hold the entire output + 1 byte for the null.
  • 4. 4Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 syntax diagrams for the printf cousins from Appendix B of the text All 3 include, for each placeholder, an argument that specifies the value to be used in place of the placeholder. All 3 include an output string that specifies what to output expressed as: literals + escape sequences + placeholders. All 3 return the number of bytes (characters) written to output. Although the square brackets indicate that the arguments at the end are optional, that is a bit misleading. They are required if there are any placeholders in the output string. There must be one argument (value) provided for each placeholder. Click Tip int printf (const char *format [, argument, …]); int fprintf (FILE *stream, const char *format [, argument, …]); int sprintf (char *buffer, const char *format [, argument, …]);
  • 5. 5Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 The syntax of the cousins varies only in the required arguments. sprintf has 2 required arguments. The first argument in sprintf identifies the destination string variable and the 2nd argument is the output string. fprintf has 2 required arguments. The first argument in fprintf identifies the file pointer for the destination file and the 2nd argument is the output string. printf has 1 required argument. That required argument is the output string. stdout is treated like a file pointer in C so the following 2 constructions produce the same result: printf("Hello"); fprintf(stdout, "Hello"); Click Tip int printf (const char *format [, argument, …]); int fprintf (FILE *stream, const char *format [, argument, …]); int sprintf (char *buffer, const char *format [, argument, …]);
  • 6. 6 int printf (const char *format [, argument, …]); All 3 of the printf functions return a result with a data type of int. The result is a count of the number of characters in the output. Example: NumLetters = printf(“Hello”); NumLetters == 5 Christine S. Wolfe Ohio University Lancaster 2008-Aug-01
  • 7. 7 It is not necessary to assign the result to a value – but if the result is assigned, then the variable on the left of the assignment operator MUST be an int. Example: int NumLetters; printf(“Goodbye”); NumLetters = printf(“Hello”); If assigned, the result must be stored in an int It is OK to call a function without assigning its value to a variable. Christine S. Wolfe Ohio University Lancaster 2008-Aug-01
  • 8. 8 int printf (const char *format [, argument, …]); const char *format means that you must include an output string that is a set of characters that are to be displayed on the screen along with escape sequences and conversion specifiers (placeholders). Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 printf("First name: "); printf("Thank you. Please visit again."); printf("Please enter a number"); Please enter a number First name: Thank you. Please visit again. printf("Report Menu"); Report Menu What is the result of each of the following statements? (Click each button to check your answer.)
  • 9. 9Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 Escape sequences are used to express output that cannot be represented on the keyboard or to express output that might be mistaken for C code. Examples of output that cannot be represented on the keyboard: r Carriage Return (move cursor to beginning of current line) f Form Feed (new page) a Audible Alert (bell) Examples of output that might be mistaken for C code. n Newline t Horizontal Tab v Vertical Tab b Backspace Backslash ? Question mark ' Single quote " Double quote %% Percent sign (honorary escape sequence) int printf (const char *format [, argument, …]);
  • 10. 10 What is the result of each of the following statements? (Click each button to check your answer.) printf("acd"); printf("abc"); printf("atbtc"); printf("acd"); printf("a"b"); printf("a"b"); printf("anbnc"); abc a b c a b c syntax error!!! a"b acd acd printf("anbtc"); a b c c and d are not defined escape sequences so the is ignored. Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 printf("a%%cd"); a%cd
  • 11. 11 int printf (const char *format [, argument, …]); Conversion specifiers are placeholders for values are not known at the time the code is written. Some common conversion specifiers: for data type use placeholder int %d float %f char %c string %s int (base 10) %i Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 http://www.cplusplus.com/reference/clibrary/cstdio/printf.html See the full list of conversion specifiers at: type%
  • 12. 12 printf(“The answer is %d”, 3); printf(“She is %d years old.”, age); printf(“%d + %d = %d”, numA, numB, numA + numB); Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 For each placeholder, there must be a value in the argument list. The data type of the value must match or be cast as the value indicated by the format specifier. The order in which the placeholders appear in the output string must exactly match the order of the values in the argument list. 1 placeholder 1 value 1 placeholder 1 value 3 placeholder 3 values
  • 13. 13 Assume the following code appears before the statements below: int answer; int age; int numA; int numB; answer = 3; age = 22; numA = 14; numB = 12; Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 printf("%d + %d = %d", numA, numB, numA + numB); printf("She is %d years old.", age); printf(“The answer is %d”, 3); The answer is 3 14 + 12 = 26 She is 22 years old. What is the result of each of the following statements? (Click each button to check your answer.) printf("%d + %d = %d", numA, numB, numA + numA); 14 + 12 = 28 Understand why the computer displays a falsehood.
  • 14. 14 Assume the following code appears before the statements below: double classAvg = 78.5; char AvgLetter = 'B'; Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 printf(“pi can be expressed as %c, %d, or %f”, PI, 3, 22/7.0); printf(“The average letter grade was %c”, AvgLetter); printf(“The class average was %f”, classAvg); The class average was 78.500000 pi can be expressed as π, 3, or 3.142857 The average letter grade was B What is the result of each of the following statements? (Click each button to check your answer.) PI is a predefined keyword in C. Click Tip
  • 15. 15 Notice that the arguments can be literals, variables, or any expression that returns a value with the appropriate data type. printf(“%d %d %d”, 5, NumClients, 6 + 3); literal variable expression Christine S. Wolfe Ohio University Lancaster 2008-Aug-01
  • 16. 16 As in all C code – you must sweat the details! Sweat it that there is a comma between every pair of arguments - including the output string if it is followed by another argument. Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 Sweat it that the closing double quote is after the output string - NOT after the last argument! Sweat it that there is a semicolon at the end of the statement. printf(“pi can be expressed as %c, %d, or %f” , PI, 3, 22/7.0); printf("Hello World"); printf(“The average letter grade was %c”, AvgLetter);
  • 17. 17 Sweat it that printf does not automatically add spaces around the inserted arguments. The programmer must include the spaces in the output string. Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 printf("She is%dyears old.", 23); She is23years old. printf("She is %d years old.", 23); She is 23 years old.
  • 18. 18 Sweat it that the programmer must code every character that should appear on the screen, … to get commas in a list of values, include the commas at the appropriate place inside the format string Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 printf(“%d %d %d”, 5, NumClients, 6 + 3); 5 123 9 printf(“%d, %d, %d”, 5, NumClients, 6 + 3); 5, 123, 9 The DOS window uses a non-proportional font. Each character uses the exact same amount of horizontal space. Courier New is an example of a non-proportional font. Click Tip
  • 19. 19 The printf placeholders may include formatting options. Required type% Optional Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 [flags] [width] [.prec] [hlL] type%
  • 20. 20 http://www.cplusplus.com/reference/clibrary/cstdio/printf.html In your textbook, see Table 12.2 "Placeholders for printf format strings" The following link is also very helpful. Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 [flags] [width] [.prec] [hlL]% type [flags] The most common flag is the minus sign, -. It reverses the normal left/right alignment. Normal for text is left aligned, normal for numeric data is right aligned. [width] The width specifies the MINIMUM number of characters to be displayed. If the value requires fewer characters, the width is padded with blank spaces. If the value requires more characters, all the characters are output using a greater width. The specified width is a MINIMUM. For numeric types, the width specifer includes space for the digits (both right and left of the decimal point) and the decimal point itself. [.prec] The precision option specifies the exact number of digits to display to the right of the decimal point. These digits count as part of the width. [hlL] Also referred to as the length option, this indicates a modification of the data type as short or long.
  • 21. 21 Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 printf(“Average cost: %-8.3f !” , 3.4); printf(“ ***%-10.4f***”, 12.333); printf(“ ***%10.1f***”, 12.333); *** 12.3*** Average cost: 3.400 ! ***12.3330 *** printf(“%5s%10sn”, "ID","Amount"); printf(“n%5d%10.2f”, 1,12.15); printf(“n%5d%10.2f”, 2,1.6); printf(“n%5d%10.2f”, 3,4500.5); printf(“n%5d%10.2f”, 4,1234567890.0123); printf(“n%5d%10.2f”, 5,16.367); ID Amount 1 12.15 2 1.60 3 4500.50 41234567890.01 5 16.37 What is the result of each of the following statements? (Click each button to check your answer.) Make sure you understand why the row for ID 4 is out of line with the others. Send me an email telling me how you would correct the problem.