Input and Output statements in C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

INPUT/OUTPUT STATEMENTS IN C

A stream is the source of data as well as the destination of data. Streams are associated with a physical
device such as a monitor or a file stored on the secondary memory. C uses two forms of streams—text and
binary, as shown below,

In a text stream, sequence of characters is divided into lines with each line being
terminated with a newline character (\n).
A binary stream contains data values using their memory representation.

We can take input/output from the keyboard/monitor or from any file but assume
that the source of data is the keyboard and destination of the data is the monitor.

FORMATTING INPUT/OUTPUT

 C language supports two formatting functions printf and scanf.


 printf is used to convert data stored in the program into a text stream for output
to the monitor, and scanf is used to convert the text stream coming from the
keyboard to data values and stores them in program variables.
printf():
 The printf function (stands for print formatting) is used to display information
required by the user and also prints the values of the variables.
 For this, the printf function takes data values, converts them to a text stream using
formatting specifications in the control string and passes the resulting text stream
to the standard output.
 The control string may contain zero or more conversion specifications, textual
data, and control characters to be displayed.
 Each data value to be formatted into the text stream is described using a separate
conversion specification in the control string. The specification in the control
string describes the data value’s type, size and specific control infomation as
shown below,

There are various forms of printf statements.


Method 1:
Syntax: printf(“ control string”);
Control string may be any character. The characters included within the double
quotes will be displayed on the output screen
Example:
printf(“Welcome to India”);
Output:
Welcome to India
Method 2:
Syntax: printf(“ control string”, variable list);
 Control string also called as format string.
 Control string consist of control specifier of particular data type
 Control Specifiers starts with % sign followed by conversion code.
 Variable list are the variable names separated by comma.
 Number of format specifiers must be equal to number of variables.
 While specifying the variables name make sure that it matches to the format
specifiers with in the double quotes.
 The control characters can also be included in the printf statement. These
control characters include \n, \t, \r, \a, etc.

Example: int a=10;


float b=20;
printf(“ integer =%d, floating=%f”,a,b);
Output:
integer=10, floating=20.00000

The prototype of the control string can be given as follows.


%[flags][width][.precision][length modifier]

type specifier

Each control string must begin with a % sign. The % character specifies how the next
variable in the list of variables has to be printed. After % sign follows:
 Flags is an optional argument which specifies output justification such as
numerical sign, trailing zeros or octal, decimal, or hexadecimal prefixes.
 Width is an optional argument which specifies the minimum number of
positions in the output.
 Precision is an optional argument which specifies the maximum number of
characters to print.
Format Specifiers:
Format specifiers are the character string with % sign followed with a character. It
specifies the type of data that is being processed. It is also called conversion specifier.
When data is being output or input it must be specified with identifier (variable) and
their format specifier.

Format Specifier Type

%c Character

%d Signed integer

%e or %E Scientific notation of floats

%f Float values

%g or %G Similar as %e or %E

%hi Signed integer (short)

%hu Unsigned Integer (short)

%i Unsigned integer

%l or %ld or %li Long

%lf Double

%Lf Long double

%lu Unsigned int or unsigned long

%lli or %lld Long long

%llu Unsigned long long

%o Octal representation

%p Pointer

%s String

%u Unsigned int

%x or %X Hexadecimal representation
#include <stdio.h>
void main()
{
//printing character data
char ch = 'B';
printf("%c", ch);
//print decimal or integer data with d and i
int x = 45, y = 90;
printf("%d", x);
printf("%i", y);
//print float value
float f = 12.67;
printf("%f", f);
//print in scientific notation
printf("%e", f);
//print in octal format
int a = 67;
printf("%o", a);
//print in hexdecimal format
printf("%x", a);
//to print string
char str[] = "Hello World";
printf("%s", str);
//shift to the right 20 characters including the string i.e right align (default)
printf("%20s", str);
//left align
printf("%-20s", str);
//shift to the right 20 characters including the string, and print string up to 5 character
printf("%20.5s", str);
//left align and print string up to 5 character
printf("%-20.5s", str);
}
Output:
B
45
90
12.670000
1.267000e+001
103
43
Hello World
Hello World
Hello World
Hello
Hello
scanf()

The scanf() function stands for scan formatting and is used to read formatted data
from the keyboard.

The scanf function takes a text stream from the keyboard, extracts and formats data
from the stream according to a format control string and then stores the data in
specified program variables.

The syntax of the scanf() function can be given as:

scanf("control string", arg1, arg2, arg3, ………….argn);

The control string specifies the type and format of the data that has to be obtained
from the keyboard and stored in the memory locations pointed by arguments arg1,
arg2,…, argn, i.e., the arguments are actually the variable addresses where each piece
of data is to be stored.

The prototype of the control string can be given as:

%[*][width][modifier]type

Here * is an optional argument that suppresses assignment of the input field, i.e., it
indicates that data should be read from the stream but ignored (not stored in the
memory location).

Width is an optional argument that specifies the maximum number of characters to


be read.

Modifier is an optional argument that can be h, l, or L for the data pointed by the
corresponding additional arguments. Modifier h is used for short int or unsigned
short int, l is used for long int, unsigned long int, or double values. Finally, L is used
for long double data values. Type specifies the type of data that has to be read. It also
indicates how this data is expected to be read from the user.
The scanf function ignores any blank spaces, tabs, and newlines entered by the user.
The function simply returns the number of input fields successfully scanned and
stored. the scanf function is used to store values in memory locations associated with
variables. For this, the function should have the address of the variables. The address
of the variable is denoted by an ‘&’ sign followed by the name of the variable.

The rules to be followed for scanf function in C programs.


Rule 1: The scanf function works until:
(a) the maximum number of characters has been processed,
(b) a white space character is encountered, or
(c) an error is detected.
Rule 2: Every variable that has to be processed must have a conversion specification
associated with it. Therefore, the following scanf statement will generate an error as
num3 has no conversion specification associated with it.
scanf("%d %d", &num1, &num2, &num3);
Rule 3: There must be a variable address for each conversion specification.
Therefore, the following scanf statement will generate an error as no variable address
is given for the third conversion specification.
scanf("%d %d %d", &num1, &num2); Remember that the ampersand operator (&)
before each variable name specifies the address of that variable name.
Rule 4: An error will be generated if the format string is ended with a white space
character. Rule 5: The data entered by the user must match the character specified in
the control string (except white space or a conversion specification), otherwise an
error will be generated and scanf will stop its processing.
For example, consider the following scanf statement.
scanf("%d/ %d", &num1, &num2); Here, the slash in the control string is neither a
white space character nor a part of conversion specification, so the users must enter
data of the form 21/46.
Rule 6: Input data values must be separated by spaces.
Rule 7: Any unread data value will be considered as a part of the data input in the
next call to scanf. Rule 8: When the field width specifier is used, it should be large
enough to contain the input data size.
Example: Variables of different data types in one single statement.
int num;
float fnum;
char ch;
scanf("%d %f %c ", &num, &fnum, &ch);
Example for both printf() and scanf():
int num;
float fnum;
char ch;
double dnum;
short snum;
long int lnum;
printf("\n Enter the values: \n");
scanf("%d %f %c %s %e %hd %ld", &num, &fnum, &ch, &dnum, &snum, &lnum);
printf("\n num = %d \n fnum = %.2f \n ch = %c \n dnum = %e \n snum = %hd \n
lnum = %ld", num, fnum, ch, dnum, snum, lnum);

You might also like