You are on page 1of 48

Input / Output

S.Vaishnavi Programming for Problem solving 1


Input/Output

 All input and output is performed with streams in C.


 stream is a sequence of characters flowing from one place to another.
It is associated with a physical device, such as a terminal , or with a file
stored in auxiliary memory.
 input stream: data flows from input device (keyboard, file, etc) into
memory
 output stream: data flows from memory to output device (monitor, file,
printer, etc)
 There are two types of streams in C:
• Text streams
• Binary streams.
 A text stream consists of a sequence of characters divided into lines
with each line terminated by a newline ( \ n ).
 A binary stream consists of a sequence of data values such as integer,
real, or complex using their memory representation.

S.Vaishnavi Programming for Problem solving 2


 A terminal can be associated only with a text stream because a
keyboard only send a stream of characters into a program and a
monitor can only can display a sequence of characters.
 A file, on the other hand can he associated with a text or binary
stream .
 In C , keyboard is the standard input and the monitor is known
as standard output.

S.Vaishnavi Programming for Problem solving 3


Formatting Input/Output
 These text streams often represent different data types, such as
integer, real, and Boolean.
 The C language provides two formatting functions: printf for
output formatting and scanf for input formatting.
 The printf function converts data stored in the program into a text
stream for output to the monitor;
 The scanf function converts the text stream coming from the
keyboard to data values and stores them in pro- gram variables.
 In other words, the printf and scanf functions are data to text
stream and text stream to data converters.

S.Vaishnavi Programming for Problem solving 4


Output Formatting: printf( )
 The printf function takes a set of data values, converts them to a
text stream using formattting instructions contained in format
control string and sends the resulting text stream to the standard
output.

Output Formatting concept

An integer 234 stored in the program is converted to a text


stream of three numeric ASCII characters (‘2’,’3’,’4’) and then is
sent to the monitor.

S.Vaishnavi Programming for Problem solving 5


we supply the following information to the print function:
1 . The format control string including any textual data to be inserted
into the text stream.
2. A set of zero or more data values to he formatted.

 Each data value to be formatted into the text stream is described as a


separate conversion specification in the control string.
 The specifications describe the data values’ type, size, and specific
format information, such as how wide the display width should be.
 The location of the conversion specification within the format control
string determines its position within the text stream.
 In addition we can also print control characters , such as tabs ( \ t ) ,
newlines ( \ n ), and alerts ( \ a ), by including them in the format
string.
 The control string and data values are passed to the printf as
parameters, the control string as the first parameter and one
parameter for each value to be printed,

S.Vaishnavi Programming for Problem solving 6


Coversion
specifiers

Textual Data

Figure ( a ) shows the format string and the data values as parameters for the print
function. Figure (b) shows the formatting operation and the resulting text stream.

S.Vaishnavi Programming for Problem solving 7


Conversion Specification
 To insert data into the stream, we use a conversion specification
that contains a start token (% ), a conversion code, and up to four
optional modifiers as shown in Figure
 Only the field-specification token ( % ) and the conversion code
are required .

 The size modifier is used to modify the type specified by the


conversion code.
 There are four different sizes: h, l ( el ), ll ( el el ) , and L.
• The h is used with the integer codes to indicate a short integer value
• The l is used to indicate a long integer value.
• The ll is used to indicate a long long integer value.
 The L is used with floating-point numbers to indicate a long double value.

S.Vaishnavi Programming for Problem solving 8


 A width modifier may be used to specify the minimum number of
positions in the output. ( If the data require using more space
than we allow, then printf overrides the width.)
 If we don’t use a width modifier, each output value will take just
enough room for the data.

 If a floating- point number is being printed , then we may specify


the number of decimal places to he printed with the precision
modifier.
 The precision modifier has the format . m
 where m is the number of decimal digits.
 If no precision is specified , printf prints six decimal positions.
These six decimal positions are often more than is necessary.
 When both width and precision are used, the width must he large
enough to contain the integral value of the number, the decimal
point , and the number of digits in the decimal position.
53.25

S.Vaishnavi Programming for Problem solving 9


 The flag modifier is used for four print modifications
justification
Padding
Sign
Conversion variants
 Justification controls the placement of a the specified width,
