#include #include /* Demonstration of printf(). Compiles on a UNIX system using: gcc -lm -Wall -o C-examples-4 C-examples-4.C Execute from the shell using "C-examples-4" or "./C-examples-4". */ int main(int argc, char** argv) { /* Announce that this begins the formatted output section. */ printf("--------------------------\n"); printf("Formatted output examples:\n\n"); /* Integers are interpolated using "%d". */ printf("A leap year occurs every %d years.\n", 4); /* Strings are interpolated using "%s". */ printf("Every %s years is a leap year.\n", "four"); /* Decimal numbers are interpolated using "%f". */ printf("Pi is approximately equal to %f.\n", 4 * atan(1)); /* The width can be specified by placing an integer between "%" and "d". This is useful for making nice looking tables. By default the numbers are right justified. */ printf("\nRight justified integers using 4d:\n"); printf("%4d\n", 365); printf("%4d\n", 365 / 4); printf("%4d\n", 365 * 4); /* We can also left justify. */ printf("\nLeft justified integers using -4d:\n"); printf("%-4d\n", 365); printf("%-4d\n", 365 / 4); printf("%-4d\n", 365 * 4); /* Occasionally it is useful to pad the left end of the string with zeros. */ printf("\nPadded on the left with zeros to make a field with width 7:\n"); printf("%07d\n", 365); /* For tabular output, decimal numbers can be displayed as %w.df, where d and w are integers specifying the the total field width (w) and the number of digits to the right of the decimal point (d). */ printf("\nDecimal output using 12.4f:\n"); printf("%12.4f\n", 4 * atan(1)); printf("%12.4f\n", log(371)); /* An example using two arguments. */ printf("\nInterpolation of two values:\n"); printf("Each year has %d days, except for leap years which have %d days.\n", 365, 365 - 1); /* An example using tabs. */ printf("\nTabs:\n"); printf("%4d\t%4d\t%4d\t%4d\n", 2, 2*2, 2*2*2, 2*2*2*2); /* A series of strings separated by whitespace are automatically joined. */ printf("\nConcatenated strings in the source code:\n"); printf("Each year has %d days, except for leap " "years, occuring every %s years, " "which have only %d days.\n", 365, "four", 365 - 1); /* A literal percent sign ("%") is given by "%%". */ printf("\nLiteral percent signs:\n"); printf("The Michigan sales tax rate is 6%%.\n"); printf("The Michigan sales tax rate is %d%%.\n", 6); printf("\nEnd of formatted output examples.\n"); printf("---------------------------------\n\n"); return 0; }