View
216
Download
2
Category
Preview:
Citation preview
A simple C program: Printing a line of text
#include <stdio.h>
main()
{
printf(“hello, world\n”);
}
Program output:hello, world
More C programs
#include <stdio.h>
main()
{
printf(“My first program.\n”);
printf(“It is wonderful.”);
}
Program output:
My first program.
It is wonderful.
More C programs
#include <stdio.h>
main()
{
printf(“My first program.”);
printf(“It is wonderful.”);
}
Program output:
My first program.It is wonderful.
Printing characters
Source program:printf(“Welcome\nto\nCOMP 1180!\n”);
Program output:Welcome
to
COMP 1180!
You can use printf to print a string of characters;
but there are special cases:
• For double quote, use \”
• For single quote, use \’
• For backslash, use \\
• For newline, use \n
Formatted Output (integer,float,char,string)• Almost every C program start with the following:
#include <stdio.h>
for the access to the standard input/output library
• For the “printf” statement:printf(format-string, arg1, arg2, ...);
• Format-string tells the program how to print the arguments out
• Format-string contains two types of objects: ordinary characters and conversion specifications
• Each conversion specification begins with a % and ends with a conversion character and maybe have a minus sign, a number, and a period in between
Basic Printf Conversions
%d %i integer
%o octal (Base 8)
%x %X hexadecimal (Base 16)
%f floating point
%e %E floating point (exponent)
%g %G floating point (general format)
%c single character
%s character string
%% print a %
Examples on Formatted Printf Statementsint a = 5; int b = 10; 123456789012345
printf(“%d\n”, a); 5
printf(“%5d\n”, a); 5
printf(“%5d\n”, b); 10
printf(“%d %d\n”, a, b); 5 10
printf(“a = %d b = %3d\n”, a, b); a = 5 b = 10
float x = 33.3456789; 123456789012345
printf(“%f\n”, x); 33.345679
printf(“%e\n”, x); 3.33457e+01
printf(“%8.3f\n”, x); 33.346
x = 0.3334567;
printf(“%e\n”, x); 3.33457e-01
More Examples on Printf (strings)
printf(“%s”, “hello, world”); hello, world:
printf(“%10s”, “hello, world”); hello, world:
printf(“%.10s”, “hello, world”); hello, wor:
printf(“%-10s”, “hello, world”); hello, world:
printf(“%.15s”, “hello, world”); hello, world:
printf(“%-15s”, “hello, world”); hello, world :
printf(“%15.10s”, “hello, world”); hello, wor:
printf(“%-15.10s”, “hello, world”); hello, wor :
Formatted Input
• For “scanf” statements,scanf(format-string, addr1, addr2, ...);
• Examples:float f;
int lower, upper;
char ch;
scanf(“%f”, &fahr);
scanf(“%d%d”, &lower, &upper);
scanf(“%c”, ch);
ch = getchar(); get the next character from STDIN
putchar(ch); put the character to STDOUT
Recommended