justification can be left or right. If there is no flag and the defined
width is larger than required , the value is right justified .
 The default is right justification. To left justify a value, the flag is set
to minus (-).
 Padding defines the character that fills the unused space when the
value is smaller than the print width. It can be a space, the default ,
or zero.
 If there is no flag defined for padding, the unused width is filled with
spaces; if the flag is 0, the unused width is filled with zeroes.
 Note that the zero flag is ignored if it is used with left justification
because adding zeros after a number changes its value.

S.Vaishnavi Programming for Problem solving 10


 The sign flag defines the use or absence of a sign in a numeric
value.
 We can specify one of three formats: default formatting, print
signed values, or prefix positive values with a leading space.
 Default formatting inserts a sign only when the value is negative.
Positive values are formatted without a sign.
 When the flag is set to a plus ( +) , signs are printed for both
positive and negative values.
 If the flag is a space, then positive numbers are printed with a
leading space and negative numbers with a minus sign .

S.Vaishnavi Programming for Problem solving 11


S.Vaishnavi Programming for Problem solving 12
Output Examples

1. printf("%d%c%f " , 23 , 'z' , 4.1 );

2. printf( "%d %c %f", 23, 'z * , 4.1 );

3. int numl = 23;


char zee = 'z ';
float num2 = 4.1;
printf( " %d %c %f ", numl, zee, num2);

4. printf( " %d \t%c\t%5.If \n", 23, ' Z' , 14.2);


Prinf(“%d
printf( " %d \", 1754, 'F', 122.0);
printf( "%d\t%c\t%5.If\n", 3 , 'P', 0.1 );

5. printf("The number%dis my favorite number." , 23);

S.Vaishnavi Programming for Problem solving 13


7. printf("The tax is %6 .2f this year." , 233.12);
The tax is 233.12 this year.

8. printf("The tax is %8.2f this year." , 233.12);

9. printf("The tax is %08.2f this year.", 233.12);

10. printf("\"%8c %d\ " ", 'h', 23);

S.Vaishnavi Programming for Problem solving 14


Input Formatting: scanf
 The standard input formatting function in C is scanf (scan
formatting .
 This 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.
 For example , the stream of 5 characters ‘2’, ‘3’ ,'4', ‘.’, and ‘2’ are
extracted as the real 234.2

S.Vaishnavi Programming for Problem solving 15


The scanf function is the reverse of the printf function.

1 . A format control string describes the data to be extracted from the


stream and reformatted .
2. Rather than data values as in the printf function , scanf requires the
variable addresses where each piece of data are to be stored . Unlike
the printf function , the destination of the data items cannot be literal
values, they must store in the variables.
3. With the exception of the character specification , leading white
spaces are discarded.
4.Any non conversion specification characters in the format string must
be exactly matched by the next characters in the input stream .

S.Vaishnavi Programming for Problem solving 16


scanf

Figure demonstrates the input format string concept with a control string
having two fields (%c and %f ) . The first one defines that a character will he
inserted here ; the second defines that a real will be inserted there.

S.Vaishnavi Programming for Problem solving 17


Conversion Specification
 To format data from the input stream, we use a conversion
specification that contains a start token (% ), a conversion code,
and up to three optional modifiers as shown in Figure.
 Only the field-specification token ( % ) and the conversion code
are required.

 There are only three differences between the conversion codes for
input formatting and output formatting.
 First, there is no precision in an input conversion specification. It is an
error to include a precision.
 There is only one flag for input formatting, the assignment
suppression flag (*). The assignment suppression flag tells scanf that
the next input field is to be read but not stored. It is discarded.
S.Vaishnavi Programming for Problem solving 18
 The third difference is the width specification ; with input formatting
it is a maximum, not a minimum width. Input Parameters
 For every conversion specification there must be a matching
variable in the address list.
 Addresses are indicated by prefixing the variable name with an
ampersand ( & ).
 If the user signals that there is no more input by keying end of file
( EOF ) , then scanf terminates the input process.
 if scanf encounters an invalid character when it is trying to convert
the input to the stored data type, it stops.

S.Vaishnavi Programming for Problem solving 19


Scanf rules

S.Vaishnavi Programming for Problem solving 20


Input Examples

34 56 +
Scanf(“%d%d %c”,&n1,&n2,&op);

S.Vaishnavi Programming for Problem solving 21


OPERATORS

S.Vaishnavi Programming for Problem solving 22


 Operators are symbols (syntactical tokens) which take one or
more operands or expressions and perform arithmetic or logical
computations(actions). 

 Operands are variables or expressions which are used in


conjunction with operators to evaluate the expression.It is an object
on which an operation is performed.

 Expressions are sequences of operators, operands, and


punctuators that specify a computation

operands

2+3

operator
S.Vaishnavi Programming for Problem solving 23
An operator is a symbol that tells the compiler to perform specific
mathematical or logical functions. C language is rich in built-in
operators and provides the following types of operators −
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

S.Vaishnavi Programming for Problem solving 24


Arithmetic Operators
The following table shows all the arithmetic operators supported by
the C language. Assume variable A holds 10 and variable B holds 20
then
Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an B%A=0


integer division.

++ Increment operator increases the integer A++ = 11 (A=A+1),++A


value by one.

-- Decrement operator decreases the integer A-- = 9 (A=A-1), --A


value by one.

S.Vaishnavi Programming for Problem solving 25


Relational Operators
The following table shows all the relational operators supported by
C. Assume variable A holds 10 and variable B holds 20 then
Operator Description Example

== Checks if the values of two operands are equal or not. If yes, (A == B) is not true.
then the condition becomes true.

!= Checks if the values of two operands are equal or not. If the (A != B) is true.
values are not equal, then the condition becomes true.

>  Checks if the value of left operand is greater than the value (A > B) is not true.
of right operand. If yes, then the condition becomes true.

<  Checks if the value of left operand is less than the value of (A < B) is true.
right operand. If yes, then the condition becomes true.

>= Checks if the value of left operand is greater than or equal to (A >= B) is not true.
the value of right operand. If yes, then the condition
becomes true.

<= Checks if the value of left operand is less than or equal to (A <= B) is true.
the value of right operand. If yes, then the condition
becomes true.

S.Vaishnavi Programming for Problem solving 26


Logical Operators
Following table shows all the logical operators supported by C
language. Assume variable A holds 1 and variable B holds 0, then
Operator Description Example

T T—T
&& Called Logical AND operator. If both the (A && B) is false.
TF –T
operands are non-zero, then the condition
becomes true. F T –T
F F –F
| Called Logical OR Operator. If any of the two (A || B) is true.
operands is non-zero, then the condition
becomes true.

Called Logical NOT Operator. It is used to !(A && B) is true.


reverse the logical state of its operand. If a T—F
condition is true, then Logical NOT operator will F--T
make it false.

S.Vaishnavi Programming for Problem solving 27


Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The
truth tables for &, |, and ^ is as follows
p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −


A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
S.Vaishnavi Programming for Problem solving 28
The following table lists the bitwise operators supported by C.
Assume variable 'A' holds 60 and variable 'B' holds 13, then
Operat Description Example
or

& Binary AND Operator copies a bit to the result if it (A & B) = 12, i.e., 0000 1100
exists in both operands.

| Binary OR Operator copies a bit if it exists in either (A | B) = 61, i.e., 0011 1101
operand.

^ Binary XOR Operator copies the bit if it is set in (A ^ B) = 49, i.e., 0011 0001
one operand but not both.

~ Binary One's Complement Operator is unary and (~A ) = ~(60), i.e,. -0111101
has the effect of 'flipping' bits.

<<  Binary Left Shift Operator. The left operands value


is moved left by the number of bits specified by the A << 2 = 240 i.e., 1111 0000
right operand.

>>  Binary Right Shift Operator. The left operands


value is moved right by the number of bits specified A >> 2 = 15 i.e., 0000 1111
by the right operand.

S.Vaishnavi Programming for Problem solving 29


4=a;X
60 – 0 13—1
A=4;
30 –0 6 –0
15—1 3—1 256
7 –1 1—1 015
3 –1 0
1 –1
0 13=0000 1101

60=0011 1100
00111100=60
01111000=120
11110000=240
A 0 0 1 1 1 1 0 0 60
B 0 0 0 0 1 1 0 1 13
A&B 0 0 0 0 1 1 0 0 12 00111100=60
00011110=30
A|B 0 0 1 1 1 1 0 1 61 00001111=15
A^B 0 0 1 1 0 0 0 1 49 00000111=7
A<<2 1 1 1 1 0 0 0 0 240 00000011=3

A>>2 0 0 0 0 1 1 1 1 15
Assignment Operators
The following table lists the assignment operators supported by the C
language

Opera Description Example


tor
= Simple assignment operator. Assigns values from right side C = A + B will assign the value of
operands to left side operand A + B to C
+= Add AND assignment operator. It adds the right operand to
C += A is equivalent to C = C + A
the left operand and assign the result to the left operand.
-= Subtract AND assignment operator. It subtracts the right
operand from the left operand and assigns the result to the C -= A is equivalent to C = C - A
left operand.
*= Multiply AND assignment operator. It multiplies the right
operand with the left operand and assigns the result to the C *= A is equivalent to C = C * A
left operand.
/= Divide AND assignment operator. It divides the left operand
with the right operand and assigns the result to the left C /= A is equivalent to C = C / A
operand.

S.Vaishnavi Programming for Problem solving 31


%= Modulus AND assignment operator. It
takes modulus using two operands and
C %= A is equivalent to C = C %
assigns the result to the left operand.
A

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2


operator.

|= Bitwise inclusive OR and assignment C |= 2 is same as C = C | 2


operator.

S.Vaishnavi Programming for Problem solving 32


Misc Operators ↦ sizeof & ternary
Besides the operators discussed above, there are a few other
important operators including sizeof and ? : supported by the C
Language.

Operator Description Example

sizeof() Returns the size of a sizeof(a), where a is integer, will return 4.


variable.

& Returns the address of a &a; returns the actual address of the
variable. variable.

* Pointer to a variable. *a;

?: Conditional If Condition is true ? then value X :


Expression.Ternary operator otherwise value Y

S.Vaishnavi Programming for Problem solving 33


 An expression is any valid set of literals, variables, operators,
operands and expressions that evaluates to a single value.
 This value can be a number, a string or a logical value.

 Expressions can be simple or complex


 A simple expression contains only one operator.Ex: 2+5
 A complex expression contains more than one operator.
 For instance a = b + c /d; denotes an expression in which there are
4 operands a, b, c,d and two operator + and =.

 A statement, the smallest independent computational unit,


specifies an action to be performed.In most cases, statements are
executed in sequence.

 The number of operands of an operator is called its arity.Based on


arity, operators are classified as nullary (no operands), unary (1
operand), binary (2 operands), ternary (3 operands).

S.Vaishnavi Programming for Problem solving 34


 The order in which the operators in a complex expression are
evaluated is determined by a set of priorities known as precedence
 Associativity is the parsing direction used to evaluate an
expression If two operators with the same precedence

S.Vaishnavi Programming for Problem solving 35


Primary Expressions
 The most elementary type of expression is a primary expression.
 A primary expression consists of only one operand with no
operator.
 The operand in the primary expression can he a name, a
constant, or a parenthesized expression .
 Although a primary expression has no operator, the null operator
is there in this expression.
Names
 A name is any identifier for a variable, a function , or any other
object in the language. Ex:price, calc, SIZE, a , n1
Literal Constants
 a constant is a piece of data whose value can ’t change during
the execution of the program. Ex: 5, 123.98, ‘ A ‘ ,"Welcome“
Parenthetical Expressions
 Any value enclosed in parentheses must be reducible to a single
value and is therefore a primary expression . Ex: (2 * 3 + 4)
(a = 23 +b * 6 )

S.Vaishnavi Programming for Problem solving 36


Postfix Expressions
 The postfix expression consists of one operand followed by one
operator.
 The operand in a postfix expression must be a variable.

operand operator

Example:
• Function Call
sum(), area()

• Postfix Increment/Decrement (++,- -)


a++,a--

S.Vaishnavi Programming for Problem solving 37


Prefix Expressions

operator operand

Variable
 In prefix expressions, the operator comes before the operand
Example:
• prefix Increment/Decrement (++,- -)
++a, --a
 If ++ is after the operand, as in a++, the increment takes place after
the expression is evaluated. If ++ is before the operand , as in ++a,
the increment takes place before the expression is evaluated.

S.Vaishnavi Programming for Problem solving 38


Unary Expressions
 A unary expression, like a prefix expression, consist of one operator
and one operand.
 The prefix expression needs a variable as the operand while the
unary expression can have an expression or a variable as the
operand.
 Example:
 sizeof operator :The sixeof operator tells us the size in bytes of a
type or primary expression.
sizeof (int), sizeof (345.23), sizeof x
 plus/minus operators : +a, -a
 cast operator. The cast operator converts one expression type to
another
int x;
( float ) x

operator operand

S.Vaishnavi Programming for Problem solving 39


Binary Expressions
 Binary expressions are formed by an operand-operator-operand
combination.

Fig : Binary Expressions


• Multiplicative Expressions
multiplication(*) , division(/) , modulus(%)
• Additive Expressions
addition(+),subtraction(-)
• Relational Expressions
> , < ,== ,>= ,<= ,!=
• Logical Expressions
&& , || , ^
• Assignment Expressions
Simple Assignment(=)
• Compound Assignment(*=, /= , % =, +=)
 The left operand in an assignment expression must be a single
variable.
S.Vaishnavi Programming for Problem solving 40
Operators Precedence in C
 Operator precedence determines the grouping of terms in an
expression and decides how an expression is evaluated.
 Certain operators have higher precedence than others. for
example, the multiplication operator has a higher precedence than
the addition operator.
 For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because
operator * has a higher precedence than +, so it first gets
multiplied with 3*2 and then adds into 7.
 Here, operators with the highest precedence appear at the top of
the table, those with the lowest appear at the bottom. Within an
expression, higher precedence operators will be evaluated first.

• (2+(3*4))
• -b++ (if b=5)

S.Vaishnavi Programming for Problem solving 41


Precedence Table
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary/Prefix + - ! ~ ++ - - (type)* & Right to left
sizeof
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= Right to left
&= ^= |=
Comma , Left to right
S.Vaishnavi Programming for Problem solving 42
Associativity
 Associativity can be left-to-right or right-to-left.
 Left-to-right associativity evaluates the expression by starting on the
left and moving to the right. Conversely, right-to-left associativity
evaluates the expression by proceeding from the right to the left.
 Associativity is used only when the operators all have the same
precedence.
Left-to-right Associativity
3*8/4%4*5
is evaluated to 10

Right-to-left Associativity
a += b *= c -= 5
If a=3,b=5, c=8
then it is evaluated to 18

(a = 3 + (b = (5 * (c = 8 - 5)))

S.Vaishnavi Programming for Problem solving 43


 A side effect is an action that results from the evaluation of
an expression.

S.Vaishnavi Programming for Problem solving 44


Type Conversion
Implicit Type Conversion
 When the types of the two operands in a binary expression are
different, C automatically converts one type to another. This is
known as implicit type Conversion .
 In C, we can assign a rank to the integral and floating-point
arithmetic types.
 Promotion occurs if the right expression has lower rank; demotion
occurs if the right expression has a higher rank.

S.Vaishnavi Programming for Problem solving 45


 There is normally no problem with promotion. The rank of the right
expression is elevated to the rank of the left variable.

 Demotion may or may not create problems. If the size of the


variable at the left side can accommodate the value of the
expression.

S.Vaishnavi Programming for Problem solving 46


Explicit Type Conversion (Cast)
 Rather than let the compiler implicitly convert data, we can convert
data from one type to another our self using explicit type conversion.
 Explicit type conversion uses the unary cast operator.
 To cast data from one type to another, we specify the new type in
parentheses before the value we want converted.
 For example, to convert an integer, a, to float, we code the
expression shown below.
( float ) a

Ex: average =( float ) totalScores / numScores ;


if totalScores=73 and numScores=5 average=?

Ex: m=( float) ( a / 10 );


if a=8 then m=?

S.Vaishnavi Programming for Problem solving 47


S.Vaishnavi Programming for Problem solving 48

You might also like