You are on page 1of 10

COM101B

LECTURE 4: INPUT & OUTPUT


ASST. PROF. DR. HACER YALIM KELEŞ

REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST


PUBLISHING CO., 1992
• C does not provide language constructs for input/output operations.
• However, ANSI C has defined a rich standard I/O library:
• a set of functions designed to provide a standard I/O system for C programs.
• We will study some subset of this library:
• printf: used for output operations
• scanf: used for input operations
• A program that uses I/O functions needs to include <stdio.h>:
• #include <stdio.h>

REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992
Example:
printf(«%c»,’C’);
results in:
>C
• Here > represent the output prompt.

REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992
PRINTF FUNCTION
The printf statement:
int i = 1;
printf(«%d\n», 2*i);
results in:
>2

The printf statement:


float r = 100.0;
printf(«\n%f\t%e», r, 100.0);
results in:
>100.000000 1.000000e+002

REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992
PRINTF FUNCTION

• The printf statement:


• float c = -11.428572;
• printf(«%f Cent = %f %s\n», c, 1.8*c+32, «Fahr»);

>-11.428572 Cent = 11.428571 Fahr

REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992
PRINTF FUNCTION

• The blank characters in the control string are significant:


printf(«1 2 3 4 end\n»);
>1 2 3 4 end

REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992
FORMAT SPECIFIERS

REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992
SCANF FUNCTION

• It is the input analog of the printf function


• scanf(control string, arg1, arg2,...);
• The control string contains conversion specifications.
• The scanf function reads one data item from the input corresponding to each argument
other than the control string
• skipping the whitespaces including newlines to find the next data item, and returns the total
number of arguments that are successfully read.

• It returns EOF (End Of File) when the end of the input is reached.
REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992
CONVERSION CONTROL CHARS

REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992
SCANF FUNCTION

Example:
int i;
float f1, f2;
char c1, c2;
Input: 10 1.0e1 10.0pc
Statement: scanf(«%d %f %e %c %c»,&i,&f1,&f2,&c1,&c2);
results in: i = 10; f1=10.000000; f2=10.000000; c1=‘p’; c2=‘c’
REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO., 1992

You might also like