CS 125 Lecture 9 Martin van Bommel
Output printf used to display integers, reals (floats and doubles), and strings printf(” control string ”, exp 1, exp 2,…) printf(”Measurement is ”); printf(”%d ft %d in\n”,feet,inch);
Format Codes FormatPurpose %d Decimal Integer %f Floating point %lf Double (Long float) %e Exponential (d.dddddde xx) %g General (uses shorter of %lf or %g ) %s String % Percent Sign
Formatted Output Need to align numbers in columns NameNumberSalary John Joan Field width - number of positions for value Alignment - left or right aligned Precision - number of digits beyond decimal
Formatted printf printf(”%sw.pf”, variable ); s - sign for alignment (none=right, - =left) w - field width - number of characters used (padded with blanks) p - precision - digits after decimal f - format code ( d,f,e,g,s)
Format Example NameNumberSalary John Joan printf(”%-8s%5d%10.2f”,n,m,s);
Crafting a Program Use comments to tell readers what they need to know, including difficult code Use indentation to show bodies of loops Use meaningful names Use convention for names - lastNumber Use standard idioms when appropriate Avoid unnecessary complexity
Designing for Change #define construct - symbolic constants #define symbol value symbol - name for symbolic constant value - replaces symbol in precompilation Why? Easier to modify program