Download presentation
Presentation is loading. Please wait.
Published byAshlee Barnett Modified over 9 years ago
1
A simple C program: Printing a line of text #include main() { printf(“hello, world\n”); } Program output: hello, world
2
More C programs #include main() { printf(“My first program.\n”); printf(“It is wonderful.”); } Program output: My first program. It is wonderful.
3
More C programs #include main() { printf(“My first program.”); printf(“It is wonderful.”); } Program output: My first program.It is wonderful.
4
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
5
Formatted Output (integer,float,char,string) Almost every C program start with the following: #include 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
6
Basic Printf Conversions %d%iinteger %ooctal (Base 8) %x%Xhexadecimal (Base 16) %ffloating point %e%Efloating point (exponent) %g%Gfloating point (general format) %csingle character %scharacter string %print a %
7
Examples on Formatted Printf Statements int 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
8
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 :
9
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.